Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to squeeze error message out of PDO? [duplicate]

People also ask

How the error messages are handled in PDO?

PDO gives you the option of handling errors as warnings, errors, or exceptions. However, when you create a new PDO connection object, PDO always throws a PDOException object if an error occurs.

What is PDO error?

If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling). The prepare statement likely caused an error because the db would be unable to prepare the statement.


setAttribute will cause PDO to throw up errors or exceptions - the latest when you execute the query.

For emulated prepared statements, there is no check in prepare():

Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

But there will be one in execute() when the query gets sent to the server.

However, the mySQL driver supports native prepared statements since mySQL 4.1 anyway, so this shouldn't apply. Using

$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

must cause an exception for the query you use.


I too was trying to get the information from errorInfo() at the database handle level, but I ended up getting the information from the statement level with PDOStatement::errorInfo()

Per PHP web site:

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.


This will print error code as well its corresponding detailed message.

Advice: this is just a demonstration. Just use for debugging purpose. Don't enable to show error messages to the public in a release version.

try{
connection=$this->get_connection();//here i brought my connection string
connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
/**
Do your works here..
//$statement=$connection->prepare($sql);
//if you are using errorInfo use after prepare statement before execute.here in this method i am not using it.
//print_r($statement->errorInfo());
**/

$statement->execute();
}
catch(PDOException $e) {
              //this will echo error code with detail
              //example: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'nasme' in 'field list'
              echo $e->getMessage();
            }
//$statement=null;

You need to first execute the query and then check for errors: So do it like this:

 $sth->execute();

and then check for errors. Then you will get errors, if any.