0

Recently I've encouraged weird error in PHP code. It's like the inner try{}catch(){} block is omited when using PDOStatement object with foreach(){}. Here is my test code which triggers this behaviour:

<?php
/* 
// THIS WORKS AS EXPECTED, JUST UNCOMMENT
try{
    for($i = 0; $i < 3; $i++){
        try{
            echo "\nTHROWING EXCEPTION\n\n";
            throw new Exception("AAAAAAAAAAAAAAAAAAAAAAAAA");
            echo "EXCETION THROWN (SHOULD NOT SHOW)\n";
        }catch(Exception $err){
            echo "========= INNER CATCH =========\n";
            echo $err->getMessage() . "\n";
        }
    }
}catch(Exception $e){
    echo "=========== OUTER CATCH ===========\n";
    die($e->getMessage() . "\n");
}
die("\nEVERYTHING OK\n");
*/
$dsn = "mysql:dbname=test_pdo;host=localhost";
try {
    $dbh = new PDO($dsn, 'root', "", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $dbh->exec("
    CREATE TABLE IF NOT EXISTS `test` (
    `id` int(10) unsigned NOT NULL,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `name` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    ");
    $dbh->exec("TRUNCATE test");
    $dbh->exec("
    INSERT INTO test (id, name) VALUES 
    (1, 'JOHN DOE 1'), (2, 'JOHN DOE 2'), 
    (3, 'JOHN DOE 3'), (4, 'JOHN DOE 4')
    ");
    echo "\nRECORDS CREATED\n";
    $sth = $dbh->prepare("SELECT id FROM test WHERE id = ?");
    foreach(array(2, 3, 4) as $id){
        $sth->execute(array($id));
        $i = 0;
        foreach($sth as $row){
            $num = $row['id'] - 1;
            // this sql should throw 2300 error duplicate key
            $sql = "UPDATE test SET name = 'JOHN DOE $num' WHERE id = {$row['id']}";
            try{
                echo "\nSENDING QUERY: $sql\n\n";
                $dbh->exec($sql);
            }catch(Exception $err){
                $code = $err->getCode();
                $msg = $err->getMessage();
                //duplicate key error?
                if($err->getCode() != "23000"){
                    echo "THROWING EXCEPTION FROM INNER CATCH.\n ERROR CODE: $code\n";
                    throw $err;
                }
                echo <<<TXT
============ GOOD CATCH ============
ERROR CODE: $code
ERROR MSG: $msg
SQL: $sql


TXT;
            }
        }

    }
}catch(Exception $e){
    $code = $e->getCode();
    $msg = $e->getMessage();
    echo <<<TXT
============ WRONG CATCH ===========
ERROR CODE: $code
ERROR MSG: $msg


TXT;
}

This outputs something like this on my localhost (PHP 5.3.6-13ubuntu3.6 with Suhosin-Patch (cli)) and on server (PHP 5.2.17):

RECORDS CREATED

SENDING QUERY: UPDATE test SET name = 'JOHN DOE 1' WHERE id = 2

============ GOOD CATCH ============
ERROR CODE: 23000
ERROR MSG: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'JOHN DOE 1' for key 'name'
SQL: UPDATE test SET name = 'JOHN DOE 1' WHERE id = 2

============ WRONG CATCH ===========
ERROR CODE: 23000
ERROR MSG: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'JOHN DOE 1' for key 'name'

Don't know why but when I change foreach($sth as $row){ to foreach($sth->fetchAll() as $row){ everythings works as expected:

RECORDS CREATED

SENDING QUERY: UPDATE test SET name = 'JOHN DOE 1' WHERE id = 2

============ GOOD CATCH ============
ERROR CODE: 23000
ERROR MSG: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'JOHN DOE 1' for key 'name'
SQL: UPDATE test SET name = 'JOHN DOE 1' WHERE id = 2


SENDING QUERY: UPDATE test SET name = 'JOHN DOE 2' WHERE id = 3

============ GOOD CATCH ============
ERROR CODE: 23000
ERROR MSG: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'JOHN DOE 2' for key 'name'
SQL: UPDATE test SET name = 'JOHN DOE 2' WHERE id = 3


SENDING QUERY: UPDATE test SET name = 'JOHN DOE 3' WHERE id = 4

============ GOOD CATCH ============
ERROR CODE: 23000
ERROR MSG: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'JOHN DOE 3' for key 'name'
SQL: UPDATE test SET name = 'JOHN DOE 3' WHERE id = 4

Did I found a bug or am I doing something wrong? Can someone confirm that behaviour? Thx

// EDIT

Upgrading PHP version to 5.3.10 seems to fix this issue. Thx for help...

4

1 回答 1

0

不,从 PDO 发回的结果不是您可以直接迭代的结果。这不是 PDO 异常,当您尝试这样做时,它是 PHP —— 它不是具有迭代器的数组或对象。

当您获取它时,它会创建一个在 foreach 循环中有效的数组。

于 2012-03-08T22:23:20.260 回答