我想创建一个包含输入字段的表,可以插入学生记录。学生的姓名位于从数据库中获取的带有while循环的表的第一列。其他列包含用于输入学生分数的字段。我面临的挑战是如何将名为result_sec的表的不同行中的所有学生的记录插入到数据库中。我已经搜索了类似的帖子,但无法得到合适的答案。下面是代码。提前谢谢。
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);
if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
foreach($exes as $key => $exe)
{
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
}
$insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">
<table>
<thead>
<tr>
<th>Name</th>
<th>Ass.</th>
<th>Exe.</th>
<th>1st C.A.</th>
<th>2nd C.A.</th>
<th>Exam</th>
</tr>
</thead>
<tbody>
<?php do { ?>
<tr>
<td><?php echo $formdata['surname']." ".$formdata['firstname']; ?></td>
<td><input name="ass[]" size="1px"/></td>
<td><input name="exe[]" size="1px" /></td>
<td><input name="ca1[]" size="1px" /></td>
<td><input name="ca2[]" size="1px" /></td>
<td><input name="exam[]" size="1px" /></td>
<input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />
</tr>
<?php } while ($formdata = mysqli_fetch_assoc($form)); ?>
</tbody>
</table>
<button type="submit">Insert Student Record</button>
</form>
<?php require('footer.php'); ?>
答案 0 :(得分:1)
请参阅“如果这可以解决您的问题”
if(isset($_POST['submit'])){
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
//You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($exes as $i => $exe) {
$exee = mysqli_real_escape_string($exe);
$ass = mysqli_real_escape_string($asss[$i]);
$ca1 = mysqli_real_escape_string($ca1s[$i]);
$ca2 = mysqli_real_escape_string($ca2s[$i]);
$exam = mysqli_real_escape_string($exams[$i]);
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
$insert = mysqli_multi_query($conn, $sql);
}
}