Welcome Guest, Not a member yet? Register   Sign In
Basic Cart Example

I just started playing with the cart class today. I looked around and didn't see a decent example of the basic functions working together so I whipped up a rough example for newbies to play with who are trying the cart for the first time and are confused.

This is a very basic example and I only used a controller since I'm just roughing it together as I post this. No proper MVC is being used - everything is in the controller so you can absorb what's happening very quickly.

The code may very well be missing things that advanced programmers are free to mention.


The one table so far, "products"
CREATE TABLE `products` (
  `product_id` int(11) NOT NULL auto_increment,
  `category_id` int(11) NOT NULL default '0',
  `product_name` varchar(50) default NULL,
  `product_short_desc` varchar(255) default NULL,
  `product_long_description` text,
  `product_price` varchar(50) default NULL,
  `product_added` timestamp NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`product_id`)

insert into `products` values('4','0','Test Product','a short description','a long description','29.95',null),
('5','0','Test Product 2','a short description','a long description','1.95',null);

Controller Code up next...

Controller Code:

class Shop extends Controller {

        function __construct()
        function index()
                // show a couple products
                $products = $this->db->get('products');
                foreach ($products->result() as $product)
                        echo '<h3>' . anchor('shop/detail/' . $product->product_id, $product->product_name) . '</h3>';
                        echo '<p><b>' . $product->product_price . '</b></p>';
                        echo '<p>' . $product->product_short_desc . '</p>';
                        echo '<hr>';
        function detail()
                // show the product and an "add to cart" link
                $product_id = $this->uri->segment(3);
                $product = $this->db->where('product_id', $product_id)->get('products')->row();
                echo '<h1>' . $product->product_name . '</h1>';
                echo '<p>' . $product->product_long_description . '</p>';
                echo '<p><b>' . $product->product_price . '</b></p>';
                echo form_open('shop/add_to_cart');
                echo form_hidden('product_id',$product->product_id);
                echo form_hidden('product_name', $product->product_name);
                echo form_hidden('product_price', $product->product_price);
                echo form_input('qty', '1');
                echo form_submit('', 'Add to Cart');
                echo form_close();
        function add_to_cart()        
                // add the selected product to the cart
                $data = array(
                        'id' => $this->input->post('product_id'),
                        'qty' => $this->input->post('qty'),
                        'price' => $this->input->post('product_price'),
                        'name' => $this->input->post('product_name'),
                        'options' => array()
        function update_cart()
                for ($i = 1; $i <= $this->cart->total_items(); $i++)
                        $item = $this->input->post($i);
                        $data = array(
                                'rowid' => $item['rowid'],
                                'qty' => $item['qty']
        function show_cart()
                &lt;?php echo form_open('shop/update_cart'); ?&gt;

                <table cellpadding="6" cellspacing="1" style="width:100%" border="0">
                <p>&lt;?php echo anchor('shop', 'Continue Shopping'); ?&gt;</p>
                  <th>Item Description</th>
                  <th style="text-align:right">Item Price</th>
                  <th style="text-align:right">Sub-Total</th>
                &lt;?php $i = 1; ?&gt;
                &lt;?php foreach($this->cart->contents() as $items): ?&gt;
                    &lt;?php echo form_hidden($i.'[rowid]', $items['rowid']); ?&gt;
                      <td>&lt;?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?&gt;</td>
                        &lt;?php echo $items['name']; ?&gt;
                            &lt;?php if ($this->cart->has_options($items['rowid']) == TRUE): ?&gt;
                                    &lt;?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?&gt;
                                        <strong>&lt;?php echo $option_name; ?&gt;:</strong> &lt;?php echo $option_value; ?&gt;<br />
                                    &lt;?php endforeach; ?&gt;
                            &lt;?php endif; ?&gt;
                      <td style="text-align:right">&lt;?php echo $this->cart->format_number($items['price']); ?&gt;</td>
                      <td style="text-align:right">$&lt;?php echo $this->cart->format_number($items['subtotal']); ?&gt;</td>
                &lt;?php $i++; ?&gt;
                &lt;?php endforeach; ?&gt;
                  <td colspan="2"> </td>
                  <td class="right"><strong>Total</strong></td>
                  <td class="right">$&lt;?php echo $this->cart->format_number($this->cart->total()); ?&gt;</td>
                <p>&lt;?php echo form_submit('', 'Update your Cart'); ?&gt;</p>
        function clear_cart()

Hi Joe,


Many thanks for a great example. I played around with it and came up with the above demo.
I am now off to incorporate it into my site and try and sell some jokes Smile

I'm glad you were able to make use of it. That was exactly the point. Jump in and play with the cart so you understand how it works. Good luck with the shop.

Looking good, thanks Joe. Is there a way of displaying the products all on one page, using checkboxes next to the product(s) you want and then when you submit it adds them to the cart?

An example of something i want goes like this:

A products one page where users enter personal details and select the products they want. When the user submits, it inserts that data into a database. Obviously at a later date if the user wants to change what they want they can do. There will be no quanities, everything will be 1.

Thanks, David.


Thanks million Smile

Will showcase mine when I'm done Smile

Whoop Whoop!


Hmm, any ideas on how to have a product that's say a 10 buck discount coupon?
have been digging deep and setting -ve qty/price doesn't seem to get through to the library, messed about there, learned to love ctrl-z!


ok got around -ve prices, and qtys by commenting out the is valid number style checking in the class
seach for "Prep the quantity. It can only be a number. Duh..." and "Prep the price. Remove anything that isn't a number or decimal point." while i was ther ei also got rid of the name format check (threw wobblies with £ signs "Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods."

all in system/libraries/Cart.php


How do I implement the checkout functionality in the above function?

add a checkout form to the code in the show_cart function
duplicate show_cart renaming it checkout

then edit the checkout function to do whatever you want to do with the data (ie rip out markup and create an sql till insert or soemthing)

play .. it'll become clear Smile

Theme © iAndrew 2016 - Forum software by © MyBB