Handle MySQL transaction in PHP

To handle MySQL transaction in PHP, you use the following steps:

Start the transaction by calling the beginTransaction() method of the PDO object.

Place the SQL statements and the commit() method call in a try block.

Rollback the transaction in the catch block by calling the rollBack() method of the PDO object.

Here is an example of how to handle MySQL transaction in PHP:


<?php

// Create a PDO object

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');


// Start the transaction

$pdo->beginTransaction();


// Try to insert a new row into the database

try {

    $sql = 'INSERT INTO users (name, email) VALUES (?, ?)';

    $stmt = $pdo->prepare($sql);

    $stmt->execute(['John Doe', 'johndoe@example.com']);


    // Commit the transaction

    $pdo->commit();

} catch (PDOException $e) {

    // Rollback the transaction

    $pdo->rollBack();

}


// Close the database connection

$pdo = null;

?>


In this example, we first create a PDO object and connect to the database. Then, we start the transaction. Next, we try to insert a new row into the database. If the insert is successful, we commit the transaction. Otherwise, we rollback the transaction. Finally, we close the database connection.


Transactions are important for ensuring the integrity of your data. By using transactions, you can ensure that all of your changes are made to the database atomically, or all at once. This prevents the possibility of data corruption if something goes wrong during a data update. 

No comments:

Post a Comment