Building a Shopping Cart using CodeIgniter’s Shopping Cart Class

CodeIgniter Shopping cart class
Late last year CodeIgniter v1.7.2 was released with a lot of improvements and bug fixes. This version is now compatible with PHP5.3.0, they added is_php() to Common functions to facilitate PHP version comparisons, modified show_error() to allow sending of HTTP server response codes, and all internal uses now send proper status codes, Form helper improved and a new class which we are about to cover in this tutorial the Shopping Cart Class.


Class Overview from CodeIgniter User Guide section.

The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove items from the cart.

The Cart class utilizes CodeIgniter’s Session Class to save the cart information to a database, so before using the Cart class you must set up a database table as indicated in the Session Documentation , and set the session preferences in your appliction/config/config.php file to utilize a database.

To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function:

$this->load->library('cart');

Once loaded, the Cart object will be available using: $this->cart

Adding an Item to The Cart

To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert() function, as shown below:


$data = array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 39.95,
               'name'    => 'T-Shirt',
               'options' => array('Size' => 'L', 'Color' => 'Red')
            );

$this->cart->insert($data);

The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has options associated with it. Use an array for options, as shown above.

The five reserved indexes are:

  • id – Each product in your store must have a unique identifier. Typically this will be an “sku” or other such identifier.
  • qty – The quantity being purchased.
  • price – The price of the item.
  • name - The name of the item.
  • options – Any additional attributes that are needed to identify the product. These must be passed via an array.

Cart Class Function reference
Function Reference

» $this->cart->insert();

Permits you to add items to the shopping cart.

» $this->cart->update();

Permits you to update items in the shopping cart.

» $this->cart->total();

Displays the total amount in the cart.

» $this->cart->total_items();

Displays the total number of items in the cart.

» $this->cart->contents();

Returns an array containing everything in the cart.

» $this->cart->has_options(rowid);

Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

» $this->cart->options(rowid);

Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

» $this->cart->destroy();

Permits you to destroy the cart. This function will likely be called when you are finished processing the customer’s order.

Lets Make our Simple Shopping Cart

Lets start to by creating our Product controller

	function Products(){

		parent::Controller();

		//load the cart library
		//you can do this to your autoload.php
		$this->load->library('cart');
		$this->load->helper('url');
	}

	function index(){

		//pull the list of products from your database.

		$vars['pList'] = $this->productModel->getProducts();

		//pList should have your product details. (product id, description, price, product image, etc.)
		//load the view then pass the product data.

		$this->load->view('product_view', $vars);
	}

	function addToCart($productId) {

		//you need the details for the selected products to be added to your cart

		$item = $this->productModel->getProductById($productId);

		//$item variable must have the 4 required indexes necessary for inserting data to our cart.

		//sample

		/* $item =	array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 99.99,
               'name'    => 'Monitor',
               'options' => array('Color' => 'Black')
            );
		*/

		//insert item to cart

		$this->cart->insert($item);

		//after a user click the add to cart button in our product page we could redirect him
		//back to our product page

		redirect('products');

		//but if you use ajax to add item to your cart maybe you could use an echo fucntion.

	}

And then our cart controller

	function Cart(){
		parent::Controller();

		$this->load->library('cart');
		$this->load->helper('form');
		$this->load->helper('url');

	}

	function index(){

		//load your cart view

		$this->load->view('cart_view');

	}

	function updateCart(){

		//To update the information in your cart, you must pass an array containing the Row ID
		//and quantity to the $this->cart->update() function.

		//ID and the Quantity can be pass by submiting the form in our cart view.

		//Our cart view can generate a data like this
		//I try add an item to cart then try to submit the form and using var dump I got something like this
		/*
		Array (
			[1] => Array (
					[rowid] => 79fcbc10fafd6b1ea8202991ba15502c
					[qty] => 12 )
			[2] => Array (
					[rowid] => e942e3675eab2e6e688bdf6a851a0a54
					[qty] => 34 )
			)
		*/

		if($_POST){

			$data = $_POST; //for the sake of this example we are going to use the $_POST variable directly

		}

		$this->cart->update($data);

		redirect('cart');
	}

And finally our Cart View

<?php echo form_open('cart/updatecart'); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="1">
<tr>
  <th>QTY</th>
  <th>Item Description</th>
  <th style="text-align:right">Item Price</th>
  <th style="text-align:right">Sub-Total</th>
  </tr>
<?php $i = 1; ?>
<?php foreach($this->cart->contents() as $items): ?>
 <?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>

  <tr>
  <td><?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
  <td>
  <?php echo $items['name']; ?>

  <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>

  <p>
  <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>

  <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />

  <?php endforeach; ?>
  </p>

  <?php endif; ?>

  </td>
  <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
  <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
  </tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
  <td colspan="2"> </td>
  <td ><strong>Total</strong></td>
  <td >$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
  </tr>
</table>
<p><?php echo form_submit('', 'Update your Cart'); ?></p>

And then a sample of a product View. What is important here is show how our addtocart function being called.

<table>
  <tr>
  <td>Name</td>
  <td>Desc</td>
  <td>Price</td>
  <td></td>
  </tr>
<?php foreach ($pList as $item) { ?>
 <tr>
  <td><?php echo $item['name']; ?></td>
  <td><?php echo $item['desc']; ?></td>
  <td><?php echo $item['price']; ?></td>
  <td><a href="addtocart/<?php echo $item['id']; ?>">Add To cart</a></td>
  </tr>

<?php } ?>
</table>

Subscribe to my RSS for more.

PG

Author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

Related Post

Delicious

24 Responses to “Building a Shopping Cart using CodeIgniter’s Shopping Cart Class”

  1. Great Tut! Really thanks !

    but is everything all right ? it’s been a while !

  2. Great Tut.

    Welcome back, I hope you stay for good.

    Thankyou

  3. ¡Me encanta tu sitio, sobre todo las notas de CodeIgniter!
    ¡Gracias por compartir tus conocimientos!

  4. Carlos Andres Restrepo Reply 22. Jan, 2010 at 2:05 am

    Thankyou muy buen aporte

  5. Im just starting out with CI, so sorry if im missing something obvious, but aren’t we missing the model? If I create a Products and Cart controller and then the proper views, I get errors because it is making calls to productModel which is never shown in this tutorial.

  6. Nice tutorial — i built my own cart with CI 1.7.1 and have been reluctant to redo it now with the 1.7.2 cart library in place.

    I guess it’s a case if ‘if it aint broken, dont fix it’ principal. But if anything your artical has given me a good insight on how it is being used.

    Will definitely use the CI library, just not yet! :)

  7. Victor is right.

    $this->load->model(‘productModel’);

    is missing :)

  8. Thanks a lot for this tutorial!!

    The user guide doesn’t really give enough detail for me to understand.

  9. great one, thx for the effort.

  10. wow! so clean.. i love codeigniter. it’s so nice.

  11. could you give a tutorial on how to integrate this to paypal? thank you!

  12. hmmmmmmmmm. This tutorial should include the model… like what is the function of $this->productModel->getProductById($productId);

  13. hmmmmmmmmm. This tutorial should include the model… like what is the function of the getProductbyId

Leave a Reply