Search code examples
phpandroidmysqlpdostatements

PHP PDO - Multiple Statements - if 1 fails, don't execute the other


So I've got this PHP Service which is connect to my Android app and it executes 2 queries at once. I've read how to detect if one fails and I know that one of mine fails because EventSlots is already 0 and is an INT unsigned.

However, the other statement is successful and gets executed. Obviously, I want to only execute both, and if 1 fails, don't execute anything at all but return an error for my App.

How would I detect if one of the statements failed and STOP the other from executing? I probably can avoid using multiple statements and do 1, check if it was OK and only then execute the other. Can I achieve that with multiple statements though?

Query:

"INSERT INTO GuestList(EventID, AccountID) VALUES (7, (SELECT AccountID FROM Accounts WHERE Username = 'test'));
 UPDATE Events SET EventSlots = EventSlots-1 WHERE EventID = 7 ;"

Solution

  • Use PDO transactions http://php.net/manual/en/pdo.transactions.php . A transaction represents a bunch of queries that has to be executed in a atomic way. If something fails during the transaction it will automatically performs a rollback to the initial state.