PDOStatement::fetchColumn
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)
PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列
说明
从结果集中的下一行返回单独的一列,如果没有了,则返回 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
参见
- PDO::query() - 预处理并执行没有占位符的 SQL 语句
- PDOStatement::fetch() - 从结果集中获取下一行
- PDOStatement::fetchAll() - 从结果集中获取剩余的行
- PDO::prepare() - 预处理要执行的语句,并返回语句对象
- PDOStatement::setFetchMode() - 为语句设置默认的获取模式
+添加备注
用户贡献的备注 3 notes
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.
seanferd at assmasterdonkeyranch dot com ¶
18 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.
theking2(at)king.ma ¶
1 year 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".
备份地址:http://www.lvesu.com/blog/php/pdostatement.fetchcolumn.php