1

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.

2
  • 1
    What is wrong with your current query? Commented Dec 24, 2012 at 15:54
  • You said "names of rows", but your query is using them as names of columns. Which is it? Commented Dec 24, 2012 at 17:00

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean implode, and the IN clause would select any row that has a 0 in any of the three columns, and not only the ones with all 0's.
could have been an acceptable answer if only implode is used
Still not correct though. OP is looking for rows where each column is equal to 0. You could use the imploded string with this SQL statement: SELECT * FROM $table WHERE ($str) = (0,0,0). See sqlfiddle.com/#!2/70023/27
0

easy,

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

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

1 Comment

This is PHP. You used mix of PHP and Javascript. This is not easy :)
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.