Reputation: 31
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
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.
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
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
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
Reputation: 6572
easy,
$arr = array(fir, seco, third);
for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and " + arr[i] + "=" + $ma;
}
Upvotes: 0