How to concatenate two arrays in PHP

I have two arrays of type A and Bed and .


A=[1,2,3,4] , B=[10,20,30,40]

      


I want to execute a mysql update query this way.


$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 this is the execution of the request in one go.

+3


source to share


4 answers


Just collect 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. mysql

Use insteadmysqli



mysqli

Note. Always avoid

+1


source


Using array_combine()

, you can create a new array, specify one array as keys and another 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 one array, use a loop foreach

and use keys (in this case all values โ€‹โ€‹from $a

) and values โ€‹โ€‹(in this case all values โ€‹โ€‹from $b

) as values, re.

This assumes that the number of entries in both arrays is always the same. If they are not the same size it array_combine()

will return false - you can use this as a check before making requests.

$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 move to a new API that supports parameterized queries using placeholders ( mysqli_*

or PDOs). The API mysql_*

was deprecated in PHP 5.6 and removed completely in PHP7.

+1


source


Assuming the lengths of both arrays are the same,

<?php
$A=[1,2,3,4];
$B=[10,20,30,40];
for($i=0;$i<sizeof($A);$i++){
mysql_query("update table set corr='".$A[$i]."' WHERE id='".$B[$i]."'");
}
?>

      

0


source


$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);
}

      

0


source







All Articles