So I've been racking my brains and searching the web for the past couple of days trying to figure this one out: I want to update multiple rows in SQL. The problem is that this database won't update. I know it's not a good idea to be putting SQL queries into loops, but this is the only way I've been able to get the data from the table.
Here is the code:
if(isset($_POST['save'])){
$update_query = "UPDATE grades SET grade_value = '{$_POST['grade']}' WHERE user_id = 1";
$result = mysqli_query($link, $update_query);
while($row = mysqli_fetch_assoc($result)){
foreach($row as $grade){
mysqli_query($link, $update_query);
}
}
}
function editGrades() {
global $link;
$query = "SELECT * FROM grades WHERE user_id = 1";
$result = mysqli_query($link, $query);
if(!$result){
die('Query failed' . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
$gradeValue = $row['grade_value'];
$gradeValue = is_array($gradeValue) ? $gradeValue : array($gradeValue);
foreach($gradeValue as $val){
?>
<td name='grade'><form name="grade" method="post"><input value='<?php if (isset($val)){echo sprintf("%0.2f",$val);} ?>' type='text' class='form-control' name='grade'></td>
<?php }
}
}
<table class="table gradebook">
<tr><th>Student</th><?php displayAssignments(); ?></tr>
<tr><?php displayStudents();?><?php editGrades(); ?></tr>
</table>
<div id="btncontainer">
<br />
<input type="submit" method="post" name="save" action="gradebook.php" class="btn btn-success">Save Changes</button>
</div>
My best guess as to why mysqli_query
isn't updating is because there are multiple $_POST['grade']
values being submitted and SQL doesn't know what to do with them. I've checked the the form and input names and all of those check out fine.
(I know user_id
shouldn't be in the grades table, but I'm just trying to get this working and will optimize SQL queries later).