PDOStatement::fetchColumn

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

PDOStatement::fetchColumn 从结果集中的下一行返回单独的一列

说明

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

从结果集中的下一行返回单独的一列,如果没有了,则返回 false

注意:

PDOStatement::fetchColumn() 不应该用于检索 boolean 列,因为无法区分 false 值和没有更多行可检索。请改用 PDOStatement::fetch()

参数

column

你想从行里取回的列的索引数字(以0开始的索引)。如果没有提供值,则 PDOStatement::fetchColumn() 获取第一列。

返回值

PDOStatement::fetchColumn() 从结果集中的下一行返回单独的一列,如果没有更多行,则返回 false

警告

如果使用 PDOStatement::fetchColumn() 取回数据,则没有办法返回同一行的另外一列。

错误/异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING,则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION,则抛出 PDOException

示例

示例 #1 返回下一行的第一列

<?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";
?>

以上示例会输出:

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

参见

添加备注

用户贡献的备注 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
10 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