如何从相同的输入名称中保存多行值。
例如,我的php,html代码来自:
<form action="functions.php" method="post" name="grades">
<table>
<thead>
<tr>
<th>Subject</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<?php $unos = $baza->odradi("SELECT subject FROM subjects ORDER BY id ASC");
if (!empty($unos)) {
foreach($unos as $row=>$value){ ?>
<tr>
<td><input type="hidden" name="subject_id[]" value="<?= $unos[$row]["id"]; ?>"> <?= $unos[$row]["subject"]; ?></td>
<td>
<select class="form-control input-xs" name="grade_id[]" required>
<option selected disabled>Select grade</option>
<option value="5">excelent</option>
<option value="4">very good</option>
<option value="3">good</option>
<option value="2">ok</option>
<option value="1">bad</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" name="grades" class="btn btn-success btn-lg" value="Submit grades">
</form>
需要保存的函数如下所示:
if (isset($_POST['grades'])) {
foreach (array_combine($_POST['subject_id'], $_POST['grade_id']) as $i => $val){
$subject = $_POST["subject_id"][$i];
$grade = $_POST["grade_id"][$i];
$sql = "INSERT INTO final_grade (subject_id,grade_id) VALUES ('$subject','$grade')";
$u = mysqli_query($db, $sql);
}
但是一切都搞砸了,在前两行中没有保存成绩或主题,并且所有的行都完全丢失了。
答案 0 :(得分:0)
因为您正在调用array_combine()
,所以循环不再像$i
那样传递子数组索引。它以subject_id
的形式传递$i
,以grade_id
的形式传递$val
。您可能只是使用$i
和$val
作为要插入的值,而不是尝试使用$_POST
重新访问$i
数组。
更干净的脚本编写方法是将id用作每个<select>
上的硬编码元素键,而不是传递隐藏字段。
<?php
$options = [
5 => 'excellent',
4 => 'very good',
3 => 'good',
2 => 'ok',
1 => 'bad'
];
?>
<td><?= $unos[$row]["subject"]; ?></td>
<td><select class="form-control input-xs" name="grade[<?= $unos[$row]["id"]; ?>]" required>
<option disabled>Select grade</option>
<?php
foreach ($options as $opt_id => $opt_val) {
echo "<option value=\"{$opt_id}\">{$opt_val}</option>";
}
?>
</select>
</td>
然后,您可以简单地访问关联的提交。
if (isset($_POST['grade'])) {
// use prepared statement and bind variables
foreach ($_POST['grade'] as $id => $val) {
// execute prepared statement with each iteration
}
}
或者,您可以建立单批结果并执行一次INSERT(我可能会这样做)。
未经测试的建议:
$data = [];
foreach ($_POST['grade'] as $subject_id => $grade_id) {
array_push($data, $subject_id, $grade_id); // restructure as indexed 1-dim array for unpacking
}
$num_of_inserts = sizeof($data);
$placeholders = array_fill(0, $num_of_inserts, '(?,?)');
$value_types = str_repeat('i', $num_of_inserts * 2); // i is because you are passing integer values
// execute single batch of inserts
$query = "INSERT INTO final_grade (subject_id,grade_id) VALUES " . implode(',', $placeholders);
$stmt = $conn->prepare($query);
$stmt->bind_param($value_types, ...$data);
$stmt->execute();
事实是,您可以通过多种方式传递表单数据,也可以通过多种方式执行INSERT查询。我不会费心写出所有变体-做您喜欢的事...但是绝对要写稳定/安全的查询。