简体   繁体   中英

How to insert multiple rows from a textarea in MySQL

<html>
<form method="POST" action="insertlines.php">
<textarea name="url" rows="10" ></textarea>
<input type="submit" name="submit" value="Enter">
</form>
</html>

How can i put every single row of the textarea into a MySQL row ?

The thing I want is when I input:

John
Peter
Steven 

in the textarea, I want them in my database with different ids each.

You have to parse the text, looking for the "enter" character:

<?php
if(isset($_POST['url'])){
    if(strpos($_POST['url'], "\n")){
        $entries = explode("\n", $_POST['url']);
    } else {
        $entries = array($_POST['url']);
    }
    // connect to DB here
    // then iterate over entries
    foreach($entries as $e){
        // build some type of Prepared Statement to protect from SQL Injection
        $q = "INSERT INTO table (col1) VALUES (?)";
        // bind $e to statements
        // Execute SQL statements
    }
    // close DB connection
}
?>

Try this:

$textarea=$_POST['url']
$sql = 'INSERT INTO YourTable(field1,field2,name) VALUES';
foreach(explode("\n", $textarea) as $row) {
$sql.='("field1","field2",.'$row'.)';
} 
$conn->query($sql)

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