How to insert multiple rows from a textarea in MyS

2019-06-11 22:20发布

问题:

<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.

回答1:

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
}
?>


回答2:

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)