article

Wednesday, August 21, 2013

CodeIgniter Shopping Cart

CodeIgniter Shopping Cart

Create Database table

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `qty` int(11) NOT NULL,
  `price` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `products` (`id`, `qty`, `price`, `name`, `image`) VALUES
(1, 10, 500, 'Samsung Galaxy S 2', 'galaxys2.jpg'),
(2, 20, 600, 'Samsung Galaxy S 3', 'galaxys3.jpg');

Setup baseurl application\config\config.php
$config['base_url'] = "http://localhost/codeignater/";

Set route application\config\routes.php
$route['default_controller'] = "cart";

Create Controller
//application/controllers/cart.php
<?php
class Cart extends Controller { 

 function Cart()
 {
  parent::Controller(); // We define the the Controller class is the parent. 
  $this->load->model('cart_model'); // Load our cart model for our entire class
 }
 
 function index()
 {
  $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
  
  $data['content'] = 'cart/products'; // Select view to display
  $this->load->view('index', $data); // Display the page
 }
 
 function add_cart_item(){
  
  if($this->cart_model->validate_add_cart_item() == TRUE){
   
   // Check if user has javascript enabled
   if($this->input->post('ajax') != '1'){
    redirect('cart'); // If javascript is not enabled, reload the page with new data
   }else{
    echo 'true'; // If javascript is enabled, return true, so the cart gets updated
   }
  }
  
 }
 
 function update_cart(){
  $this->cart_model->validate_update_cart();
  redirect('cart');
 }
 
 function show_cart(){
  $this->load->view('cart/cart');
 }
 
 function empty_cart(){
  $this->cart->destroy();
  redirect('cart');
 }
}
Create Model
///application/models/cart_model.php
<?php 
class Cart_model extends Model {

 // Function to retrieve an array with all product information
 function retrieve_products(){
  $query = $this->db->get('products');
  return $query->result_array();
 }
 
 // Updated the shopping cart
 function validate_update_cart(){
  
  // Get the total number of items in cart
  $total = $this->cart->total_items();
  
  // Retrieve the posted information
  $item = $this->input->post('rowid');
     $qty = $this->input->post('qty');

  // Cycle true all items and update them
  for($i=0;$i < $total;$i++)
  {
   // Create an array with the products rowid's and quantities. 
   $data = array(
               'rowid' => $item[$i],
               'qty'   => $qty[$i]
            );
            
            // Update the cart with the new information
   $this->cart->update($data);
  }

 }
 
 // Add an item to the cart
 function validate_add_cart_item(){
  
  $id = $this->input->post('product_id'); // Assign posted product_id to $id
  $cty = $this->input->post('quantity'); // Assign posted quantity to $cty
  
  $this->db->where('id', $id); // Select where id matches the posted id
  $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
  
  // Check if a row has been found
  if($query->num_rows > 0){
  
   foreach ($query->result() as $row)
   {
       $data = array(
                 'id'      => $id,
                 'qty'     => $cty,
                 'price'   => $row->price,
                 'name'    => $row->name
             );

    $this->cart->insert($data); 
    
    return TRUE;
   }
  
  // Nothing found! Return FALSE! 
  }else{
   return FALSE;
  }
 }
}
Create view index
//application\views\index.php
<html>
<head>
<title>CodeIgniter Shopping Cart</title>
<link href="<?php echo base_url(); ?>assets/css/core.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/core.js"></script>
</head>
<body>
<div id="wrap">
 <?php $this->view($content); ?>
 <div class="cart_list">
  <h3>Your shopping cart</h3>
  <div id="cart_content">
   <?php echo $this->view('cart/cart.php'); ?>
  </div>
 </div>
</div>
</body>
</html>
Create view cart.php
//application\views\cart\cart.php
<?php if(!$this->cart->contents()):
 echo 'You don\'t have any items yet.';
else:
?>

