<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>
<channel>
	<title>Matt&#039;s Blog &#187; cart</title>
	<atom:link href="http://www.roaringmoon.com/blog/tag/cart/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.roaringmoon.com/blog</link>
	<description>Odds and Ends from inside my head...</description>
	<lastBuildDate>Fri, 28 Oct 2011 17:51:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Shopping Cart for CodeIgniter</title>
		<link>http://www.roaringmoon.com/blog/2009/06/09/shopping-cart-for-codeigniter/</link>
		<comments>http://www.roaringmoon.com/blog/2009/06/09/shopping-cart-for-codeigniter/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 13:17:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[cart]]></category>
		<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[php]]></category>
		<guid isPermaLink="false">http://www.roaringmoon.com/blog/?p=41</guid>
		<description><![CDATA[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 ...]]></description>
			<content:encoded><![CDATA[<p>Despite much Googling, I haven&#8217;t been able to find a ready made shopping cart for the <a href="http://codeigniter.com/">CodeIgniter</a> PHP framework. Unfortunately one of my current projects requires such a thing, so I decided to roll my own. Starting from the code here: <a href="http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart">http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart</a>, I made a few changes to fit the CodeIgniter way of doing things.</p>
<p>The revised version looks like this:</p>
<pre class="brush: php;">&lt;?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() {
    }
}
</pre>
<p>The associated view looks like this:</p>
<pre class="brush: php">
Basket Total: &amp;pound;&lt;?= $grand_total ?>
&lt;?php
if (isset($basket)) {
    ?>
<form method="post" id="cart-form" action="&lt;?= 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>
            &lt;?php
            foreach ($basket as $val) {
                ?>
<tr>
<td>&lt;?= $val['id'] ?></td>
<td>&lt;?= $val['caption'] ?></td>
<td>&lt;?= $val['price'] ?></td>
<td>
<input type="text" name="qty' &lt;?= $val['id'] ?>'" value="&lt;?= $val['qty'] ?>" size="3" maxlength="3" /></td>
<td>&lt;?= $val['total'] ?></td>
<td><a href="&lt;?= site_url() . 'delete_item/' . $val['id'] ?>">[x]</a></td>
</tr>
        &lt;?php
    }
    ?>
        </table>
<input type="submit" name="submit" value="Update Cart" />
    </form>
<a href="&lt;?= site_url() . 'delete_all' ?>">Empty Cart</a>
<a href="&lt;?= site_url() . 'checkout' ?>">Checkout</a>
    &lt;?php
} else {
    ?>
Your shopping basket is empty.
    &lt;?php
}
?>
</pre>
<p>The code also assumes a database &#8220;stock_table&#8221; with the following structure:</p>
<pre class="brush: sql;">
	--
	-- 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 ;
</pre>
<p>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&#8217;s worth looking at the CodeIgniter PayPal library <a href="http://codeigniter.com/wiki/PayPal_Lib/">http://codeigniter.com/wiki/PayPal_Lib/</a> to help you.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="medium" count="1" href="http://www.roaringmoon.com/blog/2009/06/09/shopping-cart-for-codeigniter/">{lang: 'en-GB'}</g:plusone></div><p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://www.roaringmoon.com/blog/2009/06/09/shopping-cart-for-codeigniter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

