PHP foreach,用于查询的数据数组


PHP foreach, arrays data used in query

我有:

$array1 =     //contains places ids and locations;
$array2 = array();
$array3 = array();

  foreach($array1 as $itemz)
  {     
      $array2[] = $itemz[place][id];
      $array3[] = $itemz[place][location][city];
      $sql = "select * from places where id=".$array2." and location=".$array3."";
  }

但是当我打印$sql时,我得到:

  select * from places where id=12 and location=Array
谁能告诉我代码有什么问题?

谢谢!

我很抱歉,但你的代码没有任何意义。我很惊讶你会得到这样的结果。让我们来看看。

引号在哪里?

$array2[] = $itemz[place][id];
$array3[] = $itemz[place][location][city];

这里缺少引号,请添加

$array2[] = $itemz['place']['id'];
$array3[] = $itemz['place']['location']['city'];

数组到字符串的转换

$sql = "select * from places where id=".$array2." and location=".$array3."";

这个语句不应该工作,有两个原因。

  1. 假设id是INT的单个字段,并且您在$array2中有一堆INT,您仍然无法在没有MySQL IN的情况下进行比较。

  2. 你正在从PHP数组转换为字符串。这行不通。

由于您在循环中运行此$array2[]$array3[]将继续变化并将增长。

所以你实际上要做的是想出一个像

这样的查询
$sql = "SELECT * 
        FROM places 
        WHERE 
             id IN (" . implode(',', $array2) . ") AND 
             location IN (" . implode(',', $array3) . ")";

但是这完全没有意义,因为随着循环的继续,您正在增量地检索相同的数据。

所以我认为你真正想做的是

$sql = "SELECT * 
        FROM places 
        WHERE 
             id = {$itemz['place']['id']} AND 
             location = {$itemz['place']['location']['city']}";

这很可能是你需要的。这将在遍历数组时为每行检索行。

我想做的几个改进是。

在循环完成后运行查询一次,这样您只需要运行一次查询,而不是运行n次。

另外,考虑只检索您需要的列,而不是执行SELECT *

你不能使用$array3来构建查询,因为它是一个数组。相反,您可以编写如下代码-

 foreach($array1 as $i=>$itemz)
  {     
      $array2[$i] = $itemz[place][id];
      $array3[$i] = $itemz[place][location][city];
      $sql = "select * from places where id=".$array2[$i]." and location=".$array3[$i]."";
  }

这一行:

 $array3[] = $itemz[place][location][city];

将创建一个名为$array3的数组,并为其添加一个等于$itemz[place][location][city]的元素,键值为0。当您尝试将此变量嵌入查询时,您会遇到问题,因为它不是字符串。

你可能需要的是:

 $id = $itemz['place']['id'];
 $city = $itemz['place']['location']['city'];
 $sql = "select * from places where id=".intval($id)." and location='".
        mysql_real_escape_string($city)."'";

请注意,我已经做了修改,以修复一些其他的严重的问题的代码(索引到数组与常量而不是字符串,使您的代码容易受到SQL注入)。

当你只需要一个标准变量时,为什么要使用数组呢?

$array1 =     //contains places ids and locations;
foreach($array1 as $itemz)
{     
    $id = $itemz['place']['id'];
    $city = $itemz['place']['location']['city'];
    $sql = "select * from places where id='$id' and location='$city'";
}