We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to get PDO error message

Hi all,

I have to update the primary key of a model, so I'm forced to use raw SQL. Here's my code:

$DI = \Phalcon\DI::getDefault();
$db = $DI->getShared('db');
$sql = "UPDATE `student` SET `barcode` = ?, `first_name` = ?, `last_name` = ? WHERE `barcode` = ?";
$success = $db->execute($sql,[
    $barcode,
    $first_name,
    $last_name,
    $original_barcode
]);

$success gets set to boolean TRUE or FALSE - which is fine. If it's FALSE I'd like to be able to get the error message. I don't know how, nor can I find documentation on how to get it.



6.9k
Accepted
answer
edited Oct '14

In your array within the Phalcon\Db\Adapter\Pdo\Mysql Constructor array just add a key 'options'

https://php.net/manual/en/pdo.error-handling.php

'options' => [ PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING ]

//eg
$di->set('db', function(){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "12345",
        "dbname" => "test",
        "options" => [ PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING ]
    ));
});

Then you just need to implement a way to handle the error/exception through a wrapper or error handler.

Thanks for that. I think PDO::ERRMODE_EXCEPTION will be easier to handle - but same basic idea.