How to insert multiple rows from a textarea in MySQL

只谈情不闲聊 提交于 2019-12-23 05:32:15

问题


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


来源:https://stackoverflow.com/questions/31925222/how-to-insert-multiple-rows-from-a-textarea-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!