开发者

Multiple insertion in mysql tables

开发者 https://www.devze.com 2023-02-23 06:16 出处:网络
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#

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() returns false if a query fails.
0

精彩评论

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