Reputation: 5651
I have a page where you can update a lot of data, I'm wondering what the best way to store this data on the backend is (using the least amount of code generally).
The data set on the page where each value can be changed would be something like this:
ID NAME DATA MURDATA FINALDATA 1 MyName XYZ 425 Blah 2 Anoth ASDF 87 987 3 Last DKL 38 19bm
How do I loop through the post data so I can do updates on all this submitted data at once?
Upvotes: 0
Views: 2046
Reputation: 4042
You can't update two tuples with different values. You will have to do one UPDATE
for each tuple or do a bulk insert using the ON DUPLICATE KEY UPDATE
-syntax. See the MySQL reference.
Have a form with inputs that have []
as suffix to their names. This way you can access these inputs as an array in PHP:
$result = mysql_query("SELECT * FROM table");
while ($tuple = mysql_fetch_assoc($result))
{
echo '<input type="text" name="name['.(int)$tuple["id"].']" value="'.htmlentities($tuple["name"]).'" />';
// echo more inputs ...
}
Your post processing code could look like this
foreach ($_POST["name"] as $id => $data)
{
// todo: check if all $_POST columns are set, before accessing them
// if (!isset($_POST["data"][$id], $_POST["murdata"][$id], ...)
// continue;
$query = "UPDATE table SET ".
$query .= "name = ".mysql_real_escape_string($_POST["name"][$id])."'";
// the other columns...
$query .= "WHERE id = '".(int)$id."'";
}
Upvotes: 2