McDan Garrett
McDan Garrett

Reputation: 183

While Loop in SQL query

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?

Upvotes: 0

Views: 2349

Answers (4)

rbaker86
rbaker86

Reputation: 1822

Or use

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

Upvotes: 0

Olivier Coilland
Olivier Coilland

Reputation: 3096

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

Upvotes: 2

xdazz
xdazz

Reputation: 160963

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).")");

Upvotes: 0

David
David

Reputation: 4117

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)

Upvotes: 2

Related Questions