简体   繁体   中英

PHP using try-catch for multiple database queries

I am trying to implement the best way to handle database errors. I am using a mvc framework (codeigniter). When I go to create my object, I end up making multiple queries to different tables.

The problem I have is if the first query is successful, and the second fails, I get an error. However, the first query is still successful and the data is already in that table.

What I want to do is wrap all of my queries in a try block, and that way, none of the queries will be completed if any of them fail.

Is there a better way to handle this situation (perhaps codeigniter specific), by rolling back the changes?

A try block doesn't do that directly....

You need tables that support transactions ie InnoDB tables

First, you need to change the database engines of your database tables to InnoDB (if they're MyISAM anyways).

Before the database operation, you then need to start a transaction (check online for your method that suits you). I use PDO so I'd normally do this:

$pdoObject->startTransaction();

So from the return values of you queries, if it succeeds you continue to the next query, else you'll do a rollback() and end execution. It's at this point your try...catch could be useful because you could decide to throw an Exception in the event that a query execution failed. You catch it and do a rollback()

If all succeed you need to do a commit() else the changes won't be reflected

NOTE: Only InnoDB tables support transactions in MySQL

What you're looking for is called transactions .

You would have to make sure that all of your tables use InnoDB though.

if ($this->db->trans_status() !== false) {
    // do stuff
}

Is what I use to verify the transaction. Note that you can also send a boolean for test mode:

$this->db->trans_start(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM