【问题标题】:How to insert multiple row from textareas in MySQL如何从 MySQL 的 textareas 中插入多行
【发布时间】:2025-12-26 14:50:07
【问题描述】:

我无法从两个文本区域(每行)插入 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 行?请任何人帮助我

【问题讨论】:

  • 顺便说一句:MYsql 函数已被弃用。您有非常危险且可注入的查询。请使用 PDO。
  • 如果你说,1 个盒子里有 25 行,另一个盒子里有 3 行,会发生什么?

标签: php mysql insert-into


【解决方案1】:

您遇到了一些 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>";
        }
    }
}

【讨论】:

  • 致命错误:在非对象上调用成员函数prepare()
  • 你应该先在你的connection.php中从mysql迁移到mysqli,然后试试这个。