简体   繁体   中英

Update multiple rows sql php

I have an balance table like this :-

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

Now I have an array coming from system like this showing usernames:-

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

Now another array with values to be added in order

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

So that balance becomes 8 for test and 10 for test1 , I try this:-

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

But I get Subquery returns more than 1 row . Help appreciated

You need to loop throgh the array and update every user independently.

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'");
}

Better way to join SQL queries in one query and execute it with mysqli_multi_query. Because it will be very slow with big tables.

Here is working example.

SQL code to test

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 code to test

<?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);
?>

After create table and insert users:

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

After script execute

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM