Custom Cart in CodeIgniter Reviewed by Momizat on . Custom cart is usefull for CodeIgniter framework. Use in Controller controller/core_cart.php [php] <?php if ( ! defined('BASEPATH')) exit('No direct script a Custom cart is usefull for CodeIgniter framework. Use in Controller controller/core_cart.php [php] <?php if ( ! defined('BASEPATH')) exit('No direct script a Rating: 0

Custom Cart in CodeIgniter

Custom cart is usefull for CodeIgniter framework.

Use in Controller

controller/core_cart.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Core_cart extends CI_Controller {


	public function __construct()
	{
		parent:: __construct();
		$this->load->model('Product_core_model');
		
	}

	public function index(){
	if(isset($_POST['command']) && $_POST['command']=="add" && $_POST['productid']>0){
		$pid=$_POST['productid'];	
		$this->addtocart($pid,1);
		redirect($_SERVER['HTTP_REFERER'], 'refresh');
	}
	$data['results']=$this->Product_core_model->view_allproducts();	
	$this->load->view('product_view',$data);
	
	}
	public function shoppingcart(){
	if(isset($_POST['command']) && $_POST['command']=="delete" && $_POST['pid']>0){
		$pid=$_POST['pid'];	
		$this->remove_product($pid);
		redirect($_SERVER['HTTP_REFERER'], 'refresh');
	}
	else if(isset($_POST['command']) && $_POST['command']=="clear"){
		$this->session->unset_userdata('cart');
		redirect($_SERVER['HTTP_REFERER'], 'refresh');
	}
	else if(isset($_POST['command']) && $_POST['command']=="update"){
		$res=array();$res1=array();
		$cart = $this->session->userdata('cart');
		$max=count($cart);
		
		$this->session->set_userdata('cart','');		
		for($i=0;$i<$max;$i++){
			$pid=$cart[$i]['productid'];
			$q=intval($_POST['product'.$pid]);				
				$res1[$i]['productid']=$pid;
				$res1[$i]['qty']=$q;				
				$this->session->set_userdata('cart',$res1);
		}
		
		redirect($_SERVER['HTTP_REFERER'], 'refresh');
	}
	$data['gg']='';	
	$this->load->view('shopping_cart',$data);
	
	}
	
	public function addtocart($pid,$q){
	$res=array();$res1=array();
		if($this->product_exists($pid) == 0){
		$cart = $this->session->userdata('cart');	
		
			if(is_array($cart)){
			$res = $this->session->userdata('cart');		
				echo $max=count($cart);
				$res1[$max]['productid']=$pid;
				$res1[$max]['qty']=$q;
				$res=array_merge($res, $res1);				
				$this->session->set_userdata('cart',$res);
			}else{				
				$res1[0]['productid']=$pid;
				$res1[0]['qty']=$q;
				$res=array_merge($res, $res1);				
				$this->session->set_userdata('cart',$res);
			}
		}
	}

	public function product_exists($pid){
		$pid=intval($pid);
		$cart = $this->session->userdata('cart');		
		$max=count($cart );
		$flag=0;
		for($i=0;$i<$max;$i++){
		echo $cart[$i]['productid'];
			if($pid==$cart[$i]['productid']){
			$flag=1;
			break;
			}
		}
		return $flag;
	}
	public function remove_product($pid){
	$cart = $this->session->userdata('cart');	
		$pid=intval($pid);
		$max=count($cart);
		for($i=0;$i<$max;$i++){
			if($pid==$cart[$i]['productid']){
				unset($cart[$i]);
			break;
			}
		}		
		$this->session->set_userdata('cart',array_values($cart));
	}

}

/* End of file ajax_controller.php */
/* Location: ./application/controllers/ajax_controller.php */
 
?>

Use in model

model/product_core_model.php
<?php

 if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product_core_model extends CI_Model {
private $_ci;
public function __construct()
{
	parent:: __construct();
	$this->_ci =& get_instance();
	$this->_ci->load->library('session');
}
function insertdata($tbl,$data)
{
	$this->db->insert($tbl,$data);
	return $this->db->insert_id();
}
function deletedata($tbl,$fid,$fval)
{
	$this->db->delete($tbl, array($fid => $fval)); 
}
public function view_allproducts(){
	
	$query=$this->db->get('products');
	return $query->result_array();

}
public function get_product_name($pid){
	$query = $this->db->query('SELECT name FROM products where serial='.$pid);	
	$row= $query->row_array();
	return $row['name'];
}
public function get_order_total(){
$cart = $this->_ci->session->userdata('cart');
	$max=count($cart);
	$sum=0;
	for($i=0;$i<$max;$i++){
		$pid=$cart[$i]['productid'];
		$q=$cart[$i]['qty'];
		$price=$this->get_price($pid);
		$sum+=$price*$q;
	}
	return $sum;
}
public function get_price($pid){
	$query = $this->db->query('SELECT price FROM products where serial='.$pid);	
	$row= $query->row_array();
	return $row['price'];
}


}/* model end*/

/* End of file product_model.php */
/* Location: ./application/models/product_model.php */

?>

Use in view

view/product_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Products</title>
<script language="javascript">
	function addtocart(pid){
		document.form1.productid.value=pid;
		document.form1.command.value='add';
		document.form1.submit();
	}
</script>
</head>
<body>

<?php
$cart = $this->session->userdata('cart');
	if(isset($cart) && is_array($cart) && $max = count($cart) <> '0'){
	?>
	<div style="float:right; margin:5px; padding:5px; border:1px solid #CCC; font-family:Arial; font-size:12px; text-align:center;">
    <p>
	<?php echo $max = count($cart); ?> Item(s)
    </p>
    <a href="http://localhost/test/index.php/core_cart/shoppingcart">
    Check Out
    </a>
</div>
<?php } ?>

<form name="form1" method="post">
	<input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>
<div align="center">
	<h1 align="center">Products</h1>
	<table border="0" cellpadding="2px" width="600px">
		<?php
			
			foreach($results as $row){
		?>
    	<tr>
        	<td><img src="<?php echo $row['picture']?>" /></td>
            <td>   	<b><?php echo $row['name']?></b><br />
            		<?php echo $row['description']?><br />
                    Price:<big style="color:green">
                    	$<?php echo $row['price']?></big><br /><br />
                    <input type="button" value="Add to Cart" onclick="addtocart(<?php echo $row['serial']?>)" />
			</td>
		</tr>
        <tr><td colspan="2"><hr size="1" /></td>
        <?php } ?>
    </table>
</div>
</body>
</html>

view/shopping_cart.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<script language="javascript">
	function del(pid){
		if(confirm('Do you really mean to delete this item')){
			document.form1.pid.value=pid;
			document.form1.command.value='delete';
			document.form1.submit();
		}
	}
	function clear_cart(){
		if(confirm('This will empty your shopping cart, continue?')){
			document.form1.command.value='clear';
			document.form1.submit();
		}
	}
	function update_cart(){
		document.form1.command.value='update';
		document.form1.submit();
	}
</script>
</head>

<body>
<form name="form1" method="post">
<input type="hidden" name="pid" />
<input type="hidden" name="command" />
	<div style="margin:0px auto; width:600px;" >
    <div style="padding-bottom:10px">
    	<h1 align="center">
        Your Shopping Cart
      </h1>
    </div>
   	<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%" align="center">
   	<?php
	$cart = $this->session->userdata('cart');
		if(isset($cart) && is_array($cart)){
    ?>
	<tr bgcolor="#FFFFFF" style="font-weight:bold"><td width="8%" align="left" bgcolor="#DFDFDF">Sr.No</td><td width="51%" align="left" bgcolor="#DFDFDF">Item(s) Description</td>
	  <td width="9%" align="center" bgcolor="#DFDFDF">Qty.</td><td width="9%" align="left" bgcolor="#DFDFDF">Price</td><td width="11%" align="left" bgcolor="#DFDFDF">Amount</td><td width="12%" align="center" bgcolor="#DFDFDF">Options</td></tr>
	<?php
		$max=count($cart);
		for($i=0;$i<$max;$i++){
			$pid=$cart[$i]['productid'];
			$q=$cart[$i]['qty'];
			$pname=$this->Product_core_model->get_product_name($pid);
			$price=$this->Product_core_model->get_price($pid);
			$totalprice=$this->Product_core_model->get_order_total();
			if($q==0)continue;
	?>
		<tr bgcolor="#FFFFFF"><td align="left"><?php echo $i+1?></td><td align="left"><?php echo $pname;?></td>
		<td align="center"><input type="text" name="product<?php echo $pid?>" value="<?php echo $q;?>" maxlength="3" size="2" style="text-align:center;" /></td>
		<td align="left"><?php echo $price; ?></td>                    
        <td align="left"><?php echo $price*$q;?></td>
		<td align="center"><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr>
	<?php					
	}
	?>
	<tr>
    	<td colspan="2" align="left" bgcolor="#EBEBEB"><b>Total Order Price: $<?php echo $totalprice;?></b>  	  </td>
    	<td colspan="4" align="right" bgcolor="#EBEBEB">
    	  <input type="button" value="Clear" onclick="clear_cart()">
    	  <input type="button" value="Update" onclick="update_cart()">
          <?php
		  if($max = count($cart)>0){
			?>
    	  <input type="button" value="Next" onclick="window.location='billing.php'">
          <?php
		  }else{
		  ?>
    	  <input type="button" value="Next" disabled="disabled">
		<?php
		  }
		  ?>
  	  </td>
      </tr>
	<?php
	}else{
		echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
	}
	?>
	</table>
    <p align="center"><input type="button" value="Continue Shopping" onclick="window.location='http://localhost/test/index.php/core_cart/'" /></p>
	</div>
</form>
</body>
</html>

Use table

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `serial` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) COLLATE latin1_general_ci NOT NULL,
  `description` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `price` float NOT NULL,
  `picture` varchar(80) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`serial`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=7 ;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`) VALUES
(1, 'product1', 'test1', 250, 'images/lcd.jpg'),
(2, 'product2', 'test2', 80, 'images/cdrom-drive.jpg'),
(3, 'product3', 'test3', 50, 'images/charger.jpg'),
(5, 'product4', 'test4', 5, 'images/mouse.jpg'),
(6, 'product5', 'test5', 299, 'images/mobile.jpg');

Leave a Comment

© 2014 Powered By