I do have an array something like this:
[cuisines] => Array
(
[0] => 17
[1] => 20
[2] => 23
[3] => 26
)
Now I need to update mysql table with these values. All values belong to one user.
So I tried it like this:
if (isset($_POST['cuisines'])) {
$cuisines = $_POST['cuisines'];
} else {
$error_alert[] = "Please select at least one cuisine";
}
if (empty($error_alert)) { // If everything's OK...
// Make the update query:
$sql = 'UPDATE restaurant_cuisines
SET restaurant_id = ?
, cuisine_id = ?
WHERE restaurant_id = ?';
$stmt = $mysqli->prepare($sql);
// Bind the variables:
$stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);
foreach ($cuisines as $value) {
$cuisine_id = $value;
// Execute the query:
$stmt->execute();
}
// Print a message based upon the result:
if ($stmt->affected_rows >= 1) {
echo 'updated';
}
// Close the statement:
$stmt->close();
unset($stmt);
}
But this query not updating mysql correctly. This is what I get running this script.
mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
| 4 | 26 |
| 4 | 26 |
| 4 | 26 |
+---------------+------------+
3 rows in set (0.00 sec)
What would be the problem of this script? Hope somebody may help me out.
Thank you.
...SET restaurant_id = ?, ... WHERE restaurant_id = ?';? Why are you trying to update a value with the value that you have in yourWHEREclause. If the value is the same it will never change. If the value was changed, it will not be in the table, so it will never change.restaurant_idin your loop, so it will end with the last array value.