(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)
PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列。
$column_number
= 0
] )
从结果集中的下一行返回单独的一列,如果没有了,则返回 FALSE
。
column_number
你想从行里取回的列的索引数字(以0开始的索引)。如果没有提供值,则 PDOStatement::fetchColumn() 获取第一列。
PDOStatement::fetchColumn() 从结果集中的下一行返回单独的一列。
如果使用 PDOStatement::fetchColumn() 取回数据,则没有办法返回同一行的另外一列。
Example #1 返回下一行的第一列
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* 从结果集中的下一行获取第一列 */
print("从结果集中的下一行获取第一列:\n");
$result = $sth->fetchColumn();
print("name = $result\n");
print("从结果集中的下一行获取第二列:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>
以上例程会输出:
从结果集中的下一行获取第一列: name = lemon 从结果集中的下一行获取第二列: colour = red
Nathan Pohpam (2012-03-21 02:49:31)
WARNING: PhoenixSegovia isn't quite correct. Perhaps it's implementation-dependent, but fetchColumn returns the empty string in my program. Beware!
PhoneixSegovia at GOOGLE_MAIL_SERVER dot com (2010-10-21 02:13:42)
fetchColumn return boolean false when a row not is found or don't had more rows.
seanferd at assmasterdonkeyranch dot com (2007-01-25 15:04:13)
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.