Stack Stack - 5 months ago 8
PHP Question

Why doesn't execute() return true on error?

Please take a look at my code:

try {
// db connection here
$stm = $dbh->prepare("INSERT INTO mytable(id,token) values(NULL,$token)")->execute();

} catch(PDOException $e){
if ( $stm ){
echo 'inserting fails';
} else {
echo 'something else is wrong';
}
}

-- `token` column is unique


Current outputs:


  • The row inserted successfully.

  • It prints
    something else is wrong
    error for both {duplicate entry} and {SQL syntax}



Expected outputs:


  • The row inserted successfully.

  • It prints
    inserting fails
    error for {duplicate entry}

  • It prints
    something else is wrong
    error for {SQL syntax}






Ok, if I write my code like following (without chaining), then expected output happens:

$stm = $dbh->prepare("INSERT INTO mytable(id,token) values(NULL,$token)");
$stm->execute();


Well I want to know, when can I chain those PDO statements?

Answer

An exception can only be thrown in either the prepare or execute methods. Either of those is going to happen before $stm =. In other words, if an exception is going to be thrown, the assignment to $stm is always going to be skipped, meaning the variable doesn't exist at all in your catch block. Therefore it can only evaluate to false, and will in fact produce a notice about being undefined.