3

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.

Mary
  • 197
  • 1
  • 15
sam
  • 69
  • 1
  • 6

3 Answers3

1

Just loop em and use the index for the second array

$as=[1,2,3,4] , $bs=[10,20,30,40];
foreach ($as as $key=>$val) {
    $abc1=mysql_query("update table set corr='".$val."' WHERE id=".$bs[$key]);
}

Note: You shouldn't use mysqluse mysqliinstead

Note: Always escape

Mazz
  • 1,859
  • 26
  • 38
1

Using array_combine(), you can create a new array, specify one array as the keys, the other as values in the new array. Then it's just a matter of looping the resulting array, and execute queries. Since you now have one array, use a foreach loop and use the keys (in this case, all the values from $a) and values (in this case, all the values from $b) as the values you're setting.

This assumes that the amount of entries in both array is always the same. If they are not of the same size, array_combine() will return false - you can use that as a check before performing the queries.

$a = [1, 2, 3, 4];
$b = [10, 20, 30, 40];
$result = array_combine($a, $b);

foreach ($result as $k=>$v) {
    mysql_query("UPDATE table SET corr='$k' WHERE id = '$v'");
}

That being said, this query is vulnerable to SQL injection, and you should upgrade to a newer API which supports parameterized queries with placeholders (mysqli_* or PDO). The mysql_* API was deprecated in PHP 5.6 and removed entirely in PHP7.

Community
  • 1
  • 1
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Don't you think that array combine will cause more iterations. We can use single loop for the solution just as Mazz said – Agam Banga May 03 '17 at 10:47
  • It's not `array_merge()`, it's `array_combine()`. That makes a new array from two arrays, where one is the keys and the other the values. Read the documentation. The resulting array would have the same length as the two arrays, in this case 4. – Qirel May 03 '17 at 10:48
0
$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);
}
Piyush Kumar
  • 48
  • 1
  • 4