Page 1 of 1

Update multiple rows in database from form input

Posted: Wed Mar 16, 2011 12:01 pm
by kwdrysdale
Hi. I have successfully selected the data I want, put it into a table and have a text box available on each row for data to be entered. What I am wondering is how to associate the text box on each row to the ID of each row?

Here is the code for the table output:

Code: Select all

<?
// this section will display the data in a table allowing scores to be entered in the text boxes
echo "<table border='1'>
<tr>
<th width='200'>Contestant</th>
<th width='250'>School</th>
<th width='75'>Level</th>
<th width='25'>Score</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  $level = $row['level'];
  if ($level == "1") $showlevel="Junior";
  elseif ($level == "2") $showlevel="Senior";
  echo "<tr>";
  echo "<td width='200'>" . $row['contestant'] . "</td>";
  echo "<td width='250' align='center'>" . $row['school'] . "</td>";
  echo "<td width='75' align='center'>" . $showlevel . "</td>";
  echo "<td width='25'><input type='text'></td>";
  echo "</tr>";
  }
echo "</table>";
?>
Contestant School Level Score
Fred SRMCS JR 80
Mary SRMCS JR 75
Sam SRMCS JR 85

The user would see a table with everything already displayed (except the score) and a text box for them to enter the score for each contestant. Then, have a submit button on the bottom and put those marks into the database with the appropriate name. Hopefully I am getting the "problem" across properly and it is possible to do this. Thanks for any help you can give.

Kevin

Re: Update multiple rows in database from form input

Posted: Wed Mar 16, 2011 12:28 pm
by AbraCadaver
Assuming you gran the name and ID, then use an array of marks and have the ID as the array key:

Code: Select all

echo $row['Name'] . '<input type="text" name="mark[' . $row['ID'] . ']">';

Re: Update multiple rows in database from form input

Posted: Wed Mar 16, 2011 12:50 pm
by kwdrysdale
Thanks for the reply. I added some code to my original post and will make the changes you suggested to my code. I understand what is happening here, but then how would I use the array key (the ID) to update the database? I apologize if this is a really simple thing...I am still learning some of the basic things in PHP. :) I just can't figure out how to use the array key as the row id.

Re: Update multiple rows in database from form input

Posted: Wed Mar 16, 2011 1:00 pm
by AbraCadaver
You would loop through the array and use the key in the WHERE clause of the update:

Code: Select all

foreach($_POST['mark'] as $id => $mark) {
   //UPDATE table SET Mark=$mark WHERE ID=$id
}

Re: Update multiple rows in database from form input

Posted: Wed Mar 16, 2011 1:58 pm
by kwdrysdale
THANKS!!! I'm not great with OOP (really a newbie to all of this) but I could make it all work out.