PHP + POSTGRESQL (Begin, Commit, Rollback)

0

In my application I have a certain process to perform test. This involves database with multi tables. I would like to know if it is possible to start a BEGIN; to do all the manual development, and in case of error, to realize a ROLLBACK; .

Note: Remember that they will be in separate moments, not in the same process, only with the same connection .

Example:

passo 1: "BEGIN;".
passo 2: processor manuais com form em html
passo 3: "ROLLBACK;" para re-teste;

I did not find many things about this type if situation and mostly it was recommended to cascade or Javascript validation, which is not possible.

    
asked by anonymous 13.08.2014 / 15:45

1 answer

1

Hello, you can use the PDO, see this example. Source php.net

In some cases it is necessary to disable the auto commit of the databases (mysql / postgres), it can be done using the PDO :: ATTR_AUTOCOMMIT constant

It is also interesting to enable debug mode for error handling with PDO :: ATTR_ERRMODE and PDO :: ERRMODE_EXCEPTION.

More PDO constants here: php.net

<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2', 
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
} catch (Exception $e) {
  die("Unable to connect: " . $e->getMessage());
}

try {
  $dbh->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
  $dbh->setAttribute(PDO::ATTR_ERRMODE,1);
  $dbh->setAttribute(PDO::ERRMODE_EXCEPTION,1);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate) 
      values (23, 50000, NOW())");
  $dbh->commit();

} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

The real challenge of this model would be to have separate database tables in the same transaction ... I think that would be another question.

    
13.08.2014 / 17:22