4343l3.text

Listing 3. Creating a New Customer

<?php

function cart_new() {
   global $conn, $customer_id, $feedback;

   //start a transaction
   query("BEGIN WORK");

   //query postgres for the next value in our sequence
   $res=query("SELECT nextval('seq_customer_id')");

   //check for errors
   if (!$res || pg_numrows($res)<1) {
         $feedback .= pg_errormessage($conn);
         $feedback .= ' Error - Database didn't return next value ';
         query("ROLLBACK");
         return false;
   } else {
         //set that value in a local var
         $customer_id=pg_result($res,0,0);

         //register the id with PHP4
         session_register('customer_id');

         //insert the new customer row
         $res=query("INSERT INTO customers (customer_id) VALUES ('$customer_id')");

         //check for errors
         if (!$res || pg_cmdtuples($res)<1) {
               $feedback .= pg_errormessage($conn);
               $feedback .= ' Error - couldn't insert new customer row ';
               query("ROLLBACK");
               return false;
          } else {
               //commit this transaction
               query("COMMIT");
               return true;
          }
      }
}

?>

