gpt4 book ai didi

php - 使用多个数组时仅插入第一行数据

转载 作者:行者123 更新时间:2023-11-29 17:58:32 25 4
gpt4 key购买 nike

我在表单中使用了四个数组。虽然只使用 2 个数组,但它可以工作。但超过2个数组(如下形式)仅插入第一个学生的第一条记录。我尝试过使用多个foreach,但它不能解决问题。我的 PHP FORM 输出如下。

<form method="post" action="mark.php">
<table id="customers">
<tr>
<th>Name</th>
<th colspan="2"><input type="text" name="subjectid[]" value="Social"></th>
<th colspan="2"><input type="text" name="subjectid[]" value="Math"></th>
<th colspan="2"><input type="text" name="subjectid[]" value="English"></th>
</tr>
<tr>
<td><input type="text" name="stdname[]" value="John"></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

</tr>
<td><input type="text" name="stdname[]" value="Rahul"></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

<td><input type="number" name="theory[]" value=""></td>
<td><input type="number" name="practical[]" value=""></td>

</tr>
</table>
<input type="submit" name="submit1" value="submit"></input>
</form>

PHP 代码

<?php }
if(isset($_POST['submit1'])){
$subjectid = $_POST['subjectid'];
$theory = $_POST['theory'];
$practical = $_POST['practical'];
$stdname = $_POST['stdname'];

foreach ($theory AS $key => $item) {
$sql = "INSERT INTO mark(subjectid, theory, practical, stdname) VALUES (:subjectid, :theory, :practical, :stdname)";
$query = $con->prepare($sql);
$query->bindParam(':subjectid', $subjectid[$key]);
$query->bindParam(':theory', $theory[$key]);
$query->bindParam(':practical', $practical[$key]);
$query->bindParam(':stdname', $stdname[$key]);
$query->execute();
echo "<script>alert('Mark is inserted')</script>";
echo("<script>window.location = 'mark.php';</script>");
}
}
?>

插入以下输入时 enter image description here

它在数据库中存储为 enter image description here

但它必须存储为 enter image description here

最佳答案

看起来prepare正在使用最后一条语句进行缓存。你可能会写

$sql = "INSERT INTO mark(subjectid, theory, practical, stdname) VALUES (:subjectid, :theory, :practical, :stdname)";
$query = $con->prepare($sql);
foreach ($theory AS $key => $item) {

而不是

foreach ($theory AS $key => $item) {               
$sql = "INSERT INTO mark(subjectid, theory, practical, stdname) VALUES (:subjectid, :theory, :practical, :stdname)";
$query = $con->prepare($sql);
<小时/>

其他可能性可能会违反任何约束,您可能对任何列有唯一的键约束并尝试在循环中插入相同的值。您可以通过将以下代码行添加到您的代码中进行验证。

echo $query->error;

关于php - 使用多个数组时仅插入第一行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com