I have two arrays like A & B.
A=[1,2,3,4] , B=[10,20,30,40]
I want to execute a mysql update query in a way like this.
$abc1=mysql_query("update table set corr='1' WHERE id=10");
$abc1=mysql_query("update table set corr='2' WHERE id=20");
$abc1=mysql_query("update table set corr='3' WHERE id=30");
$abc1=mysql_query("update table set corr='4' WHERE id=40");
all these query execution in one go.
Just loop and use the index for the second array
$as=[1,2,3,4] , $bs=[10,20,30,40]; foreach ($as as $key=>$val) { $abc1=mysqli_query("update table set corr='".$val."' WHERE id=".$bs[$key]); }
Note: you should not use mysql
, use mysqli
instead
Note: always escape
Using array_combine()
, you can create a new array, specify one array as keys and the other as values in the new array. Then it's just a matter of looping through the resulting array and executing queries. Since you now have an array, use a foreach
loop and use the keys (in this case all the values of $a
) and the values (in this case all the values of $b
) as the values you are setting.
This assumes that the number of entries in both arrays is always the same. If they are not the same size, array_combine()
will return false; you can use it as verification before doing the queries.
$a = [1, 2, 3, 4]; $b = [10, 20, 30, 40]; $result = array_combine($a, $b); foreach ($result as $k=>$v) { mysqli_query("UPDATE table SET corr='$k' WHERE id = '$v'"); }
That said, this query is vulnerable to SQL injection and you should upgrade to a newer API that supports parameterized queries with placeholders ( mysqli_*
or PDO). The mysql_*
API was deprecated in PHP 5.6 and completely removed in PHP7.
$a=[1,2,3,4];$b=[10,20,30,40];
$res=array_combine($a, $b );
foreach ($res as $key => $value) {
$abc1=mysql_query("update table set corr='".$key."' WHERE id=".$value);
}