©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
(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( "从结果集中的下一行获取第二列:
" );
$result = $sth -> fetchColumn ( 1 );
print( "colour = $result \n" );
?>
以上例程会输出:
从结果集中的下一行获取第一列: name = lemon 从结果集中的下一行获取第二列: colour = red
[#1] ohcc at 163 dot com [2015-11-24 09:03:40]
usernote #118367 is just a mistake.
I have taken a misunderstanding about PDOStatement::fetch() with PDO::FETCH_COLUMN.
Sorry, it's my bad.
[#2] ohcc at 163 dot com [2015-11-24 07:21:49]
When an invalid column offset is suplied, PDOStatement::fetch() with PDO::FETCH_COLUMN always returns the value of the first column of the first row.
However, PDOStatement::fetchAll() with PDO::FETCH_COLUMN and an invalid column offset whill throw an exception instead.
<?php
$pdo = new PDO(....);// let's assume the database is connected.
$PDOStatement = $pdo->query('SELECT * FROM `WuXiancheng`');
echo $PDOStatement->fetch(PDO::FETCH_COLUMN, -1); // minus column offset
$PDOStatement = $pdo->query('SELECT * FROM `WuXiancheng`');
echo $PDOStatement->fetch(PDO::FETCH_COLUMN, 3691); // column offset is number greater than column count
$PDOStatement = $pdo->query('SELECT * FROM `WuXiancheng`');
echo $PDOStatement->fetch(PDO::FETCH_COLUMN, 36.5); // column offset is a float number
?>
Examples above will all input the first column value of the first row of data get from the database.
This is really weird.
[#3] gaiusgracchus33 at gmail dot com [2015-06-08 18:27:29]
It looks like the example may be saying it is fetching the second column from the NEXT row, not the same one that returned 'lemon' for name. The warning message says you can't return another column from the SAME row after fetchColumn().
[#4] 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.
[#5] 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.