0

I'm not sure why this SQL query is not working.

I'm new to SQL/PHP so please forgive.

mysql_query("
    SELECT * FROM table WHERE name = " . "'Bob'" . 
    while($i < $size)
    {
        $i++; 
        echo "OR name = '"; 
        echo $array[$i] . "'";
    } . 
    " ORDER BY id DESC "
);

Dreamweaver gives me an error saying it is not correct but does not tell me what is wrong.

Is it possible to put a while loop into an sql command?

1
  • 3
    advice, try running your query into sql first, make it work then move it to your code Commented Jun 27, 2012 at 8:27

4 Answers 4

2

you can not use a while in a string

$where = "";
if ($size > 0) 
{
$where .= " WHERE ";
}
while($i < $size)
{
$i++;
$where .= "OR name = '".$array[$i]."' ";
}

$query = "SELECT * FROM table WHERE name = '".Bob."'".$where." ORDER BY id DESC";
mysql_query($query);

(this code is not tested)

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

Comments

2

Woot !

You just can't write this :D

Build your OR condition before writing the query and it will be just fine:

$myCondition = " ";
while($i < $size) {
    $i++;
    $myCondition .= "OR name = '" . $array[$i] . "'";
}
mysql_query(
    "SELECT * FROM table WHERE name = " . "'Bob'" . $myCondition . " ORDER BY id DESC ");

Comments

0

echo is to output the string, and it won't return the string.

Something like $str = "aaa" . echo "bbb"; won't work.

For you case, use IN will be better.

foreach ($array as &$name) {
  $name = "'".mysql_real_escape_string($name)."'";
}
mysql_query("SELECT * FROM table WHERE name IN (".implode(',', $array).")");

Comments

0

Or use

"SELECT * FROM table WHERE name IN(".implode( ',', $array).")";

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.