我有一个包含3行的表。我试图遍历所有行,但没有得到正确数量的行。
我的代码如下:
$result1_prepare = $DB->prepare("SELECT * FROM table");
$result1_prepare->execute();
$num = $result1_prepare->fetchColumn();
$result1 = $result1_prepare->fetchAll();
echo $num; //OUTPUT 3
echo count($result1); //OUTPUT 2
if($num > 0){
foreach ($result1 as $x => $row) {
//LOOPING only 2 times, 1 row is not showing
}
}
fetchAll()函数仅返回2行。怎么来的?
最佳答案
您的代码与您的语言相矛盾。最有可能在fetchAll之前调用fetchColumn-因此,fetchColumn从结果集中抢走了一行,而对于fetchAll只保留了两行。
无论如何,您都不需要这些
$stm = $DB->prepare("SELECT * table");
$stm->execute();
$data = $stm->fetchAll();
foreach ($data as $x => $row) {
//LOOPING only if there was data returned. no need to check the number
}
关于php - PDO错误:fetchColumn()VS count(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16363184/