fetchColumn return boolean false when a row not is found or don't had more rows.
(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
fetchColumn return boolean false when a row not is found or don't had more rows.
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.
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".