PHP

Emptying the Shopping Cart

Example 11-4 lists the cart.4 script that empties the shopping cart. The script is again a one-component module that carries out its actions, produces no output, and then redirects back to the calling page. The script removes the row in the orders table and any rows in the items table that have an order_id equal to the value of the session variable order_no. It then deletes the session variable itself, thus completing the emptying of the cart.

Example 11-4. cart.4 empties the cart
<?php
  // This script empties the cart and deletes the session
  include 'include.inc';
  set_error_handler("errorHandler");
  // Initialise the session - this is needed before
  // a session can be destroyed
  session_start(  );
  // Is there a cart in the database?
  if (session_is_registered("order_no"))
  {
     // Open a connection to the DBMS
     if (!($connection = @ mysql_connect($hostName,
                                       $username,
                                       $password)))
        showerror(  );
     if (!mysql_select_db($databaseName, $connection))
        showerror(  );
     // First, delete the order
     $query = "DELETE FROM orders
               WHERE cust_id = -1
               AND order_id = $order_no";
     if (!(@ mysql_query ($query, $connection)))
        showerror(  );
     // Now, delete the items
     $query = "DELETE FROM items
               WHERE cust_id = -1
               AND order_id = $order_no";
     if (!(@ mysql_query ($query, $connection)))
        showerror(  );
     // Finally, destroy the session variable
     session_unregister("order_no");
  }
  else
  {
     session_register("message");
     $message = "There is nothing in your cart.";
  }
  // Redirect the browser back to the calling page.
  if (session_is_registered("referer"))
  {
     session_unregister("referer");
     header("Location: $referer");
     exit;
  }
  else
     header("Location: $HTTP_REFERER");
?>