PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn Returns a single column from the next row of a result set

Description

public PDOStatement::fetchColumn(int $column = 0): mixed

Returns a single column from the next row of a result set or false if there are no more rows.

Note:

PDOStatement::fetchColumn() should not be used to retrieve boolean columns, as it is impossible to distinguish a value of false from there being no more rows to retrieve. Use PDOStatement::fetch() instead.

Parameters

column

0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.

Return Values

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

Warning

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

Errors/Exceptions

Emits an error with level E_WARNING if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_WARNING.

Throws a PDOException if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_EXCEPTION.

Examples

Example #1 Return first column of the next row

<?php
$sth
= $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

print
"Fetch the first column from the first row in the result set:\n";
$result = $sth->fetchColumn();
print
"name = $result\n";

print
"Fetch the second column from the second row in the result set:\n";
$result = $sth->fetchColumn(1);
print
"colour = $result\n";
?>

The above example will output:

Fetch the first column from the first row in the result set:
name = lemon
Fetch the second column from the second row in the result set:
colour = red

See Also

add a note

User Contributed Notes 3 notes

up
52
PhoneixSegovia at GOOGLE_MAIL_SERVER dot com
14 years ago
fetchColumn return boolean false when a row not is found or don't had more rows.
up
11
seanferd at assmasterdonkeyranch dot com
17 years ago
This is an excellent method for returning a column count. For example:

<?php
$db
= new PDO('mysql:host=localhost;dbname=pictures','user','password');
$pics = $db->query('SELECT COUNT(id) FROM pics');
$this->totalpics = $pics->fetchColumn();
$db = null;
?>
In my case $pics->fetchColumn() returns 641 because that is how many pictures I have in my db.
up
0
theking2(at)king.ma
9 months ago
When migrating from mysqli it is important that while mysqli_result::fetch_column will iterate over subsequent rows PDOStatement::fetchColumn will NOT!

<?php
while ( $row0 = $db->query("SELECT `value` FROM `bool`")->fetchColumn(0) ) {
var_dump( $row0 );
}
?>

is an endless loop unless the first column in the first row of the table bool is "0".
To Top