Multiple Execution of Prepared Statements in PDO in PHP
We can execute a prepared statement for a database query multiple times. This is slightly more efficient in terms of resources than preparing it anew each time.
For example, let's say we need to make update queries for user salaries in the table.
Let's assume we already have an associative array,
where the key will be the user's
id, and the value -
their salary:
<?php
$salaries = [
1 => 200,
3 => 500,
5 => 700,
];
?>
Let's prepare the query once:
<?php
$res = $pdo->prepare('UPDATE users SET salary=? WHERE id=?');
?>
And now in a loop, we will iterate through our array and execute our prepared query in each iteration with different data for the placeholders:
<?php
foreach ($salaries as $id => $salary) {
$res->execute([$salary, $id]);
}
?>
Given an array with user IDs and ages:
<?php
$ages = [
1 => 20,
3 => 30,
5 => 40,
];
?>
Write code that will update user data in a loop.