How to intercept the result of a query?

2

I need to test whether the query you have done is fine or you hear something wrong. I have tried to find something that does not satisfy what I need.

Example:

I submitted a sql in the database, and it was done correctly, but I heard an error in the field number, in the sql of insert it was empty. The Try/catch will not be able to get the error, because it was submitted but it was not effective.

I need to know this, whether it has been honored or not.

In case of an UPDATE and DELE mysql_affected_rows it works perfectly, it will return the affected rows just by making a if if it is >0 was successful if not, he / she hears some error.     

asked by anonymous 06.12.2015 / 13:14

1 answer

2

When using prepared statements with the PDO, check the return of execute() and of course define in the PDO constructor that errors should be treated as exceptions.

$stmt = $db->prepare($sql);
if(!$stmt->execute()){
   print_r($stmt->errorInfo());
}else{
   echo 'sucesso';
}

With execptions:

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

try{
    $stmt = $db->prepare($sql);
    $stmt->execute();
}catch(PDOException $e){
    echo $e->getMessage();
}
    
06.12.2015 / 16:10