We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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'

http://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.