PHP 8.3.4 Released!

PDOStatement::fetch

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

PDOStatement::fetch 从结果集中获取下一行

说明

public PDOStatement::fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixed

从一个 PDOStatement 对象相关的结果集中获取下一行。mode 参数决定 POD 如何返回行。

参数

mode

控制下一行如何返回给调用者。此值必须是 PDO::FETCH_* 系列常量中的一个,缺省为 PDO::ATTR_DEFAULT_FETCH_MODE 的值 (默认为 PDO::FETCH_BOTH )。

  • PDO::FETCH_ASSOC:返回一个索引为结果集列名的数组

  • PDO::FETCH_BOTH(默认):返回一个索引为结果集列名和以0开始的列号的数组

  • PDO::FETCH_BOUND:返回 true ,并分配结果集中的列值给 PDOStatement::bindColumn() 方法绑定的 PHP 变量。

  • PDO::FETCH_CLASS:返回一个请求类的新实例,映射结果集中的列名到类中对应的属性名,然后调用构造函数,除非指定 PDO::FETCH_PROPS_LATE。如果 mode 包含 PDO::FETCH_CLASSTYPE(例如:PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE),则类名由第一列的值决定

  • PDO::FETCH_INTO:更新一个被请求类已存在的实例,映射结果集中的列到类中命名的属性

  • PDO::FETCH_LAZYPDO::FETCH_BOTHPDO::FETCH_OBJ 组合使用,返回 PDORow 对象,该对象在访问时创建对象属性名。

  • PDO::FETCH_NAMED:返回与 PDO::FETCH_ASSOC 具有相同形式的数组,除了如果有多个同名列,则该键引用的值将是具有该列名的行中所有值的数组

  • PDO::FETCH_NUM:返回一个索引为以0开始的结果集列号的数组

  • PDO::FETCH_OBJ:返回一个属性名对应结果集列名的匿名对象

  • PDO::FETCH_PROPS_LATE:当与 PDO::FETCH_CLASS 一起使用时,类的构造方法在从相应的列值分配属性之前被调用。

cursorOrientation

对于 一个 PDOStatement 对象表示的可滚动游标,该值决定了哪一行将被返回给调用者。此值必须是 PDO::FETCH_ORI_* 系列常量中的一个,默认为 PDO::FETCH_ORI_NEXT。要想让 PDOStatement 对象使用可滚动游标,必须在用 PDO::prepare() 预处理SQL语句时,设置 PDO::ATTR_CURSOR 属性为 PDO::CURSOR_SCROLL

cursorOffset

对于一个 cursorOrientation 参数设置为 PDO::FETCH_ORI_ABS 的 PDOStatement 对象代表的可滚动游标,此值指定结果集中想要获取行的绝对行号。

对于一个 cursorOrientation 参数设置为 PDO::FETCH_ORI_REL 的 PDOStatement 对象代表的可滚动游标,此值指定想要获取行相对于调用 PDOStatement::fetch() 前游标的位置

返回值

此方法成功时返回的值依赖于获取类型。在所有情况下,失败或没有更多记录时都返回 false

错误/异常

如果属性 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();

/* 运用 PDOStatement::fetch 风格 */
print "PDO::FETCH_ASSOC: ";
print
"Return next row as an array indexed by column name\n";
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print
"\n";

print
"PDO::FETCH_BOTH: ";
print
"Return next row as an array indexed by both column name and number\n";
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print
"\n";

print
"PDO::FETCH_LAZY: ";
print
"Return next row as a PDORow object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print
"\n";

print
"PDO::FETCH_OBJ: ";
print
"Return next row as an anonymous object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_OBJ);
print
$result->name;
print
"\n";
?>

以上示例会输出:

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [name] => apple
    [colour] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [name] => banana
    [0] => banana
    [colour] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as a PDORow object with column names as properties
