PHP foreach,数组查询中使用的数据

| 我有:
$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
谁能告诉我代码有什么问题吗? 谢谢!
已邀请:
为什么只需要标准变量时使用数组:
$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\'\";
}
抱歉,您的代码根本没有意义。令您惊讶的是,我很惊讶。让我们来看看它。 报价在哪里?
$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.\"\";
该语句不起作用有两个原因。 假设
id
是INT的单个字段,并且在
$array2
中有很多INT,那么如果没有MySQL
IN
,仍然无法比较它们。 您正在从PHP数组转换为字符串。那行不通。 由于您是在循环中运行
$array2[]
和ѭ10continue,因此它们将继续变化并不断增长。 因此,您实际上要尝试的是提出一个类似的查询
$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\']}\";
这很可能是您所需要的。当您遍历数组时,这将检索每一行的行。 我会做一些改进。 循环完成后,运行一次查询,因此您只需运行一次查询,而不必运行“ 13”次。 另外,考虑只检索所需的列,而不要执行
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
的数组,并向其添加键为
0
的等于
$itemz[place][location][city]
的元素。当您尝试将此变量嵌入查询中时,会遇到问题,因为它不是字符串。 您可能需要的是:
 $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注入的攻击)。

要回复问题请先登录注册