Reputation: 2634
I have this previous post where I need to change my HTML form to accept an array. This post has the full details of the code.
So I changed all forms accordingly, such as:
<select name="camera_type[]">
But now I'm stuck on how to run the update query. Now that I store everything in an array I obviously can't use my query as is. Here is a post that seems to be exactly what I need, but I'm not sure I understand: Update MySQL table with an Array using Foreach
Any further help on this is appreciated.
Upvotes: 0
Views: 109
Reputation: 9876
To help understand looping through an array and running UPDATE
queries check this out:
// first setup your MySQLi connection
$db = new mysqli('localhost', 'user', 'pass', 'dbname');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
// disable autocommit for transactions
$db->autocommit(false);
// **EDIT** forgot to escape input data. fixed now. note the mysqli_real_escape_string() and int type casting
foreach ($_POST['camera_type'] as $type) {
// assuming 'id' is set in the POST array
$query = sprintf(
'UPDATE table SET column = "%s" WHERE id = %d',
$db->real_escape_string($type),
(int) $_POST['id']
);
$db->query($query);
}
// commit transactions (or commit the updates that were run) and then close
$db->commit();
$db->close();
Upvotes: 1
Reputation: 5941
Use a foreach
loop on the submitted value. Then you can iterate over the entire array and construct queries as you please.
For example: You have a $_POST['camera_type'] variable which is an submitted from the browser. In your php script do the following.
foreach($_POST['camera_type'] as $value) {
//do your processing.
}
Upvotes: 1