PDORow Object
(
    [name] => orange
    [colour] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

示例 #2 使用一个可滚动游标获取行

<?php
function readDataForwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while (
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print
$data;
}
}
function
readDataBackwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
do {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print
$data;
} while (
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
}

print
"Reading forwards:\n";
readDataForwards($conn);

print
"Reading backwards:\n";
readDataBackwards($conn);
?>

以上示例会输出:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

示例 #3 构造顺序

当通过 PDO::FETCH_CLASS 获取对象时,首先分配对象属性,然后调用类的构造方法。如果还指定了 PDO::FETCH_PROPS_LATE,则此顺序相反,即首先调用构造方法,然后分配属性。

<?php
class Person
{
private
$name;

public function
__construct()
{
$this->tell();
}

public function
tell()
{
if (isset(
$this->name)) {
echo
"I am {$this->name}.\n";
} else {
echo
"I don't have a name yet.\n";
}
}
}

$sth = $dbh->query("SELECT * FROM people");
$sth->setFetchMode(PDO::FETCH_CLASS, 'Person');
$person = $sth->fetch();
$person->tell();
$sth->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Person');
$person = $sth->fetch();
$person->tell();
?>

以上示例的输出类似于:

I am Alice.
I am Alice.
I don't have a name yet.
I am Bob.

参见

add a note

User Contributed Notes 26 notes

up
90
terry at bitsoup dot com
18 years ago
WARNING:
fetch() does NOT adhere to SQL-92 SQLSTATE standard when dealing with empty datasets.

Instead of setting the errorcode class to 20 to indicate "no data found", it returns a class of 00 indicating success, and returns NULL to the caller.

This also prevents the exception mechainsm from firing.

Programmers will need to explicitly code tests for empty resultsets after any fetch*() instead of relying on the default behavior of the RDBMS.

I tried logging this as a bug, but it was dismissed as "working as intended". Just a head's up.
up
77
yarco dot wang at gmail dot com
10 years ago
If no record, this function will also return false.
I think that is not very good...
up
36
henry at henrysmith dot org
12 years ago
Someone's already pointed out that PDO::CURSOR_SCROLL isn't supported by the SQLite driver. It's also worth noting that it's not supported by the MySQL driver either.

In fact, if you try to use scrollable cursors with a MySQL statement, the PDO::FETCH_ORI_ABS parameter and the offset given to fetch() will be silently ignored. fetch() will behave as normal, returning rows in the order in which they came out of the database.

It's actually pretty confusing behaviour at first. Definitely worth documenting even if only as a user-added note on this page.
up
28
gergo at gergoerdosi dot com
11 years ago
When using PDO::FETCH_COLUMN in a while loop, it's not enough to just use the value in the while statement as many examples show:

<?php
while ($row = $stmt->fetch(PDO::FETCH_COLUMN)) {
print
$row;
}
?>

If there are 5 rows with values 1 2 0 4 5, then the while loop above will stop at the third row printing only 1 2. The solution is to either explicitly test for false:

<?php
while (($row = $stmt->fetch(PDO::FETCH_COLUMN)) !== false) {
print
$row;
}
?>

Or use foreach with fetchAll():

<?php
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
print
$row;
}
?>

Both will correctly print 1 2 0 4 5.
up
19
lod
15 years ago
A quick one liner to get the first entry returned. This is nice for very basic queries.

<?php
$count
= current($db->query("select count(*) from table")->fetch());
?>php
up
12
public at grik dot net
13 years ago
When fetching an object, the constructor of the class is called after the fields are populated by default.

PDO::FETCH_PROPS_LATE is used to change the behaviour and make it work as expected - constructor be called _before_ the object fields will be populated with the data.

sample:

<?php
$a
= $PDO->query('select id from table');
$a->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'ClassName');
$obj = $a->fetch();
?>

http://bugs.php.net/bug.php?id=53394
up
8
Typer85 at gmail dot com
14 years ago
Here is quick note for developers that use the PDO SQLite Driver:

