Listing 4. Adding Items to a Cart
  
<?php
function cart_add_item($item_id,$quantity=1) {
     global $customer_id, $feedback, $conn;
     //no need to start a transaction, as only one
     //query will be updating the database
     //query postgres for the next value in our
     //sequence
     $res=query("SELECT * FROM item_inventory WHERE part_number='$item_id'");
     //check for errors
     if (!$res || pg_numrows($res)<1) {
           $feedback .= pg_errormessage($conn);
           $feedback .= ' Error-item not found ';
           return false;
     } else {
           //item was legit-see if already in cart. If so, increment quantity
           //start a transaction so we can lock the rows if they are found
           query("BEGIN WORK");
           $res=query("SELECT * FROM cart_items ".
                  "WHERE part_number='$item_id' AND customer_id='$customer_id' FOR UPDATE");
           //check for errors
           if (!$res || pg_numrows($res)<1) {
                  //insert it into the cart
                  $res=query("INSERT INTO cart_items ".
                        "(customer_id,part_number,quantity)".
                        "VALUES ($customer_id,$item_id,$quantity)");
                  //check for errors on insert
                  if (!$res || pg_cmdtuples($res) < 1) {
                        $feedback .= pg_errormessage($conn);
                        $feedback .= ' Error-couldn't insert into cart ';
                        //nothing was changed but it's good form to cancel the transaction
                        query("ROLLBACK");
                        return false;
                   } else {
                        query("COMMIT");
                        return true;
                   }
            } else {
                   //item already in cart-increment quantity
                   $res=query("UPDATE cart_items SET quantity = quantity + $quantity ".
                         "WHERE part_number='$item_id' AND
customer_id='$customer_id'");
                   if (!$res || pg_cmdtuples($res) < 1) {
                         $feedback .= pg_errormessage($conn);
                         $feedback .= ' Error-couldn\'t increment quantity in cart ';
                         //again nothing was changed
                         query("ROLLBACK");
                         return false;
                   } else {
                         //commit the updated quantity to the database
                         query("COMMIT");
                         return true;
                   }
            }
      }
}
?>
  
  
  
  
  
  
  
  
  
    Copyright © 1994 - 2014 Linux Journal.  All rights reserved.