2.CodeIgniter Shopping Cart


Introduction:
A shopping cart is expected in every e-commerce website so LET’S DO THIS.

Easy Steps:
1.     On mysql, create a table for products.
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(50) DEFAULT NULL,
  `qty` int(11) DEFAULT NULL,
  `price` decimal(10,0) DEFAULT NULL,
  `status` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Note: Insert data on your products table.
2.     On the views folder create a file named products_view.php with the codes below:
<html>
<head>
<title>Products | BizjobFinder</title>
</head>
<body>
<h2>Products</h2>
<div>
    <table border = "1">
                <tr>
                <th>ID</th>
                <th>Description</th>
                <th>Price</th>
                <th>Qty</th>
                <th>Action</th>
                </tr>
        <?php foreach($products as $product){ ?>
                        <form method='post' action="<?php echo base_url()?>product-add-to-cart">
                        <tr>
                        <td>
                        <?php echo $product['id'] ?>
                        <input type = "hidden" name = "id" value = "<?php echo $product['id'] ?>"/>
                        </td>
                        <td>
                        <?php echo $product['description'] ?>
                        <input type = "hidden" name = "description" value = "<?php echo $product['description'] ?>"/>
                        </td>
                        <td>
                        <?php echo $product['price'] ?>
                        <input type = "hidden" name = "price" value = "<?php echo $product['price'] ?>"/>
                        </td>
                        <td>
                        <input type = "text"  name ="qty" style ="width:50px;" value = "1"/>
                        </td>
                        <td><input type = "submit" value ="Add to cart" /></td>
                        </tr>
                        </form>
        <? } ?>
        </table>
        <br/>
        <div><a href = "<?php base_url()?>shopping-cart-view" >My Shopping Cart</a></div>
</div>
</body>
</html>
3.     On mysql, create a table for order_details.
CREATE TABLE IF NOT EXISTS `order_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) DEFAULT NULL,
  `description` varchar(50) DEFAULT NULL,
  `price` decimal(10,0) DEFAULT NULL,
  `qty_ordered` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
4.     On the config folder open autoload.php and add the cart object.
$autoload['libraries'] = array('database','session','cart');
5.     On the config folder open routes.php and add these routes.
$route['products'] = "products";
$route['product-add-to-cart'] = "products/addToCart";
$route['shopping-cart-view'] = "products/shoppingCartView";
$route['save-shopping-cart'] = "products/saveCartProducts";
6.     On the views folder create a file named shopping_cart_view.php with the codes below:
<html>
<head>
<title>Shopping Cart |BizjobFinder</title>
</head>
<body>
<h2>My Shopping Cart</h2>
<div>                             
                        <?php if(isset($this->session->userdata['user'])){?>
                        <div>
                        <?php echo $this->session->userdata['user']['msg'];
                                        $this->session->unset_userdata('user');
                        ?>
                        </div>
                        <?php } ?>
                        <form method='post' action="<?php echo base_url()?>save-shopping-cart">
                        <table border = "1">
                        <tr>
                                        <th>ID</th>
                                        <th>Description</th>
                                        <th>Price</th>
                                        <th>Qty</th>
                        </tr>
                        <?php
                                        foreach($products as $product){ ?>               
                                        <tr>
                                        <td>
                                        <?php echo $product['id'] ?>
                                        <input type = "hidden" name = "id[]" value = "<?php echo $product['id'] ?>"/>
                                        </td>
                                        <td>
                                        <?php echo $product['name'] ?>
                                        <input type = "hidden" name = "name[]" value = "<?php echo $product['name'] ?>"/>
                                        </td>
                                        <td>
                                        <?php echo $product['price'] ?>
                                        <input type = "hidden" name = "price[]" value = "<?php echo $product['price'] ?>"/>
                                        </td>
                                        <td>
                                        <?php echo $product['qty'] ?>
                        <input type = "hidden"  name ="qty[]" style ="width:50px;" value = "<?php echo $product['qty']?>"/>
                                        </td>
                                        </tr>
                                        <? } ?>  
                                        </table>
                                        <input type = "submit" value = "Save Cart"/>
                        </form>
                        <div>
                                        <a href = "<?php base_url()?>products">Go back Products</a>
                        </div>
</div>
</body>
</html>
7.     On the controllers folder create a file named products.php with the codes below:
<?php
if( !defined('BASEPATH') ) exit ('No direct script access allowed');
class products extends CI_Controller{

        function __construct(){
                                                        parent::__construct();
                                                        $this->load->model('product_model','product');
        }

        function index(){
                        $data['products'] = $this->product->get_products();
                        $this->load->view('products_view',$data);
        }
        function addToCart(){
                        $data = array(
               'id'      => $this->input->post('id'),
               'qty'     => $this->input->post('qty'),
               'price'   => $this->input->post('price'),
               'name'    => $this->input->post('description')
            );
                        $this->cart->insert($data);
                        redirect(base_url().'shopping-cart-view');
        }
        function shoppingCartView(){
                        $data['products'] = $this->cart->contents();
                        $this->load->view('shopping_cart_view',$data);
        }
       
        function saveCartProducts(){
                        $ids = Array();
                        $descriptions = Array();
                        $prices = Array();
                        $qtys = Array();
                        $ids = $this->input->post('id');
                        $descriptions = $this->input->post('name');
                        $prices = $this->input->post('price');
                        $qtys = $this->input->post('qty');
                        $result = $this->product->save_cart_products($ids,$descriptions,$prices,$qtys);
                       
                        if($result){
                                        $msg="Successfully Save...";
                                        $this->cart->destroy();
                                        }
                        else{
                                        $msg="Save Failed..."
                                        }                 
                                                       
                        $data=array('msg' => $msg);
                        $this->session->set_userdata('user',$data);    
                        redirect(base_url().'shopping-cart-view');
        }   
}
8.     On the models folder create a file named product_model.php with the codes below:
<?php
class product_model extends CI_Model{
    
      private $table;
    
      function __construct(){
                  parent::__construct();
                  $this->table='products';
      }  
          function get_products(){
                                        $result = $this->db->get($this->table);
                                        return $result->result_array();
          }
          function save_cart_products($ids,$descriptions,$prices,$qtys){
                                        $this->db->trans_begin();
                                        $ndx=0;
                                        foreach($ids as $id){
                                                        //save product to order_details table.
                                                        $data = array('product_id' => $id,
                                                                                                          'description' => $descriptions[$ndx],
                                                                                                          'price' =>$prices[$ndx],
                                                                                                          'qty_ordered' =>$qtys[$ndx]);
                                                        $this->db->insert("order_details",$data);
                                                       
                                                        //update product qty on the products table.
                                                        $this->db->where('id',$id);
                                                        $this->db->set('qty', "qty-$qtys[$ndx]", FALSE);
                                                        $this->db->update($this->table);
                                                        $ndx++;
                                        }
                                        if ($this->db->trans_status() === FALSE){
                                                        $this->db->trans_rollback();
                                                        return FALSE;
                                                        }
                                        else{
                                                        $this->db->trans_commit();
                                                        return TRUE;
                                        }
          }
}
9.     You made it, nice job.:)

1 comment: