douyun3799 2014-12-14 11:43
浏览 82
已采纳

将多行插入数据库

I need insert multiple line from text area insert in to each row of database. but now is insert all line in one row how i can do it? also i want echo finished line, and echo if line exit with warning

My text area input is :

line1
line2
line3
line4
line5

I want insert like this

id  url
1   line1
2   line2
3   line3
4   line4
5   line5

This is my insert.php

<html><body>
    <h1>indian mp3 Database: indianmp3</h1>

    <form action="post.php" method="post">
        Firstname:<textarea name="url" id="term" cols="40" rows="10"></textarea><br><br>
        Category: <select name="cat_id">
            <option value="1">cat1</option>
            <option value="2">cat2</option>
            <option value="3">cat3</option>
        </select>

        <input type="submit"/>
    </form>
</body></html>

This is my post.php

<html><body>
<?php
$host="localhost";
$user=" ";
$pass=" ";
$database=" ";
$con=mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_set_charset('UTF8', $con);
if(!$con) {
    die('Could not connect: '.mysql_error());
}

if(isset($_POST['cat_id'])) {
    $cat_it=(int)$_POST['cat_id'];
    $url=$_POST[url];
    mysql_select_db($database, $con) or die("Could not find database.");
    $sql="INSERT INTO link (url, cat_id) VALUES ('$url' , '$cat_it')";
}
if(!mysql_query($sql, $con)) {
    die('Error: '.mysql_error());
}
echo "inserted all line";
mysql_close($con)
?>
</body></html>
  • 写回答

1条回答 默认 最新

  • dsk49208 2014-12-14 11:49
    关注

    the problem here is you are making single insert with entire url data.

    1) first identify each url value from text area and make an array of it using explode with '.' or specific keyword.

    2) loop through the size of url array to insert into the table.

    while inserting check error on mysql object in error occurs exit otherwise keep on inserting till all insertion is done.

    suppose you have all urls in $url= $_POST[url]; with ' ' seperate then:

    $urlArr = explode("
    ",$url);
    
    for($i=0;$i< sizeof($urlArr);i++){
    $sql="INSERT INTO link (url, cat_id) VALUES ('$url[i]' , '$cat_it')";
    if (!mysql_query($sql,$con))
                      {
                      die('Error: ' . mysql_error());
                      }
    
    
    }
    

    and please start using PDO or mysqli.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?