Demonstarting Drupal transaction using db_transaction()

Public

Get raw version
php
  1. /**
  2.  * Demonstarting Drupal transaction using db_transaction()
  3.  */
  4. function my_transaction_function() {
  5. // The transaction opens here.
  6. $txn = db_transaction();
  7. try {
  8. $id = db_insert('example')
  9. ->fields(array(
  10. 'field1' => 'mystring',
  11. 'field2' => 5,
  12. ))
  13. ->execute();
  14. my_other_function($id);
  15. return $id;
  16. }
  17. catch (Exception $e) {
  18. // Something went wrong somewhere, so roll back now.
  19. $txn->rollback();
  20. // Log the exception to watchdog.
  21. watchdog_exception('type', $e);
  22. }
  23. // $txn goes out of scope here. Unless the transaction was rolled back, it
  24. // gets automatically commited here.
  25. }
  26. function my_other_function($id) {
  27. // The transaction is still open here.
  28. if ($id % 2 == 0) {
  29. db_update('example')
  30. ->condition('id', $id)
  31. ->fields(array('field2' => 10))
  32. ->execute();
  33. }
  34. }