2013-05-03 43 views
0

我有一个包含3行的表。我试图遍历所有的行,但我没有得到正确数量的行。PDO错误:fetchColumn()VS计数()

我的代码如下:

$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行。怎么来的?

+5

? – christopher 2013-05-03 16:07:43

+0

请参阅'PDOStatement :: rowCount' http://php.net/manual/en/pdostatement.rowcount.php – 2013-05-03 16:14:58

+0

@dirt:'...一个SELECT语句,某些数据库可能会返回该语句返回的行数。然而,这种行为是不能保证的......' – 2013-05-03 16:15:37

回答

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 

} 
使用了`fetchColumn`计算行数
+0

你是对的。 FetchColumn正在抓取结果集中的一行。此外,我现在使用rowcount来计算行数。 – 2013-05-03 17:06:41