• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic Cart Example

#1
[eluser]SitesByJoe[/eluser]
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.

Enjoy!

The one table so far, "products"
Code:
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`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

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

#2
[eluser]SitesByJoe[/eluser]
Controller Code:

Code:
class Shop extends Controller {

        function __construct()
        {
                parent::Controller();
                $this->load->library('cart');
        }
        
        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()
                );
                
                $this->cart->insert($data);                
                redirect('shop/show_cart');
        }
        
        
        function update_cart()
        {
                //print_r($this->input->post('1'));
                for ($i = 1; $i <= $this->cart->total_items(); $i++)
                {
                        $item = $this->input->post($i);
                        $data = array(
                                'rowid' => $item['rowid'],
                                'qty' => $item['qty']
                        );
                        $this->cart->update($data);
                }
                redirect('shop/show_cart');
        }
        
        function show_cart()
        {
                //$this->load->view('public/shop/cart');
                ?&gt;
                &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>
                
                <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>
                
                &lt;?php $i = 1; ?&gt;
                
                &lt;?php foreach($this->cart->contents() as $items): ?&gt;
                
                    &lt;?php echo form_hidden($i.'[rowid]', $items['rowid']); ?&gt;
                    
                    <tr>
                      <td>&lt;?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?&gt;</td>
                      <td>
                        &lt;?php echo $items['name']; ?&gt;
                                    
                            &lt;?php if ($this->cart->has_options($items['rowid']) == TRUE): ?&gt;
                                    
                                <p>
                                    &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;
                                </p>
                                
                            &lt;?php endif; ?&gt;
                                
                      </td>
                      <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>
                    </tr>
                
                &lt;?php $i++; ?&gt;
                
                &lt;?php endforeach; ?&gt;
                
                <tr>
                  <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>
                </tr>
                
                </table>
                
                <p>&lt;?php echo form_submit('', 'Update your Cart'); ?&gt;</p>
                &lt;?php
        }
        
        function clear_cart()
        {
                $this->cart->destroy();
                redirect('shop');
        }
        
}

#3
[eluser]John_Betong[/eluser]
&nbsp;
Hi Joe,
&nbsp;

http://johns-jokes.com/ci_jokes/c_shop/

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

#4
[eluser]SitesByJoe[/eluser]
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.

#5
[eluser]daparky[/eluser]
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.

#6
[eluser]fourmi[/eluser]
Joe,

Thanks million Smile

Will showcase mine when I'm done Smile

Whoop Whoop!

Ant

#7
[eluser]fourmi[/eluser]
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!

cheers
ant

#8
[eluser]fourmi[/eluser]
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

cheers

#9
[eluser]garaki[/eluser]
How do I implement the checkout functionality in the above function?

#10
[eluser]fourmi[/eluser]
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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.