Received: from makus.postgresql.org ([98.129.198.125]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1T4YqA-0005DG-FA for pgsql-php@postgresql.org; Thu, 23 Aug 2012 14:56:58 +0000 Received: from mx1.gogca.com ([50.116.54.212]) by makus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1T4Yq9-0008Dp-D1 for pgsql-php@postgresql.org; Thu, 23 Aug 2012 14:56:57 +0000 Received: from booby.gogca.com (booby.gogca.com [50.116.54.212]) by mx1.gogca.com (Postfix) with ESMTPSA id 789401C516 for ; Thu, 23 Aug 2012 10:56:55 -0400 (EDT) Date: Thu, 23 Aug 2012 10:56:54 -0400 (EDT) From: Gary Chambers To: PostgreSQL PHP Users List Subject: Pg Transactional Function Message-ID: User-Agent: Alpine 2.00 (DEB 1167 2008-08-23) MIME-Version: 1.0 Content-Type: TEXT/PLAIN; format=flowed; charset=US-ASCII X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201208/3 X-Sequence-Number: 4272 All, I've written a procedural function to [hopefully] create less cluttered code when working with PostgreSQL transactions and I am soliciting criticism and suggestions on how to make it better (or to scrap it). function db_exec_transaction($dbh, $query_and_params, &$results_array, &$error_str) { if (!is_array($query_and_params)) die('Queries and parameters variable must be an array type'); pg_query($dbh, 'begin'); foreach ($query_and_params as $i => $qp) { if (empty($qp['params'])) $stmt = pg_query($dbh, $qp['query']); else $stmt = pg_query_params($dbh, $qp['query'], $qp['params']); if ($stmt === false) { $error_str = pg_last_error($dbh); pg_query($dbh, 'rollback'); return false; } else $results_array[] = $stmt; } pg_query($dbh, 'commit'); $error_str = null; return true; } A lame and mostly useless example of how I intend to call it is as follows: function foo_bar_handler($dbh) { $query_resources = array(); $queries = array(); $queries[] = array('query' => 'select * from foo for update', 'params' => array()); $queries[] = array('query' => 'delete from foo', 'params' => array()); $queries[] = array('query' => 'select * from bar where fizz = $1 and buzz = $2', 'params' => array(42, 15)); $stmt = db_exec_transaction($dbh, $queries, $query_resources, $error_str); if ($stmt === false) { echo $error_str . "\n"; return false; } /* Fetch and do something with the results */ $rows = pg_fetch_all($query_resources[0]); echo 'Rows retrieved: ' . pg_num_rows($query_resources[0]) . "\n"; $the_answers = pg_fetch_all($query_resources[2]); /* Release the resources */ pg_free_result($query_resources[0]); pg_free_result($query_resources[1]); pg_free_result($query_resources[2]); return true; } Any comments, criticisms, or suggestions are very much appreciated. Thank you, Gary Chambers