简体   繁体   中英

PHP Mysql update multiple columns with multiple row values by single query

I am trying to update rows in mysql, but I have to use a "for" loop for multiple update queries, which have multiple values in each query. The queries are like the following:

update table set column1='100',column2='140,column3='150' where id =1
update table set column1='120',column2='145,column3='154' where id =2
update table set column1='141',column2='148,column3='155' where id =3

I am using a "for" loop to run multiple queries with different id's, I want to run a single query to update all rows, but not by using "case". Is that possible?

you can use loop for generating dynamic query. please have a look. This might be helpful to you.

$data[] = array("column1"=>100, "column2"=>140, "column3"=>150, "id"=>1 );
$data[] = array("column1"=>120, "column2"=>145, "column3"=>154, "id"=>2 );
$data[] = array("column1"=>142, "column2"=>148, "column3"=>155, "id"=>3 );

foreach($data as $dat){
    $query = "UPDATE table SET column1=".$dat['column1'].", column2=".$dat['column2'].", column3=".$da['column2']." WHERE id=".$dat['id'];
    echo $query;
}

Why would you put the WHERE clause if you wanna update all the ID's? If you don't wanna update all the ID's you will have to do it in a for loop.

UPDATE tableName SET column1 = '100', column2 = '140', column3 = '150'

You can use WHERE IN(...) for this. Eg:

update table set column1='100',column2='140,column3='150' where id IN (1,2,3)

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