Update Values of Entire Table

Avatar of Chris Coyier
Chris Coyier on

This code assumes you are connected to a MySQL database which has a table with Names and Emails. The idea is that it will output a table of every single value from that table, as text inputs. You can then alter the values of these inputs and re-submit, updating all the values in the database.

//get data from db
$sql = mysql_query("SELECT * FROM table");

//start a table
echo '<form name="form1" method="post" action="">
<table width="292" border="0" cellspacing="1" cellpadding="0">';

//start header of table
echo '<tr>

//loop through all results

//print out table contents and add id into an array and email into an array
echo '<tr>
<td><input type="hidden" name="id[]" value='.$r->id.' readonly></td>
<td><input name="email[]" type="text" id="price" value="'.$r->email.'"></td>

//submit button
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>

// if form has been submitted, process it
       // get data from form
       $name = $_POST['name'];
       // loop through all array items
   foreach($_POST['id'] as $value)
       // minus value by 1 since arrays start at 0
               $item = $value-1;
               //update table
       $sql1 = mysql_query("UPDATE table SET email='$email[$item]' WHERE id='$value'") or die(mysql_error());

// redirect user
$_SESSION['success'] = 'Updated';

Submitted values are not cleaned in this example, as it is assumed only an admin would have access to this type of powerful entry system.