Maf*_*tsi 5 php foreach pdo fetchall while-loop
我想知道我是否做得很好或者fetchAll()不适用于WHILE.
这是一个例子
$db=new PDO("mysql:host=" .$dbhost. "; dbname=" . $dbname, $dbuser, $dbpass);
$page=$db->prepare("SELECT * FROM page");
$page->execute();
foreach ($page->fetchAll(PDO::FETCH_ASSOC) as $row) {
//echo a row
//is working
}
Run Code Online (Sandbox Code Playgroud)
但是,如果尝试循环一段时间我
while ($row=$page->fetchAll(PDO::FETCH_ASSOC)){
//echo a row
//Show empty
}
Run Code Online (Sandbox Code Playgroud)
我试图只使用fetch(),它正在工作,我的问题:为什么fetchAll()不能用于"WHILE"?
Ora*_*ill 18
获取全部返回结果集中剩余的所有记录.考虑到这一点,您的foreach能够按预期迭代结果集.
对于等效实现应该使用 $page->fetch(PDO::FETCH_ASSOC);
while ($row = $page->fetch(PDO::FETCH_ASSOC)){
// do something awesome with row
}
Run Code Online (Sandbox Code Playgroud)
如果您想使用一段时间并获取所有可以做的事情
$rows = $page->fetchAll(PDO::FETCH_ASSOC);
// use array_shift to free up the memory associated with the record as we deal with it
while($row = array_shift($rows)){
// do something awesome with row
}
Run Code Online (Sandbox Code Playgroud)
但是请注意:获取所有内容将完全相同,如果结果大小很大,它将会对您计算机上的资源造成压力.我只会知道结果集很小,或者我通过对查询应用限制来强制执行此操作.
无需遍历记录集,因为fetchAll- 好吧 -在一个命令中获取所有记录。不错,不是吗?
$rows = $page->fetchAll(PDO::FETCH_ASSOC);
// $rows is an array containing all records...
foreach ($rows as $row)
echo $row->fieldname;
Run Code Online (Sandbox Code Playgroud)