问题描述
我有以下代码:
if(!empty($postCountryAdd)) {
$sqlQueryLocalityAdd = $dbh->prepare("SELECT DISTINCT locality_add FROM table WHERE country_add = :country_add ORDER BY locality_add ASC");
$sqlQueryLocalityAdd->execute(array(':country_add' => $postCountryAdd));
echo '<option value="">Select locality</option>';
foreach($sqlQueryLocalityAdd as $localityAddRow) {
//while ($localityAddRow = $sqlQueryLocalityAdd->fetch()){
echo '<option value="';
echo $localityAddRow["locality_add"];
echo '">';
echo $localityAddRow["locality_add"];
echo '</option>';
}
}
如果我使用foreach($sqlQueryLocalityAdd as $localityAddRow)
,代码将停止响应.为什么我不能多次使用foreach?我该如何解决?
If I use foreach($sqlQueryLocalityAdd as $localityAddRow)
the code stops responding. Why can't I use foreach more than once? How can I fix it please?
推荐答案
$sqlQueryLocalityAdd
不是结果集,它是一个PDOStatement
对象,您只能直接对其进行一次迭代(如deceze所清楚指出的).
$sqlQueryLocalityAdd
isn't a result set, it's a PDOStatement
object and you can only iterate over it directly once (as noted clearly by deceze).
execute()
语句在查询成功时返回boolean
true或false.
The execute()
statement returns a boolean
true or false on success of the query.
如果成功运行,则需要在查询后从中获取结果并迭代返回的数组:
If successfully run, you need to fetch results from it post-query and iterate the array returned:
$success = $sqlQueryLocalityAdd->execute(array(':country_add' => $postCountryAdd));
if($success) {
$results = $sqlQueryLocalityAdd->fetchAll();
foreach($results as $localityAddRow) {
echo '<option value="';
....
生成的数组$results
只是一个普通数组,因此您可以根据需要对其进行多次迭代.
The resulting array $results
is just a vanilla array, so you can iterate over it as many times as you want.
注意:如果execute()
返回false,则查询有问题-成功运行的查询返回空结果集结果仍将导致true
.
Note: If the execute()
returns false, something is wrong with the query--a successful running query returning a empty result set results will still result in a true
.
这篇关于PHP/PDO-使用多个foreach循环时,请多次使用PDO语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!