开发者

How to make sure two MySQL queries are successful?

I have two MySQL queries in my PHP code.

Basically I need the two queries to execute (they are two INSERT) queries and both must be successful. If for example query1 is successful but query2 is not successful; I need to rollback query1 as both queries must be successful.

I am using MyISAM and I know I cannot do rollbacks etc but is there any way I can overcome my problem (another solution) to do what I want?

They both depend on each other as query1 stores开发者_开发百科 data from form and query2 inserts some other details into another table (it's basically a counter) that tracks total counts for a referral system.


One option would be to store the ID of the insterted record in the first table. If the second query fails, use a delete query to remove the record inserted by the first query. I would advice you to change the engine to InnoDB however, so you can use transactions. Or do you a specific reason to use MyISAM (like full text searches?)


After the first insert, you can get the ID using mysql_insert_id() and store it.

Then when you do the second query, get that ID as well. If the ID is null, then it means it wasn't successful, and you've got the old ID so you can then delete it, like so

DELETE FROM table WHERE id='$insertId'

Edit:

Just a note, this isn't a complete solution, the only true way would be to convert to InnoDB


Sounds to me like you need transactions.

http://www.techrepublic.com/article/implement-mysql-based-transactions-with-a-new-set-of-php-extensions/6085922

They allow you to rollback an entire series of database modifications within a single transaction.


Transactions are the answer. If your chosen storage engine does not support them, and you have this scenario, then you probably picked the wrong storage engine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