PHP + MySQL transactions examples

后端 未结 9 2324
一整个雨季
一整个雨季 2020-11-21 11:50

I really haven\'t found normal example of PHP file where MySQL transactions are being used. Can you show me simple example of that?

And one more question. I\'ve alr

9条回答
  •  渐次进展
    2020-11-21 12:04

    When using PDO connection:

    $pdo = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // this is important
    ]);
    

    I often use the following code for transaction management:

    function transaction(Closure $callback)
    {
        global $pdo; // let's assume our PDO connection is in a global var
    
        // start the transaction outside of the try block, because
        // you don't want to rollback a transaction that failed to start
        $pdo->beginTransaction(); 
        try
        {
            $callback();
            $pdo->commit(); 
        }
        catch (Exception $e) // it's better to replace this with Throwable on PHP 7+
        {
            $pdo->rollBack();
            throw $e; // we still have to complain about the exception
        }
    }
    

    Usage example:

    transaction(function()
    {
        global $pdo;
    
        $pdo->query('first query');
        $pdo->query('second query');
        $pdo->query('third query');
    });
    

    This way the transaction-management code is not duplicated across the project. Which is a good thing, because, judging from other PDO-ralated answers in this thread, it's easy to make mistakes in it. The most common ones being forgetting to rethrow the exception and starting the transaction inside the try block.

提交回复
热议问题