<?php echo form_open('cart/update_cart'); ?>
<table width="100%" cellpadding="0" cellspacing="0">
 <thead>
  <tr>
   <td>Qty</td>
   <td>Item Description</td>
   <td>Item Price</td>
   <td>Sub-Total</td>
  </tr>
 </thead>
 <tbody>
  <?php $i = 1; ?>
  <?php foreach($this->cart->contents() as $items): ?>
  
  <?php echo form_hidden('rowid[]', $items['rowid']); ?>
  <tr <?php if($i&1){ echo 'class="alt"'; }?>>
     <td>
      <?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?>
     </td>
     
     <td><?php echo $items['name']; ?></td>
     
     <td>$<?php echo $this->cart->format_number($items['price']); ?></td>
     <td>$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
    </tr>
    
    <?php $i++; ?>
  <?php endforeach; ?>
  
  <tr>
   <td</td>
     <td></td>
     <td><strong>Total</strong></td>
     <td>$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
  </tr>
 </tbody>
</table>

<p><?php echo form_submit('', 'Update your Cart'); echo anchor('cart/empty_cart', 'Empty Cart', 'class="empty"');?></p>
<p><small>If the quantity is set to zero, the item will be removed from the cart.</small></p>
<?php 
echo form_close(); 
endif;
?>
Create View Product.php
//application\views\cart\products.php
<ul class="products">
 <?php foreach($products as $p): ?>
 <li>
  <h3><?php echo $p['name']; ?></h3>
  <img src="<?php echo base_url(); ?>assets/img/products/<?php echo $p['image']; ?>" alt="" />
  <small>$<?php echo $p['price']; ?></small>
  <?php echo form_open('cart/add_cart_item'); ?>
   <fieldset>
    <label>Quantity</label>
    <?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
    <?php echo form_hidden('product_id', $p['id']); ?>
    <?php echo form_submit('add', 'Add'); ?>
   </fieldset>
  <?php echo form_close(); ?>
 </li>
 <?php endforeach;?>
</ul>
Create CSS core.css in root directory assets\css\core.css
body{
 font-family: "Lucida Sans";
 font-size: 12px;
}

#wrap{
 width: 1024px;
}

ul.products{
 list-style-type: none;
 width: 525px;
 margin: 0;
 padding: 0;
}

 ul.products li{
  background: #eeeeee;
  border: 1px solid #d3d3d3;
  padding: 5px;
  width: 150px;
  text-align: center;
  float: left;
  margin-right: 10px;
 }

 ul.products h3{
  margin: 0;
  padding: 0px 0px 5px 0px;
  font-size: 14px;
 }
 
 ul.products small{
  display: block;
 }
 
 ul.products form fieldset{
  border: 0px;
 }
 
 ul.products form label{
  font-size: 12px;
 }
 
 ul.products form input[type=text]{
  width: 18px;
  background: #FFF;
  border: 1px solid #d3d3d3;
 }
div.cart_list{
 background: #eeeeee;
 border: 1px solid #d3d3d3;
 padding: 5px;
 float: left; 
 width: 490px;
}

 div.cart_list h3{
  margin: 0 0 10px 0;
  padding: 0;
  font-size: 14px;
 }
 
 div.cart_list table thead tr td{
  border-bottom: 1px solid #d3d3d3;
  padding: 5px;
 }
 
 div.cart_list table tbody tr td{
  padding: 5px;
 }
 
 div.cart_list table tbody tr td input[type=text]{
  background: #FFF;
  border: 1px solid #d3d3d3;
  width: 25px;
 }
 
 div.cart_list table tbody tr.alt{
  background: #f5f5f5;
 }
Create folder for image root directory assets\img\products\galaxys2.jpg, assets\img\products\galaxys3.jpg Create javascript file assets\js\core.js
$(document).ready(function() { 
 /*place jQuery actions here*/ 
 var link = "/codeignater/index.php/";
 
 
 $("ul.products form").submit(function() {
  // Get the product ID and the quantity 
  var id = $(this).find('input[name=product_id]').val();
  var qty = $(this).find('input[name=quantity]').val();
  
   $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
     function(data){
     
     if(data == 'true'){
       
       $.get(link + "cart/show_cart", function(cart){
       $("#cart_content").html(cart);
    });

      }else{
       alert("Product does not exist");
      } 
      
    }); 

  return false;
 });
 
 $(".empty").live("click", function(){
     $.get(link + "cart/empty_cart", function(){
      $.get(link + "cart/show_cart", function(cart){
      $("#cart_content").html(cart);
   });
  });
  
  return false;
    });

});

Related Post