How to intercept the result of a query?

Asked

Viewed 120 times

2

I need to test if the query made everything went well or if there was an error. I tried however I did not find anything that satisfies what I need.

Example:

I submitted an sql in the database, and it was done correctly, but there was an error in the number field, in the sql of Insert it was empty. O Try/catch will not be able to catch the error, it was submitted but was not effective.

I need to know this, whether or not she was made.

In case it is an UPDATE and IT mysql_affected_rows works perfectly, it will return the affected lines just by making a if if it’s >0 was successful if not, there was some mistake.

  • 1

    Put Quey on the question.

  • It could be any one. From Insert, from delete, from uptade, any query. I just need to know if it was successful or not

  • Look at your field in mysql if you are with not null PHP did not error "because probably this field accepts "null data"

  • @Rafaelacioly You don’t understand what I want. I need to know if there is a mechanism to know if there was an error in the sql inserted, or if everything went well. The number case is just an example I gave to understand what I want.

  • @Renanrodrigues when you run a query it returns automatically true or false, use a if if you want to confirm the execution! if Voce says it appears an error in the browser then look for enable the error in php.ini and use error_reporting(E_ALL)

  • 2

    So this is not to intercept, you want to check if the query was executed as expected by the application, yet the query can be executed without errors, but not as expected by the application. And you yourself answered your question on the final lines, although citing PDO in the tag and the function you exemplified has nothing to do with PDO.

  • 1

    Look at that answer on Soen. -> http://stackoverflow.com/a/11820939/5524514

  • 1

    mysqli_error($conexao) or $conexao->errorare responsible for storing and returning errors in a query, if any. There are also other functions responsible for the errors, see this.

  • mysqli_error($conexao)? the question has the PDO tag, unless you got it wrong.

  • 1

    It’s PDO anyway, but I’ve managed to fix it, thank you all

Show 5 more comments

1 answer

2


When using Prepared statements with 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();
}

Browser other questions tagged

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