|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #52444 Extending PDOStatement and replacing fetch() apply when using foreach
Submitted: 2010-07-26 12:57 UTC Modified: 2020-04-02 09:56 UTC
Avg. Score:4.8 ± 0.4
Reproduced:4 of 4 (100.0%)
Same Version:3 (75.0%)
Same OS:3 (75.0%)
From: antennen at gmail dot com Assigned:
Status: Open Package: PDO Core
PHP Version: Irrelevant OS: All
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
Solve the problem:
31 - 15 = ?
Subscribe to this entry?

 [2010-07-26 12:57 UTC] antennen at gmail dot com
Extending PDOStatement and replacing fetch() doesn't work when iterating using foreach. It calls the built in fetch rather than my overridden one. This can be circumvented using while($r = $s->fetch()) { .. } but I believe this behaviour is unexpected.

Test script:
class ExtendedStatement extends PDOStatement {
	protected function __construct() {
	public function fetch($fetch_style = PDO::FETCH_ASSOC, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = 0)
		$r = parent::fetch($fetch_style, $cursor_orientation, $cursor_offset);
		if (is_array($r)) { $r["extradata"] = TRUE; }
		return $r;
$db = new PDO("sqlite::memory:");
$db->setAttribute(PDO::ATTR_STATEMENT_CLASS, array("ExtendedStatement", array($db)));
$db->exec("CREATE TABLE example(id INTEGER PRIMARY KEY, name VARCHAR)");
$db->exec("INSERT INTO example(name) VALUES('test')");
$s = $db->prepare("SELECT * FROM example");
foreach ($s as $r) {

Expected result:
array(3) {
  string(1) "1"
  string(4) "test"

Actual result:
array(2) {
  string(1) "1"
  string(4) "test"


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-11-26 13:31 UTC]
PDO should rather implement the Iterator interface so one can override "current"
 [2014-01-01 12:48 UTC]
-Package: PDO related +Package: PDO SQLite
 [2020-04-02 09:56 UTC]
-Package: PDO SQLite +Package: PDO Core
 [2020-04-02 09:56 UTC]
> PDO should rather implement the Iterator interface so one can
> override "current"

ACK.  And PHP 8 would likely be suitable for this change.

By the way, this is a general PDO issue, not only for PDO SQLite.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat Sep 18 16:03:37 2021 UTC