我正在循环遍历数组以一次更新一行,例如:
for ($i = 0; $i < count($users); $i++) {
$query = "UPDATE users SET name = :name WHERE id = :id";
$statement = $pdo_conn->prepare($query);
$result = $statement->execute('name' => $users[$i]['name'], 'id' => $users[$i]['id']);
}
有没有办法制作这个1查询,或以任何方式进行优化?
答案 0 :(得分:3)
使用foreach()并迭代$ users数组,绑定值并在数组中执行语句
$stmt = $pdo->prepare('UPDATE users SET name = :name WHERE id = :id');
foreach($users as $user)
{
$stmt->bindValue(':name', $user['name']);
$stmt->bindValue(':id', $user['id']);
$stmt->execute();
}