1

I have been working on a registration system for a while. The data interacting with db is pretty sensitive so I'm trying to pay extra attention to details. This is an example of how I do inserts.

    try{
        $query="INSERT INTO account (user_id,password,salt) VALUES (:user_id,:password,:salt)";
        $stmt=$db->prepare($query);
        $params=array(':user_id'=>$userId,':password'=>$password,':salt'=>$salt);
        $result=$stmt->execute($params);
        if(!$result){
           $db->rollBack();
           doStaff();
        }
    }
    catch(PDOException $e){
       $db->rollBack();
       doStaff();
    }

I was wondering if there is any scenario that the result of an execute operation returns false but pdo does not throw exception? Should I check them both, or am I being paranoid?

Whiteley
  • 101
  • 1
  • 6
  • `$stmt->execute()` can absolutely return false without throwing an exception. However, `$db->rollback()` rolls back transactions, which you aren't using. – castis Sep 24 '14 at 19:20
  • @castis I'm using it,you can see it in the code. Can you be specific about when execute returns false without throwing exception? – Whiteley Sep 24 '14 at 19:26
  • Do you understand [transactions](http://php.net/manual/en/pdo.transactions.php)? That is what `rollback` is used for; as it stands, the call to `rollback` in your code does nothing. – wavemode Sep 24 '14 at 19:38
  • @wavemode This is only a part of my code, which includes multiple queries and of course; $db->beginTransaction() if that is what you are asking. – Whiteley Sep 24 '14 at 19:51
  • @Whitney Alright, just checking :) – wavemode Sep 24 '14 at 19:54

1 Answers1

1

The answer is yes.

A PDOException will be raised if you try to do something entirely impossible (i.e. connect to database with an incorrect hostname, authenticate with an incorrect username or password, etc.). However, if there is simply a syntax error or undefined reference in your SQL, PDOStatement::execute will silently return false. If you want to check for these errors and roll back the changes, you should certainly make sure that execute returns true.

However, instead of this, you can change this behavior so that SQL errors appear as exceptions:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Then, a single catch statement in your code will suffice.

wavemode
  • 2,076
  • 1
  • 19
  • 24