PDO Bug:fetchColumn()VS count()

时间:2013-05-03 16:04:14

标签: php mysql pdo

我有一个包含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行。怎么样?

1 个答案:

答案 0 :(得分:5)

你的代码与你的言论相矛盾。很可能你在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

}