Return error message for queries in PHP database

Asked

Viewed 5,744 times

3

Is there any way to receive error messages from the database when trying to execute a Query with PHP PDO?

I’ve tried to get one try catch in the method ->execute() but the class PDOException captures nothing.

Does anyone have any idea how to be?

  • Yes it is possible! There are some ways to do this with exceptions or error returns.

1 answer

0


To manipulate the error returning by a query you can use exceptions or function returns (errors).

  • Exceptions

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

To capture bank errors as exceptions first set this in PDO construction

$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 standard approach is this, check the return of execute() if false use the method errorInfo() for 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());
}
  • All you have to do is set the PDO::ERRMODE is enough to receive messages from the bank, THANK YOU!

  • @Adrianoluz has another PDO feature on this link => http://answall.com/a/68238/91

Browser other questions tagged

You are not signed in. Login or sign up in order to post.