简体   繁体   中英

PHP, MySQL Update multiple columns

$mengetotzut = 7','8','9','22','23','24','25 ;
$zutatiddd = 42','75','8','90','23','82','33 ;
$sql5= "UPDATE zutaten SET Menge=('$mengetotzut') WHERE Zutat_ID IN('$zutatiddd')";
 $run_query = mysqli_query($con,$sql5);

As SQL statement is looking like :

UPDATE zutaten SET Menge=('42','75','8','90','23','82','33') WHERE Zutat_ID IN('7','8','9','22','23','24','25')

What i am trying to do is to do is:

Update Menge='42' Where Zutat_ID is '7' AND Update Menge ='75' Where Zutat_ID = '8' ...

But in one SQL statement. Can someone tell me if this is possible and how can i do it?

Use foreach loop

foreach( $mengetotzut as $index => $code ) {
$sql5= "UPDATE zutaten SET Menge=('$code') WHERE Zutat_ID = $zutatiddd[$index];
 $run_query = mysqli_query($con,$sql5);   
}

Considering that both arrays have the same count, try the below

$count = 7;

for ($i=0; $i<$count; $i++) {
    $sql5= "UPDATE zutaten SET Menge=$mengetotzut[$i] WHERE Zutat_ID = $zutatiddd[$i]";
    $run_query = mysqli_query($con,$sql5);
}

You can use an SQL query like the following to UPDATE with one go:

UPDATE zutaten AS t1
JOIN (
    SELECT 7 AS Zutat_ID, 42 AS Menge
    UNION ALL
    SELECT 8, 75
    UNION ALL
    SELECT 9, 8
) t2 ON t1.Zutat_ID = t2.Zutat_ID
SET t1.Menge = t2.Menge

What you are after is CASE , your query will look like this:

UPDATE zutaten SET Menge = CASE Zutat_ID
    WHEN 42 THEN 7
    WHEN 75 THEN 8
    WHEN 8 THEN 9
    WHEN ...
END WHERE Zutat_ID IN (42,75,8,...)

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