How to create transactions with PHP and MySQL?

Spread the love

Sometimes, we want to create transactions with PHP and MySQL.

In this article, we’ll look at how to create transactions with PHP and MySQL.

How to create transactions with PHP and MySQL?

To create transactions with PHP and MySQL, we can use the beingTransaction and commit methods.

For instance, we write

try {
    $db->beginTransaction();
    
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');
    
    $db->commit();
} catch (\Throwable $e) {
    $db->rollback();
    throw $e;
}

to call beginTransaction on the $db PDO connection object.

Then we call query to make the queries.

And then we call commit to commit the transaction if all the queries succeed.

We add a catch block to catch any errors raised by the queries.

And if there’re any errors, we call rollback to roll back the transaction.

Conclusion

To create transactions with PHP and MySQL, we can use the beingTransaction and commit methods.

Leave a Reply

Your email address will not be published.