Problem
So, I have this program that allows the user to edit student info in the db. When the submit button is clicked on the info goes into an array, so I can easily loop through the info and put the info into the db. But, the problem is that I don't know how to figure out which column the info goes into.
My current method is by using a variable to keep track of the column that the info should go into, but that doesn't work.
I'm my html, I'm putting the student info into an input, so the user can edit the info.
Students Table
studentID | firstname | lastname | teacherID
1 | Bob | Roberts | 2
2 | Rick | Phil | 1
PHP Form
<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 Code That Process's Form Info
$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++;
}
}