Shopping Cart for CodeIgniter
Despite much Googling, I haven’t been able to find a ready made shopping cart for the CodeIgniter PHP framework. Unfortunately one of my current projects requires such a thing, so I decided to roll my own. Starting from the code here: http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart, I made a few changes to fit the CodeIgniter way of doing things.
The revised version looks like this:
<?php// Based on http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cartclass Cart extends Controller {function Cart(){parent::Controller();$this->load->library('session');$this->load->helper('url');}function index(){$cart = $this->session->userdata('cart');if ($cart) {$items = explode(',',$cart);$contents = array();foreach ($items as $item) {$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;}}if ($contents){$id_list = '';foreach(array_keys($contents) as $val)$id_list .= $this->db->escape($val) .',';$id_list = substr($id_list,0,len($id_list) - 1);$query_string = "SELECT * FROM stock_table WHERE id IN(".$id_list.")";$query = $this->db->query($query_string);f ($query->num_rows() > 0){$basket = array();foreach ($query->result() as $row){$basket[] = array('id' => $row->id, 'caption' => $row->caption, 'price' => $row->price,
'qty' => $contents[$row->id], 'total' => $contents[$row->id] * $row->price);}}}$data = array();if ($basket){$data['basket'] = $basket;$grand_total = 0;foreach($basket as $item)$grand_total += $item[total];$data['grand_total'] = sprintf("%01.2f", $grand_total);}else$data['grand_total'] = sprintf("%01.2f", 0);$data['page'] = 'cart_view';$data['title'] = "Your basket";$this->load->view('template/container',$data);}function add_item($item_id=''){$cart = $this->session->userdata('cart');if ($cart) {$cart .= ','.$item_id;} else {$cart = $item_id;}$this->session->set_userdata(array('cart' =>$cart));redirect('/cart/', 'refresh');}function delete_item($item_id=''){$cart = $this->session->userdata('cart');if ($cart) {$items = explode(',',$cart);$newcart = '';foreach ($items as $item) {if ($item_id != $item) {if ($newcart != '') {$newcart .= ','.$item;} else {$newcart = $item;}}}$cart = $newcart;}$this->session->set_userdata(array('cart' =>$cart));redirect('/cart/', 'refresh');}function delete_all(){$this->session->unset_userdata('cart');redirect('/cart/', 'refresh');}function update_cart(){if ($cart) {$newcart = '';foreach ($_POST as $key=>$value) {if (stristr($key,'qty')) {$id = str_replace('qty','',$key);$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);$newcart = '';foreach ($items as $item) {if ($item_id != $item) {if ($newcart != '') {$newcart .= ','.$item;} else {$newcart = $item;}}}for ($i=1;$i<=$value;$i++) {if ($newcart != '') {$newcart .= ','.$id;} else {$newcart = $id;}}}}}$this->session->set_userdata(array('cart' =>$newcart));redirect('/cart/', 'refresh');}function checkout(){}}
The associated view looks like this:
<p>Basket Total: £<?=$grand_total?></p><?phpif (isset($basket)){?><form method="post" id="cart-form" action="<?=site_url().'update_cart'?>"><table><tr><td>ID:</td><td>Desc:</td><td>Price:</td><td>Quantity:</td><td>Total:</td><td>Delete?</td></tr><?phpforeach ($basket as $val){?><tr><td><?=$val['id']?></td><td><?=$val['caption']?></td><td><?=$val['price']?></td>
<td><input type="text" name="qty'<?=$val['id']?>'" value="<?=$val['qty']?>" size="3" maxlength="3" /></td>
<td><?=$val['total']?></td><td><a href="<?=site_url().'delete_item/'.$val['id']?>">[x]</a></td></tr><?php}?></table><input type="submit" name="submit" value="Update Cart" /></form><p><a href="<?=site_url().'delete_all'?>">Empty Cart</a></p><p><a href="<?=site_url().'checkout'?>">Checkout</a></p><?php}else{?><p>Your shopping basket is empty.</p><?php}?>
The code also assumes a database “stock_table” with the following structure:
---- Table structure for table `stock_table`--CREATE TABLE IF NOT EXISTS `stock_table` (`id` int(10) unsigned NOT NULL auto_increment,`caption` varchar(20) NOT NULL,`quantity` int(10) NOT NULL default '0',`price` float NOT NULL,PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
This code has yet to be put to the test in a production environment, so use it entirely at your own risk. You will also notice that the checkout function has not been completed. This is a project for another day, and it’s worth looking at the CodeIgniter PayPal library http://codeigniter.com/wiki/PayPal_Lib/ to help you.
2 Comments
Other Links to this Post
RSS feed for comments on this post. TrackBack URI
By sylvie, August 5, 2009 @ 6:07 pm
Interesting indeed.
I’m looking for an open-source shopping cart based on codeigniter framework.
Do you know one ?
By Julian, August 22, 2009 @ 3:56 am
Hi, how are you?
Did you try the new CI Cart Library that is on trunk? Probably will help you.
http://www.jigniter.com/simple-shopping-cart-in-codeigniter
I am trying it right now and sounds very promising.