在SQL WHERE子句中使用php数组的麻烦

时间:2014-11-09 01:06:45

标签: php sql arrays oracle

我的php页面中有一个sql语句,如下所示:

 $places=array('CHI','DET','LA','NYC','DALLAS');

$SQL="SELECT NAME,
             ID,
             PHONE,
             EMAIL,
             LOCATION
      FROM SHOPPERS
      WHERE LOCATION IN '{$places}'
      AND ID BETWEEN '25687' AND '28050'
      ";

然后我将查询作为一个表格回显,但我没有得到任何结果,因为$ places数组存在问题。任何帮助,将不胜感激。谢谢

1 个答案:

答案 0 :(得分:2)

您需要将其格式化为与SQL期望的友好关系:

$places=array('CHI','DET','LA','NYC','DALLAS');

$SQL="SELECT NAME,
             ID,
             PHONE,
             EMAIL,
             LOCATION
      FROM SHOPPERS
      WHERE LOCATION IN ('".implode("', '", $places)."')
      AND ID BETWEEN '25687' AND '28050'
      ";

SQL where column in子句需要括号,所以你需要将它们添加进来 - 然后你仍然需要将数组内爆成一个字符串。构造的SQL应该如下所示:

$SQL="SELECT NAME,
             ID,
             PHONE,
             EMAIL,
             LOCATION
      FROM SHOPPERS
      WHERE LOCATION IN ('CHI','DET','LA','NYC','DALLAS')
      AND ID BETWEEN '25687' AND '28050'
      ";