Reputation: 660
I have a table wherein I store the list of students enrolled in a class, and also their respective grades. It has STUD_ID and STUD_GRADE as columns, and the default value of the STUD_GRADE is NA.
What I want to do is to display all the students in the table, and a textbox for their grades beside them, and when the submit button is pressed, then all of the rows would be updated.
I display them all by using this code:
$query = "SELECT stud_id FROM tblgrade";
$result = mysql_query($query,$db) or die (mysql_error($db));
while($row = mysql_fetch_array($result))
{
extract($row);
echo "<tr><td><input type='hidden' value='$stud_id' name='id'/> stud_id </td>
<td><input type='text' size='10' name='grade'></td>
<tr>";
}
?>
What I am trying to do is to update the NA grades by using a loop in either the query itself or PHP functions. I tried so many things already but I'm really having difficulties in making the proper loop. It always give out a result wherein only the last row would be updated.
Here is the first and last thing I tried to work on:
$query = "SELECT stud_id FROM tblgrade";
$result = mysql_query($query,$db) or die (mysql_error($db));
while($row = mysql_fetch_array($result))
{
$query1 = "UPDATE tblgrade SET stud_grade = '$_POST[grade]' WHERE stud_id = '$_POST[id]'";
mysql_query($query1,$db) or die (mysql_error($db));
}
echo "Grades have been updated!";
I choose not to post the loops I tried, because they are all really messed up, and I am hoping something like the one I posted above can be done.
Suggestions, anyone? Thanks in advance. :D
PS: Really not good at looping.. :(
Upvotes: 0
Views: 951
Reputation: 191
i would do it like this:
UPDATE tblgrade
SET stud_grade = CASE
WHEN stud_id_1_value THEN 'stud_grade_1_value'
WHEN stud_id_2_value THEN 'stud_grade_2_value'
WHEN stud_id_3_value THEN 'stud_grade_3_value'
...
END
WHERE stud_id IN (stud_id_1_value,stud_id_2_value,stud_id_3_value,...);
Upvotes: 1