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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!