Return error message for database queries with PHP

3

Is there any way to get error messages coming from the database when trying to run a Query with the PHP PDO?

I have tried to put a try catch in the ->execute() method but the PDOException class does not capture anything.

Does anyone have any idea how to do it?

    
asked by anonymous 29.03.2016 / 22:42

1 answer

0

To manipulate the error returning by a query one can use exceptions or returns of functions (errors).

  • Exceptions

The fourth argument is an array where some settings can be passed between them PDO::ATTR_ERRMODE and the PDO::ERRMODE_EXCEPTION value defines that the errors will be treated as exceptions.

To capture bank errors as exceptions first defined this in PDO building

$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$db = new PDO('pgsql:host=localhost;dbname=test', 'root', '', $opcoes);

$sql = "select ... invalido";
$stmt = $db->prepare($sql);

try{
    $stmt->execute();
}catch(PDOException $e){
    echo $e->getMessage();
}
  • Function return

The default approach is to check the return of execute() if false use the errorInfo() method to get details about the error with the message and SQLState.

$db = new PDO('pgsql:host=localhost;dbname=test', 'root', '');
$sql = "select ... invalido";
$stmt = $db->prepare($sql);

if($stmt->execute() === false){
    echo "<pre>";
    print_r($stmt->errorInfo());
}
    
29.03.2016 / 22:50