Multiple insertion in mysql tables
i am facing a problem in inserting into mysql tables. I have 3 related tables to insert on save, but I want to make sure that either all of the queries are run, or none of them. I have done this in C#, but I want to know how i can do i开发者_如何学Got in PHP.
In order to have a all or nothing behavior, you'll want to use a transaction :
- start the transaction
- do your queries
- if all queries have been executed successfully, commit
- else, rollback.
In PHP, if working with PDO, you'll want to use the PDO::beginTransaction(), PDO::commit() and PDO::rollback() methods.
If working with MySQLi, you'll want to use mysqli::commit() and mysqli::rollback() -- after having disabled autocommit with mysqli::autocommit().
To detect if a query has failed, you'll want to :
- With PDO, use
PDO::setAttribute()so exceptions are thrown when an error occurs. - With MySQLi,
mysqli::query()returnsfalseif a query fails.
加载中,请稍侯......
精彩评论