hal1on
{ USER }
posts: 5
last: 13-Jul-2008
TITLE: Multiple SQL Queries and Transactions in PHP
DESCRIPTION: How to do SQL transactions with PHP/MySQL
Submitted: 25-Sep-2007 23:14:12 ( 1yrs 14w 6d 6h ago ) Language: PHP (*.php *.php4 *.php5 *.phtml)
Views: 329 Lines of Code: 89 LINES
Rating:
rate: star1
star2
star3
star4
star5
dstar1
dstar2
dstar3
dstar4
dstar5  ( rated! )
  { 4.00 / 5 }
Difficulty: Advanced
Bookmark
/*
this db class/function will accept an array of arrays holding querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc

NB this will require the mysql innodb engine (ie.. not myisam!)
*/

/* Database Constants  */

define("DB_SERVER", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");


/* DB Class */

class MySQLDB
{
   private $connection;          // The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }


   /* Transactions functions */

   function begin(){
      $null = mysql_query("START TRANSACTION", $this->connection);
      return mysql_query("BEGIN", $this->connection);
   }

   function commit(){
      return mysql_query("COMMIT", $this->connection);
   }
   
   function rollback(){
      return mysql_query("ROLLBACK", $this->connection);
   }

   function transaction($q_array){
   	  $retval = 1;

      $this->begin();

   	  foreach($q_array as $qa){
   	     $result = mysql_query($qa['query'], $this->connection);
   	     if(mysql_affected_rows() == 0){ $retval = 0; }
   	  }

      if($retval == 0){
         $this->rollback();
         return false;
      }else{
         $this->commit();
         return true;
      }
   }

};

/* Create database connection object */
$database = new MySQLDB;







// then from anywhere else simply put the transaction queries in an array or arrays like this:

// ((NB: remember if taking query info from a web form input, you will need to escape special chars!))

   function function(){
      global $database;

      $q = array ( 
         array("query" => "UPDATE table WHERE something = 'something'"),
         array("query" => "UPDATE table WHERE something_else = 'something_else'"),
         array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
      );

      $database->transaction($q);

   }