简体   繁体   中英

Execute multiple mysql updates in one query

What is the best way to merge two mysqli query's as one query

TABLE SERVER_JOINS

ID    DEFAULT   SERVER_ID     MEMBER_ID
---------------------------------------
1       0         1             57
2       0         52            57
3       0         22            57
4       1         35            57

Only one row must have default as 1 By clicking on a link i want to change the default value

mysqli_query($database->connection,"UPDATE `server_joins` SET 
`default` = '0' WHERE `default` = '1' AND `member_id` = '$session->u_id'");

mysqli_query($database->connection,"UPDATE `server_joins` SET 
`default` = '1' WHERE `server_id`= '$id' AND `member_id` = '$session->u_id'");

I think you want to schieve something like that:

mysqli_query($database->connection,"UPDATE `server_joins` 
SET `default` = '1' 
WHERE `default`= '0' AND `server_id`= '$id' AND `member_id` = '$session->u_id'");

Use an if() function or a conditional case expression in the set clause depending on the value of the server field to decide whether default is to be set to 0 or 1.

UPDATE `server_joins`
SET `default` = if(`server_id`= $id, 1, 0)
WHERE `member_id` = $session->u_id

Couple of notes:

  1. Your code is likely to be vulnerable to sql injection attack. Consider using prepared statements with parameters.
  2. If you have numeric values in a field, then do not pass the values as string. Mysql has to convert the values on the flight.

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