user1844971
user1844971

Reputation: 31

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.

Upvotes: 1

Views: 3132

Answers (4)

bozdoz
bozdoz

Reputation: 12860

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.

Upvotes: 0

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

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.

Upvotes: 1

TimSum
TimSum

Reputation: 738

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'";

Upvotes: 0

Mert
Mert

Reputation: 6572

easy,

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

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

Upvotes: 0

Related Questions