如何在MySQL中从textareas插入多行

时间:2015-11-24 12:37:32

标签: php mysql insert-into

我无法从两个textarea(每一行)插入mysql,

首先这是一个add.html

<form id="form1" name="form1" method="post" action="func/insert.php">
<table>
<tr>
<td>text 1</td>
<td>:</td>
<td><textarea class="custom" rows="10" cols="80" name="text1" id="text1" required></textarea>
</td>
</tr>
<tr>
<td>text 2</td>
<td>:</td>
<td><textarea class="custom" rows="10" cols="80" name="text2" id="text2" required>
</textarea></td>
</tr>
</table>
</from>

然后插入.php

<?php
include"connection.php";
if(isset($_POST['text1'])){
if(strpos($_POST['text1'], "\n")){
$entrytext1 = explode("\n",$_POST['text1']);
}
else{
$entrytext1 = array($_POST['text1']);
}
foreach ($entrytext1 as $linetext1){
$sql="INSERT INTO data(text1,text2)VALUES('$linetext1','$_POST[text2]')";
$result=mysql_query($sql);
if ($result){
echo"<script>alert(\"Success ...\");window.location='../index.php'</script>";
}
else{
echo"<script>alert(\"Failed ...\");self.history.back()</script>";
}
}
}
?>

好吧,我从How to insert multiple rows from a textarea in MySQL

获得了参考资料

那么,我如何将textarea的每一行(text1和text2)放入MySQL行?请帮助我任何人

1 个答案:

答案 0 :(得分:0)

你有一些html错误以及不安全的查询执行。试试这个: 的 HTML

<form id="form1" name="form1" method="post" action="func/insert.php">
<table>
<tr>
<td>text 1</td>
<td>:</td>
<td><textarea class="custom" rows="10" cols="80" name="text1" id="text1" required></textarea></td>
</tr>
<tr>
<td>text 2</td>
<td>:</td>
<td><textarea class="custom" rows="10" cols="80" name="text2" id="text2" required>
</textarea></td>
</tr>
</table>
</form>

<强> PHP

include"connection.php";
if(isset($_POST['text1'])){
    if(strpos($_POST['text1'], "\n")){
        $entrytext1 = explode("\n",$_POST['text1']);
    }
    else{
        $entrytext1 = array($_POST['text1']);
    }
    foreach ($entrytext1 as $linetext1){
        $stmt = $mysqli->prepare("INSERT INTO data(text1,text2)VALUES(:text1, :text2)");
        $result = $stmt->execute(array('text1' => $linetext1, 'text2'    =>  $_POST['text2']));
        if ($result){
        echo"<script>alert(\"Success ...\");window.location='../index.php'</script>";
        }
        else{
            echo"<script>alert(\"Failed ...\");self.history.back()</script>";
        }
    }
}