The PDO SQLite driver does not support cursors, so using the PDO::CURSOR_SCROLL Attribute, will not work when using the PDO SQLite driver. For example:

<?php

// Assuming $Handle Is a PDO Handle.
$Statement = $Handle->query( $sqlStatement , array( PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL ) );

?>

What is even worse is that PDO::prepare will NOT throw an Exception when it fails to prepare the query, even when the error mode is set to throw Exceptions, and will instead return a Boolean False!

Not only do I consider this a poor design choice, but also its a real shame that this is not documented anywhere in the manual -- in fact the manual is not clear on what Attributes are supported by which drivers and which are not so developers are left to play a classic game of guess.

I hope this saves some developers some headaches.

Good Luck,
up
2
paulf at quillandmouse dot com
4 years ago
A prior poster indicated that this function returns a NULL when there are no results. This is not true. This function returns an empty array. fetchAll() returns the same.

Also, the documentation specifies what happens on "failure", but doesn't indicate what constitutes a "failure". A "failure" could be where the function returns no results; that is, the query "failed". However, a "failure" is apparently a situation where the PDO error functions would reveal a "failure", as in illegal SQL syntax, or a query on a table which doesn't exist, etc. An empty result is not a "failure". Maybe that's obvious to everyone else, but it wasn't to me.
up
9
Gerard van Beek
16 years ago
If you to use a new instance of a class for a record you can use:

<?php
include_once("user.class");
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");

