Page 1 of 1

My First Shopping Cart

Posted: Fri Jun 06, 2008 5:10 pm
by <br>
Here's my first stab at building a shopping cart. See anything that might cause me trouble later? Right now all it does is pass # of items and order total back to index.php so that I can display the shopping cart summary. Next I'll tackle the full shopping cart page, change QTY, delete, etc.

Code: Select all

$cart = $_SESSION['cart'];
if ($cart) {
    $cart .= ','.$_GET['id'];
} else {
    $cart = $_GET['id'];
}
$_SESSION['cart'] = $cart;
$column==1;
$items = explode(',',$cart,100);
$inlist = implode(", ",$items);
$contents = array();
foreach ($items as $item) {
    $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$con = mysql_connect($db, $user, $pass) or die(mysql_error());
mysql_select_db($db2) or die(mysql_error());
$query  = "SELECT $select FROM $table WHERE id IN ($inlist)";
$result = mysql_query($query);
$column=1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $p=$row[id];
    $q=$contents[$p];
    $c=$row[price];
    $_SESSION[$column] =($c*$q);
    $column++;
}
$ppp=$column-1;
$ttt=1;
$additives = array();
while ( $ttt <= $ppp ){
    $additives[$ttt] = $_SESSION[$ttt];
    $ttt++;
}
$_SESSION['total']=array_sum($additives);
Also, my pages are pull based on an exploded URL... for example, the "sign in" page code is displayed when

Code: Select all

$exploded_URL[1]=='signin'
Categories are pulled because my table has a column that mimics my url directories... so if the url is '/Earrings/Gold', it pulls everything that has 'Earrings - Gold' in it's 'category column' (aka '$exploded_url[1] + " - " + $exploded_url[2]'). Is this a common practice or am I setting my self up for disaster?

Thanks for your input

Re: My First Shopping Cart

Posted: Mon Jun 09, 2008 2:31 am
by Christopher
I think the first improvement is that you can store arrays in the session, so I would recommend doing that instead of concat/explode. You should also do some better filtering and validation of the Request values.

Re: My First Shopping Cart

Posted: Fri Aug 08, 2008 7:25 am
by pkbruker
Actually, I'd try a different approach. Make a sepparate class for storing the cart data. You can use serialize() and unserialize() to store/retrieve the data in a database.

Using a class gives a whole lot more structure to how the cart works. Here is a small example of functions you might wanna include:

Code: Select all

 
class Cart {
 
  public function __construct() {
  }
  
  // Insert an item in the cart
  public function insert() {
  }
  
  // Remove an item from the cart
  public function remove() {
  }
  
  // Calculate total shipping cost based on cart contents
  public function calculateShipping() {
  }
  
  // Calculate total cost of items in cart
  public function calculateItems() {
  }
  
  // Calculate total cost of purchase
  public function calculateTotal() {
  }
  
  // Get all items in cart as an array
  public function getItems() {
  }
 
}