我有这个查询
$categories = $dbh->query(" SELECT * FROM categories ORDER BY name ASC ");
我需要在这个数组上循环两次。
foreach($categories as $category) {
dd($category);
}
echo '---------------';
foreach($categories as $category) {
dd($category);
}
此代码返回
stdClass Object
(
[id] => 24
[name] => granchi
[slug] => granchi
)
stdClass Object
(
[id] => 26
[name] => molluschi
[slug] => molluschi
)
stdClass Object
(
[id] => 25
[name] => pesci
[slug] => pesci
)
---------------
在第二个循环中,数组变空。我发现了类似的问题Two While Loops, Second Returns Empty Array?,但我没有为PDO找到类似的解决方案。
如果没有查询两次创建两个相同的数组,我该如何循环它们两次?
我不明白为什么它会在第一次循环后清空。
答案 0 :(得分:3)
您必须先将查询结果提取到数组中。
的mysqli:
<?php
$db = new mysqli('localhost', 'root', '', 'test');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = " SELECT * FROM categories ORDER BY name ASC ";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo $row['**column name**'] . '<br />';
}
?>
PDO:
<?php
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$sql = "SELECT * FROM categories ORDER BY name ASC ";
try {
$stmt = $db->query($sql);
} catch(PDOException $ex) {
echo "An Error occured!";
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $val)
{
echo $key.' - '.$val.'<br />';
}
?>