PHP PDO transaction with multiple objects

0

The idea would be this: I have 3 classes, one for connection to the bank, another for Users and another for Product.

The User class with the database tb_usuarios .

The Product class with the database tb_produtos .

I make INSERT in each User and Product class.

I'm now trying on two objects to do a transaction with the code below.

try {
    require_once 'Connection.php';

    $conn = new Connection();
    $conn->connectionDB()->beginTransaction();

    $objuser = new Usuario();
    $objuser->insertUser("Nome Teste", "[email protected]");

    $objproduct = new Produto();
    $objproduct->insertProduct("Nome Produto", "Preço", "Data");

    $conn->connectionDB()->commit();
} 

catch(PDOException $ex) {
    $conn->connectionDB()->rollBack();
    echo $ex.getMessage();
}

The failure occurs in the following section:

$conn->connectionDB()->rollBack();
    
asked by anonymous 18.04.2018 / 13:15

1 answer

2

You need to include the instance of the connection before the try, so that it is available in the catch.

require_once 'Connection.php';

$conn = new Connection();

try {

    $conn->connectionDB()->beginTransaction();

    $objuser = new Usuario();
    $objuser->insertUser("Nome Teste", "[email protected]");

    $objproduct = new Produto();
    $objproduct->insertProduct("Nome Produto", "Preço", "Data");

    $conn->connectionDB()->commit();
} 

catch(PDOException $ex) {
    $conn->connectionDB()->rollBack();
    echo $ex.getMessage();
}
    
18.04.2018 / 13:28