问题
所以我的问题是我有一些PHP代码进入数据库并获取学生数据。然后程序将学生信息输出到屏幕上。信息放在input
内,因为用户可以编辑信息。当用户编辑信息并单击Update
时,我需要在数据库上更新信息。我的问题是我不知道如何遍历所有输入。
PHP代码 - 当用户点击Update
foreach ($_POST as $data) {
echo $data . "<br>";
}
PHP代码 - 允许用户编辑
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
echo "
<tr>
<td><input type='text' value='$studentID'></td>
<td><input type='text' value='$firstname'></td>
<td><input type='text' value='$lastname'></td>
<td><input type='text' value='$teacherFirstname'></td>
<td><input type='text' value='$teacherLastname'></td>
</tr>
";
}
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
答案 0 :(得分:0)
所以,我所做的是我使用一个变量来跟踪数据的行。
代码
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students ORDER BY studentID");
$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'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
echo "
<tr>
<td><input type='text' name='studentID-$value' value='$studentID'></td>
<td><input type='text' name='firstname-$value' value='$firstname'></td>
<td><input type='text' name='lastname-$value' value='$lastname'></td>
<td><input type='text' name='teacherFirst-$value' value='$teacherFirstname'></td>
<td><input type='text' name='teacherLast-$value' value='$teacherLastname'></td>
</tr>
";
}
// add to row
$value += 1;
}
?>