gainacho gainacho - 3 months ago 13
PHP Question

Why do I get FALSE when I put $statement->fetchColumn() in while() statement?

$statement = $db->query("select count(*) from myMenu");
$count = 0;
while($count < $statement->fetchColumn())
{
var_dump($statement->fetchColumn()); //bool(false)
echo"d";
$count += 1;
}
//echo : d


myMenu table has 6 columns, but while() executes only once when I run the above code.

I even erased var_dump(), but it is still the same.

To solve this problem, I put $statement->fetchColumn() in $count variable like this:

$statement = $db->query("select count(*) from myMenu");
$count = 0;
$count_max = $statement->fetchColumn();
while($count < $count_max)
{
echo"d";
$count += 1;
}
//echo : dddddd


Then it output well.

What did I do wrong in the first code?

I can not understand even if I read the manual of php.net:
http://php.net/manual/en/pdostatement.fetchcolumn.php

Answer Source

From the doc,

PDOStatement::fetchColumn() returns a single column from the next row of a result set or FALSE if there are no more rows.

Since your SQL query select count(*) from myMenu returns only one row, the while() loop will get executed just once and not six times. And that's because after the first iteration of while loop, ->fetchColumn(); statement will return false instead of the column value(because there are no more rows left).