更新多行sql php

时间:2018-09-21 15:24:37

标签: php sql mysqli

我有一个像这样的资产负债表:-

 id | balance |user
 1  | 5       |test
 2  | 6       |test1

现在我有一个来自系统的数组,显示用户名:-

 $arr = array(0 => test, 1 => test1)

现在另一个要按顺序添加值的数组

 $bal = array(0 => 3, 1 => 4)

因此,8的余额变成test10的余额变成test1,我尝试这样做:-

 $sql = "UPDATE balance
SET balance = balance + IN (".implode(',',$bal).") WHERE username IN (".implode(',',$arr).")";
 $query = mysqli_query($conn, $sql);

但是我得到Subquery returns more than 1 row。感谢帮助

2 个答案:

答案 0 :(得分:0)

您需要遍历数组并独立更新每个用户。

foreach ($bal as $key => $amount) {
    $username = mysqli_real_escape_string($conn, $arr[$key]);
    mysqli_query($conn, "UPDATE balance SET BTC = (BTC + $amount) WHERE username = '$username'");
}

答案 1 :(得分:0)

在一个查询中联接SQL查询并使用mysqli_multi_query执行它的更好方法。因为用大桌子会很慢。

这是工作示例。

要测试的SQL代码

create table users_balance (
    id serial,
    user_id int unsigned not null,
    balance int unsigned not null
);
insert into users_balance (user_id, balance) values (1, 111), (2, 222), (3, 333);

要测试的PHP代码

<?php
$db = mysqli_connect("localhost", "test123", "test123", "test123");
if (!$db) { echo "Connect error: " . mysqli_connect_error() . PHP_EOL; exit; }

$users = array(1 => 'user1', 2 => 'user2', 3 => 'user3');
$new_balance = array(1 => 100, 2 => 200, 3 => 300);

$sql = '';
foreach ($new_balance as $user_id => $amount) {
    $sql .= "UPDATE users_balance SET balance = balance + $amount WHERE user_id=$user_id;";
}
mysqli_multi_query($db, $sql);

mysqli_close($db);
?>

创建表并插入用户后:

select * from users_balance;
+----+---------+---------+
| id | user_id | balance |
+----+---------+---------+
|  1 |       1 |     111 |
|  2 |       2 |     222 |
|  3 |       3 |     333 |
+----+---------+---------+

执行脚本后

select * from users_balance;
+----+---------+---------+
| id | user_id | balance |
+----+---------+---------+
|  1 |       1 |     211 |
|  2 |       2 |     422 |
|  3 |       3 |     633 |
+----+---------+---------+