简体   繁体   中英

How can I query to mysql with ARRAY in condition

A have names of rows in array

$arr = array(fir, seco, third);

how can I query mysql like:

$query = "SELECT * FROM $table where fir=0 and seco=0 and third=0";

but using array.

and

$query = "update $table SET fir='$ma', seco='$ma', third='$ma'";

but using array.

For search you can fire below query -

$str = implode(",", $arr);
$query = "SELECT * FROM $table where 0 IN ($str)";

But for update you have to use query what you have written.

easy,

$arr = array(fir, seco, third);

for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and "  + arr[i] + "=" + $ma;
}

This is what I would do...

$fir = $arr[0];
$seco = $arr[1];
$third = $arr[2];
$query = "UPDATE $table SET $fir = '$ma', $seco = '$ma', $third = '$ma'";

Not sure if there is a more optimal answer, but you could use a for loop to create the SQL statement:

<?php
$arr = array(fir, seco, third);

$query = "SELECT * FROM $table where ";
$count = count($arr);
for($i=0;$i<$count;$i++){
  $query .= ($i==$count-1) ? "$arr[$i]=0" : "$arr[$i]=0 and ";
}

echo $query;
?>

Echoes SELECT * FROM $table where fir=0 and seco=0 and third=0 . You can do the same with the UPDATE SQL statement.

Update

Also, you could implode the array, like in Suresh Kamrushi's answer, and use the following code:

<?php
    $arr = array(fir, seco, third);
    $str = implode(',',$arr);
    $query_one = "SELECT * FROM $table WHERE ($str) = (0,0,0)";
    echo $query_one;
?>

The UPDATE query would still need a for loop though, I think.

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