I’m executing two different mysql queries in php,
but I also need to check if both of them where successful. If one of them failed, I need to throw an error and recall the changes made.
Is there a simple way to doing this?
PS: One is and update and the other one is an insert.
EDIT Currently I have two queries:
INSERT INTO table1 ( warning ) VALUES ( 0 ) WHERE con_id = 1
UPDATE table2 SET no_alerts = 1 WHERE con_id = 1
I’m using basic mysql_ inserts and updates, no PDO.
Transactions is what you are looking for.
There is no such thing as “plain inserts / updates”. If you are talking about using the ancient
mysql_*function please stop using them. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can’t decide, this article will help to choose. If you care to learn, here is a good PDO tutorial.If you are using PDO / mysqli you can make queries in transactions. This way you can easily rollback changes instead of committing them.
UPDATE
If you are worried about old systems (although PDO is 5.1.0+ and mysqli is 5+) there is something which you can do, but it is a hack and is prone to errors and things might get messed up. You could store the last insert id of the query and if the update query fails you can manually delete the inserted rows however as stated this is very much prone to errors on a concurrent system.
What could be the reason a query fails? Maybe there is a better way of doing things?