Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

85
Vistas
How to relate two arrays in PHP

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.

8 months ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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

8 months ago · Santiago Trujillo Denunciar

0

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.

  • Why shouldn't I use mysql_* functions in PHP?

  • How can I prevent SQL injection in PHP?

  • Handbook for array_combine()

8 months ago · Santiago Trujillo Denunciar

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);
}
8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.