PHP PDO transaction with multiple objects

Asked

Viewed 176 times

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 do the INSERT in each User and Product class.

I am trying now on two objects to make 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 fault occurs in the section below:

$conn->connectionDB()->rollBack();
  • 1

    If he entered the catch. Failure occurs in the try. What the $ex.getMessage(); informs?

  • 1

    Another thing that $conn->connectionDB()->rollBack(); cannot be used as the object $conn was not instantiated within the catch.

1 answer

2


you need to include the connection instance before Try, so it is available in 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();
}
  • I made a transaction class and passed the INSERT I needed. I made the connection before Try and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.