I have a PDO object with the following code:
$query = "SELECT DISTINCT SUBSTR( Date(Date), 1, 4) AS YEAR from Events ORDER BY YEAR DESC;";
$sth = $dbh->query( $query );
while( $row = $sth->fetch( PDO::FETCH_ASSOC )['YEAR'] ) {
print $row
}
The code executes, but I get
Trying to access array offset on value of type bool
What is the explanation, and is there a solution?
The way that a while
loop works is that it will keep on iterating as long as the condition evaluates to a boolean true.
PDOStatement::fetch()
will return an array containing the data of the current row and move an internal pointer to the next row in the result. If there are no more rows, it returns false
.
This means that once you reach the end of the PDO result, fetch()
returns false
and you can't access array offset on false
. This is why you get an error.
There are a couple of ways to solve this problem.
Don't use while
loop. There's no reason to use it in your example.
foreach ($sth as $row) { echo $row['YEAR']; }
If all you want is a single column then there's no reason to fetch an array.
while( $year = $sth->fetchColumn() ) { echo $year; }
Set the fetch mode when you execute the query or using setFetchMode()
.
$sth = $dbh->query( $query, PDO::FETCH_COLUMN, 0 ); foreach ($sth as $year) { echo $year; }
This seems to work too:
$sth = $dbh->query( $query );
while( $row = $sth->fetch( PDO::FETCH_ASSOC ))
print $row['YEAR']
I agree that foreach
is more appropriate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.