Posts tagged: php

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-cart
class 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);
            if ($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:

Basket Total: &pound;<?= $grand_total ?>

<?php if (isset($basket)) { ?>
<?php foreach ($basket as $val) { ?> <?php } ?>
ID:Desc:Price:Quantity:Total:Delete?
<?= $val['id'] ?><?= $val['caption'] ?><?= $val['price'] ?> <?= $val['total'] ?>[x]

Empty Cart

Checkout

<?php } else { ?>

Your shopping basket is empty.

<?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.

{lang: 'en-GB'}

WordPress Themes