简体   繁体   中英

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?

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)

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

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

Something like $str = "aaa" . echo "bbb"; $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).")");

或使用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM