Update Multiple rows in a single form


/ Published in: PHP
Save to your folder(s)

This snippet allows you to update multiple rows of a database using a single form in one easy click


Copy this code and paste it in your HTML
  1. //get data fromdb
  2. $sql = mysql_query("SELECT * FROM table");
  3. $count=mysql_num_rows($sql);
  4.  
  5. //start a table
  6. echo '<form name="form1" method="post" action="">
  7. <table width="292" border="0" cellspacing="1" cellpadding="0">';
  8.  
  9. //start header of table
  10. echo '<tr>
  11. <td width="17" align="center">&nbsp;</td>
  12. <td width="115" align="center"><strong>Name</strong></td>
  13. <td width="149"><strong>Email</strong></td>
  14. </tr>';
  15.  
  16. //loop through all results
  17. while($r=mysql_fetch_object($sql)){
  18.  
  19. //print out table contents and add id into an array and email into an array
  20. echo '<tr>
  21. <td align="center"><input type="hidden" name="id[]" value='.$r->id.' readonly></td>
  22. <td align="center">'.$r->name.'</td>
  23. <td><input name="email[]" type="text" id="price" value="'.$r->email.'"></td>
  24. </tr>';
  25. }
  26.  
  27. //submit the form
  28.  
  29. echo'<tr>
  30. <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
  31. </tr>
  32. </table>
  33. </form>';
  34.  
  35.  
  36. //if form has been pressed proccess it
  37.  
  38. if($_POST["Submit"])
  39. {
  40. //get data from form
  41. $name = $_POST['name'];
  42. //loop through all array items
  43. foreach($_POST['id'] as $value)
  44. {
  45. //minus value by 1 since arrays start at 0
  46. $item = $value-1;
  47. //update table
  48. $sql1 = mysql_query("UPDATE table SET email='$email[$item]' WHERE id='$value'")or die(mysql_error());
  49. }
  50.  
  51. //redirect user
  52. $_SESSION['success'] = 'Updated';
  53. header("location:index.php");
  54. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.