简体   繁体   中英

Insert Multiple lines to database

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>

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 '\\n' seperate then:

$urlArr = explode("\n",$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM