-1

我已经创建了这个代码

       $cities = arrary('city1','city2','city3','city4','city5');

       $query = "SELECT * FROM data_entry WHERE ";

        foreach($cities as $city){

           $query += " AND city = '$city' ";

        }

        echo $query;

此代码打印零

我想像这样制作 $query 输出

  SELECT * FROM data_entry WHERE city = 'city1' AND city = 'city2' .... etc.
4

4 回答 4

5

$cities = array('city1','city2','city3','city4','city5');

   $query = "SELECT * FROM data_entry WHERE ";

    foreach($cities as $key => $city){
      if($key ==0){
        $query .= " city = '$city' ";
       }
       else{
       $query .= " AND city = '$city' ";
       }
    }

    echo $query;
于 2012-12-15T19:26:02.167 回答
3
   $cities = array('city1','city2','city3','city4','city5');

   $query = "SELECT * FROM data_entry WHERE city='"
          .implode("' AND city='", $cities)."'";

   echo $query;

但是这个查询总是返回空结果,如果数组中有不同的城市,也许你需要选择查询如下:

$cities = array('city1','city2','city3','city4','city5');
$query = 'SELECT * FROM data_entry '
    .'WHERE city IN("'.implode('","',$cities).'")';
于 2012-12-15T19:40:58.863 回答
1
$query = "SELECT * FROM data_entry WHERE 1=1";
foreach($cities as $city){
    $query .= " AND city = '$city' ";
}

不要忘记转义$city值以避免安全问题......(SQL注入)

于 2012-12-15T19:15:25.337 回答
-1

此代码应该可以工作:

$cities=array('city1','city2','city3','city4','city5');
$query="SELECT * FROM data_entry WHERE city='".$cities[0]."'";
foreach(array_slice($cities,1) as $city)
{
    $query.=" OR city='$city'";
}
echo $query;

或者,从 didierc 的想法:

$cities=array('city1','city2','city3','city4','city5');
$query="SELECT * FROM data_entry WHERE city='".$cities[0].implode("' OR city='",array_slice($cities,1))."'";
echo $query;
于 2012-12-15T19:18:11.907 回答