/* create instance automatically */
$sth->setFetchMode( PDO::FETCH_CLASS, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
print (
$user->id);

/* or create an instance yourself and use it */
$user= new user();
$sth->setFetchMode( PDO::FETCH_INTO, $user);
$sth->execute();
$user= $sth->fetch( PDO::FETCH_INTO );
$sth->closeCursor();
print (
$user->id);
?>
up
3
lenz_kappov at yahoo dot co dot uk
10 years ago
Because MySQL does not currently support the use of cursors, the $cursor_offset feature cannot work when using PDO to access a MySQL database.

If you are tring to arbitrarily access a specific record or group of records in a MySQL database recordset, you might want to consider using the LIMIT clause of the SELECT statement to achieve this e.g. LIMIT 5,3 to return just the 6th,7th & 8th records - 3 records starting at index 5 (which is the 6th record).
up
4
fh at ez dot no
18 years ago
If you want to use PDO::FETCH_CLASS you need to set it up with setFetchMode first like so:
$stmt->setFetchMode( PDO::FETCH_CLASS, 'classType', array( 'parameters to constructor' );
$object = $stmt->fetch( PDO::FETCH_CLASS );
If you ommit this PHP will segfault.
up
3
fh at ez dot no
18 years ago
I can also add that the constructor is run _after_ the data is set on the object if yo use PDO::FETCH_CLASS.
up
0
Drew
4 years ago
When using a PDOStatement with the fetch mode set to FETCH_CLASS, fetch will return false if no rows were found.
up
1
marcini
16 years ago
Be careful with fetch() when you use prepared statements and MySQL (I don`t know how it is with other databases). Fetch won`t close cursor and won`t let you send any other query, even if your result set has only one row, .
If you use $statement->fetch(), you will also have to use $statement->closeCursor() afterwards, to be albe to execute another query.
Alternatively you can use $statement->fetchAll() without $statement->closeCursor().
up
0
Black Knight
7 years ago
this is just On reminder note about Second parameter -cursor_oriantation-

PDO::FETCH_ORI_NEXT :-
Fetch the next row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_PRIOR :-
Fetch the previous row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_FIRST :-
Fetch the first row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_LAST :-
Fetch the last row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_ABS :-
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_REL :-
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
up
-2
Alex
12 years ago
It seems that if you do a $statement->query() with an INSERT statement and after that a $statement->fetch() you will get an exception saying: SQLSTATE[HY000]: General error.
up
-1
lozitskiys at gmail dot com
15 years ago
I spent some hours trying to find out how to manipulate with BLOB fields using PDO.

Remember that you can't retreive BLOB data using something like this :

<?php
$sql
= 'SELECT * FROM sometable LIMIT 1';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->setAttribute(PDO::FETCH_ASSOC);
$row = $stmt->fetch();

$myFile = $row['file'];
?>

Instead of this you should try following approach:

<?php
$sql
= "SELECT mime, file FROM sometable LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();

$stmt->bindColumn(1, $mime,);
$stmt->bindColumn(2, $file, PDO::PARAM_LOB);

$stmt->fetch();

header('Content-type: '.$mime);
print
$file;

?>
up
-2
josh
15 years ago
Note that PDO::ATTR_STRINGIFY_FETCHES will NOT work for the MySQL driver. MySQL will always return strings because that is the behaviour of the core mysql PHP extension. See http://bugs.php.net/bug.php?id=44341
up
-2
tastro
9 years ago
Note that this way, the "fetch mode" will get "overwritten", and PDO::FETCH_PROPS_LATE won't be applied:

<?php
$sth
= $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
?>

Instead, you should leave the parameter area for the fetch() method empty, like this (if you want to set the fetch mode with the setFetchMode() method):

<?php
$sth
= $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch();
$sth->closeCursor();
?>
up
-3
sumariva at gmail dot com
11 years ago
I could use PDO::FETCH_COLUMN to retrieve the first column from result.
$ps->fetch( PDO::FETCH_COLUMN );
Worked on Postgresql with PHP 5.3.10.
up
-2
aledmb at gmail dot com
18 years ago
note that fetch constants are not included in the PDO class for PHP versions prior to 5.1
up
-4
tim at kooky dot org
7 years ago
Be careful when using PDO::FETCH_LAZY. It adds an additional field called queryString. I'm not sure if this a bug or not. I'm using version 5.6.17 in Debian Jessie.

Query: 'select 1,2,3'

$row=$smt->fetch(PDO::FETCH_OBJ);
var_dump($row);

object(stdClass)#6 (3) {
["1"]=>
string(1) "1"
["2"]=>
string(1) "2"
["3"]=>
string(1) "3"
}

$row=$smt->fetch(PDO::FETCH_LAZY);
var_dump($row);

object(PDORow)#3 (4) {
["queryString"]=>
string(12) "select 1,2,3"
["1"]=>
string(1) "1"
["2"]=>
string(1) "2"
["3"]=>
string(1) "3"
}
up
-6
avinoamr at gmail dot com
18 years ago
Note that using the FETCH_CLASS mechanism does NOT trigger the class's constructor! You must explicity instantiate the class to use it's constructor behavior.
up
-14
BaBna
16 years ago
When you do a SELECT query for one row, and want to check if it's there, you don't need to count the fetchAll() result, you can just check if $result->fetch() is true:
<?php
$bbnq
= sprintf("SELECT login
FROM users
WHERE id = %u"
,27);
try
{
$req = $db_bbn->query($bbnq); }
catch (
Exception $e)
{
bbnf_pdo_error($e,__FILE__,__LINE__); }
if (
$r = $req->fetch() )
{ echo
"This query has a row result"; }
else
{ echo
"This query has an empty result"; }
?>
up
-17
Ome Ko
12 years ago
Don't do
if($objStatement->fetch()) return $objStatement->fetch();

You want
if($blah=$objStatement->fetch()) return $blah;

Trust me on this one.
up
-20
sumariva at gmail dot com
10 years ago
I got problems during fetch of stored procedures with mssql following PDOException:

SQLSTATE[IMSSP]: The active result for the query contains no fields

with a a prepared statement like:
EXEC [mydb].[stored_procedure_that_returns_select] ?;

The solution was to supress the count of records
SET NOCOUNT ON; EXEC [mydb].[stored_procedure_that_returns_select] ?;

Hope it helps!
To Top