问题
所以,我有这个程序,允许用户编辑数据库中的学生信息。当单击提交按钮时,信息将进入数组,因此我可以轻松地遍历信息并将信息放入数据库。但是,问题是我不知道如何确定信息进入哪一列。
我当前的方法是使用变量来跟踪信息应该进入的列,但这不起作用。
我是我的HTML,我将学生信息放入输入中,因此用户可以编辑信息。
学生表
studentID | firstname | lastname | teacherID
1 | Bob | Roberts | 2
2 | Rick | Phil | 1
PHP表格
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher ID</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
?>
<tr>
<td>
<?php echo $studentID ?>
</td>
<td>
<input type='text' name='student[<?php echo $studentID ?>][firstname]' value='<?php echo $firstname ?>' />
</td>
<td>
<input type='text' name='student[<?php echo $studentID ?>][lastname]' value='<?php echo $lastname ?>' />
</td>
<td>
<input type='text' name='student[<?php echo $studentID ?>][teacherID]' value='<?php echo $teacherID ?>' />
</td>
</tr>
<?php
// add to row
$value += 1;
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
PHP代码进程的表单信息
$counter = 0; // keeps track of number of columns
// get data and loop through it
foreach ($_POST['student'] as $id => $data) {
foreach ($data as $d) {
if($counter > 1) {
$counter = 0;
update($counter, $link, $id, $d);
} else {
update($counter, $link, $id, $d);
}
}
}
function update($counter, $link, $id, $d) {
if($counter == 0) {
$update = $link->prepare("UPDATE students SET firstname = :firstname WHERE studentID = :id");
$update->execute(array(
"firstname" => $d,
"id" => $id
));
echo $counter . "<br>";
$counter++;
} else if($counter == 1) {
$update = $link->prepare("UPDATE students SET lastname = :lastname WHERE studentID = :id");
$update->execute(array(
"lastname" => $d,
"id" => $id
));
echo $counter . "<br>";
$counter++;
}
}
答案 0 :(得分:0)
问题是因为您的$ counter变量未作为引用传递。请尝试以下方法:
function update(&$counter, $link, $id, $d) {
之前,传递的变量总是等于0.当你递增它时,不会保存更改。使用&amp;参考时通过引用传递它会告诉PHP更新您最初发送的变量而不是新副本。
编辑:谢谢鲍勃!