Codeigniter shopping cart tutorial

Codeigniter shopping cart tutorial | codeigniter shopping cart ajax | codeigniter cart class

1 year ago

Codeigniter shopping cart tutorial with Codeigniter cart class and Codeigniter shopping cart ajax

Trymycode offers the best Codeigniter shopping cart tutorial for you using Codeigniter cart class. This Codeigniter shopping cart ajax is used to pass product data from view to controller. The shopping cart is a simple E-commerce platform used to sell the products all over the world. The user interface and page loading are very much essential in case of a shopping cart. We need to satisfy each user genuinely so that they will return to our shop frequently. Shopping cart creation using Codeigniter framework is surprisingly simple. The Codeigniter framework has a shopping cart class which help us to perform this process. At the same time, your platform is very much secure and dynamic if you go for this framework. Codeigniter shopping cart tutorial enables you to become more accustomed to the latest Codeigniter features too.

 

Codeigniter cart class

 

The Codeigniter has an inbuilt library class named cart class. This cart class helps us to add items to a session while the user is browsing our platform. The cart class only provides the core functionality of a shopping cart. You can’t expect much more from this class. For example, shipping, payment and much more. The cart class uses the Session Class to save the cart data into the database. The cart class also help us to retrieve this data from the database. The Session class initialization is possible using cart class. You don’t need to initialize Session class once again to add an item. The cart class initialization is possible using the code given below.

$this->load->library('cart');

Meanwhile, product insertion is possible by passing an array of product information. Sample array of product information is this.

$data = array(
'id'      => 'product_id',
'qty'     => 1,
'price'   => 150,
'name'    => 'Shirt',
'options' => array('Size' => 'X', 'Color' => 'Green')
);
$this->cart->insert($data);

We are using ajax to pass product data from view to controller. From the controller, we add data to this array as well as to the class.

 

Codeigniter shopping cart ajax

Codeigniter shopping cart ajax

In this Codeigniter shopping cart tutorial, we are going to learn shopping cart creation using this cart class. Now you have an idea about the Codeigniter cart class. Although, you may be familiar with Codeigniter framework. You have the option to get the introduction about Codeigniter and features of Codeigniter from Trymycodes. Codeigniter is an open source PHP framework. Codeigniter 3 source file is available from codeigniter.com. Please download the source file for this process. Copy the file to your server ( HTDOCS in case of localhost or PUBLICHTML). After copying, edit the .htaccess for removing index.php on base URL. The .htaccess code is right below.

<Ifmodule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$1 [PT,L]
</Ifmodule>

Please open phpmyadmin and create a database named “shoppingcart”. Configure the database so that we can save take our product data from the database. The SQL query to create product table is below.

CREATE TABLE `tblproduct` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_code` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=1

The SQL query to create shopping session table is below.

CREATE TABLE `shop_session` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned NOT NULL DEFAULT '0',
`data` blob NOT NULL,
PRIMARY KEY (`id`),
KEY `ci_sessions_timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Please change the session configuration on config.php file to save the session data on the database. Substitute the session configuration code(line 380 to 386) with this.

$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'shop_session';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

Please edit the routes.php file to set the default controller. Change the line 52 on routes.php file with this code below.

$route['default_controller'] = 'home';

 

Codeigniter shopping cart tutorial shows you to create a controller(Controller)

Like other MVC frameworks, we are performing our core operations from the controller. At the same time, we use two controllers for this shopping cart. The functions like add to cart, reduce cart and remove cart product is on the home controller. The cart controller is used to load cart details page. The code to create home controller is right below.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
ob_start();
class Home extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('array');
$this->load->helper('url');
$this->load->model("Cart");
$this->load->library('cart');
$this->load->library('session');
}
public function index(){
$cart_data=$this->Cart->get_cart();
$added_data= $this->cart->contents();
$this->load->view('home',array('cart_data'=>$cart_data,'added_data'=>$added_data));
}
public function addtocart(){
$id = $_POST['id'];
$cart_data=$this->Cart->get_cart($id);
$cart_data = json_decode( json_encode($cart_data), true);
$data = array(
'id' => $id,
'qty' => 1,
'price' => $cart_data[0]["price"],
'name' => $cart_data[0]["name"],
'title' => $cart_data[0]["name"],
'image' => $cart_data[0]["image"],
'code' => $cart_data[0]["code"],
'description'=> $cart_data[0]["description"],
);
$cart_row = $this->cart->insert($data);
$cart = array_values($this->cart->contents($cart_row));
$data = array(
'status' => 'Success',
'count'=>$this->cart->total_items(),
);
echo json_encode($data);
}
public function reducecart(){
$row_id= $_POST['row'];
$qty = ($_POST['qty'] - 1);
$array=array('rowid' =>$row_id ,'qty'=>$qty );
$this->cart->update($array);
$data = array(
'status' => 'Success',
);
echo json_encode($data);
}
public function remove_cart_product(){
$row_id= $_POST['row'];
$qty=0;
$array=array('rowid' =>$row_id ,'qty'=>$qty );
$this->cart->update($array);
$data = array(
'status' => 'Success',
);
echo json_encode($data);
}
public function clear(){
$this->cart->destroy();
}
}
?>

The code to create view is below.(View)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$base_url = base_url();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Codeigniter Shopping cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link id="callCss" rel="stylesheet" href="<?= $base_url ?>themes/bootshop/bootstrap.min.css" media="screen"/>
<link href="<?= $base_url?>themes/css/base.css" rel="stylesheet" media="screen"/>
<!-- Bootstrap style responsive -->
<link href="<?= $base_url?>themes/css/bootstrap-responsive.min.css" rel="stylesheet"/>
<link href="<?= $base_url?>themes/css/font-awesome.css" rel="stylesheet" type="text/css">
<!-- Google-code-prettify -->
<link href="<?= $base_url?>themes/js/google-code-prettify/prettify.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<style type="text/css" id="enject"></style>
</head>
<body>
<div id="header">
<div class="container">
<div id="welcomeLine" class="row">
<div class="span6">
</div>
</div>
<!-- Navbar ================================================== -->
<div id="logoArea" class="navbar">
<div class="navbar-inner">
<a class="brand" href="index.html"></a>
<a href="<?php echo base_url('home');?>"><span class="btn btn-small btn-success">Home</span></a>
<div class="pull-right">
<a href="<?php echo base_url('cart');?>"><span class="btn btn-mini btn-primary"><i class="icon-shopping-cart icon-white"></i> <span class="count"><?= $this->cart->total_items() ?></span> Itemes in your cart </span> </a>
</div>
</div>
</div>
</div>
</div>
<div id="mainBody">
<div class="container">
<div class="row">
<div class="span12">
<h4>Latest Products </h4>
<ul class="thumbnails">
<?php
if(!empty($cart_data)){
foreach($cart_data as $row){
?>
<li class="span3">
<div class="thumbnail">
<a href="product_details.html"><img src="<?= $row->image ?>" alt=""/></a>
<div class="caption">
<h5><?= $row->name ?></h5>
<p>
<?= $row->description ?>
</p>
<h4 style="text-align:center">
<a class="btn" href="javascript:void(0)" onclick="addtocart(<?= $row->id ?>)">Add to <i class="icon-shopping-cart"></i></a> <a class="btn btn-primary" href="#">Rs- <?= $row->price ?></a></h4>
</div>
</div>
</li>
<?php
}
} ?>
</ul>
</div>
</div>
</div>
</div>
<script>
function addtocart(id){
if(id != ""){
$.ajax({
url:'<?php echo base_url(); ?>home/addtocart',
type:'POST',
dataType:'json',
data:{
'id' : id
},
success: function(data) {
$('.count').html(data.count);
//location.reload();
}
});
} else {
return false;
}
return false;
}
</script>
</body>
</html>

We can see the ajax script at the bottom of view page. We use the ajax to pass data from view to controller. The product ID in JSON format passes through the ajax to add to cart function. Inside the add to cart function, the product ID is collected additionally. The product details having this product ID is fetched from the database using cart model. Meanwhile, a get_cart function from the model is used to get data from the database. Moreover, we have options to load the model from the construct of home controller. The code showing the model is below.

<?PHP
class Cart extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->helper('array');
$this->load->helper('url');
$this->load->database('default');
}
function get_cart($id = ""){
$data = array();
if(!empty($id)){
$this->db->where('id',$id);
}
$query = $this->db->get('tblproduct');
$res = $query->result();
return $res;
}
}
?>

We use the cart controller only to load the cart view since we use a home controller to perform remaining functions. The code for the cart controller used in this Codeigniter shopping cart tutorial is given below.

Codeigniter cart class


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cart extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('array');
$this->load->helper('url');
}
public function index()
{
$cart_data=$this->cart->contents();
$this->load->view('cart',array('cart_data' => $cart_data));
}
}
?>

The code to create cart page is below.(View)

Actually cart page helps to manage the products that we added from the home page. Here we have options to remove, increment or decrement the quantity of a product. I have provided this facility in a separate view so that you can understand coding simpler. Presently you can see more ajax function than the home page. Due to multiple actions like product removal, increment or decrement quantity we use these functions. This cart page is so important that we do the main functionality’s from this cart page. Please find the code to create cart view from right below.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$base_url = base_url();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Codeigniter Shopping cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link id="callCss" rel="stylesheet" href="<?= $base_url?>themes/bootshop/bootstrap.min.css" media="screen"/>
<link href="<?= $base_url?>themes/css/base.css" rel="stylesheet" media="screen"/>
<!-- Bootstrap style responsive -->
<link href="<?= $base_url?>themes/css/bootstrap-responsive.min.css" rel="stylesheet"/>
<link href="<?= $base_url?>themes/css/font-awesome.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<style type="<?= $base_url?>text/css" id="enject"></style>
</head>
<body>
<div id="header">
<div class="container">
<div id="welcomeLine" class="row">
<div class="span6">
</div>
</div>
<!-- Navbar ================================================== -->
<div id="logoArea" class="navbar">
<div class="navbar-inner">
<a class="brand" href="index.html"></a>
<a href="<?php echo base_url('home');?>"><span class="btn btn-small btn-success">Home</span></a>
<div class="pull-right">
<a href="<?php echo base_url('cart');?>"><span class="btn btn-mini btn-primary"><i class="icon-shopping-cart icon-white"></i> <span class="count"><?= $this->cart->total_items() ?></span> Itemes in your cart </span> </a>
</div>
</div>
</div>
</div>
</div>
<!-- Header End====================================================================== -->
<div id="mainBody">
<div class="container">
<div class="row">
<div class="span12">
<ul class="breadcrumb">
<li><a href="<?php echo base_url('home');?>">Home</a> <span class="divider">/</span></li>
<li class="active"> SHOPPING CART</li>
</ul>
<h3> SHOPPING CART [ <small><span class="count"><?= $this->cart->total_items() ?></span> Item(s) </small>]<a href="<?php echo base_url('home');?>" class="btn btn-large pull-right"><i class="icon-arrow-left"></i> Continue Shopping </a></h3>
<hr class="soft"/>
<table class="table table-bordered " id="mytable">
<thead>
<tr>
<th>Product</th>
<th colspan="2">Description</th>
<th>Quantity/Update</th>
<th colspan="2">Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php
$grand_total = 0;
if(!empty($cart_data)){
foreach ($cart_data as $data) {
$total = ($data['price']*$data['qty']);
$grand_total += $total;
?>
<tr>
<td> <img width="60" src="<?= $data['image'] ?>" alt=""/></td>
<td colspan="2"><?= $data['name'] ?><br/>Description : <?= $data['description'] ?></td>
<td>
<div class="input-append">
<input class="span1" style="max-width:20px" readonly="true" placeholder="1" id="appendedInputButtons<?= $data['id'] ?>" size="16" type="text" value="<?= $data['qty'] ?>">
<a class="btn" href="javascript:void(0)" onclick="reducecart('<?= $data['rowid']?>',<?= $data['qty'] ?>)"><i class="icon-minus"></i></a>
<a class="btn" href="javascript:void(0)" onclick="addtocart(<?= $data['id'] ?>)"><i class="icon-plus"></i></a>
<a href="javascript:void(0)" class="btn btn-danger"
onclick="remove_cart_product('<?= $data['rowid'] ?>')"><i class="icon-remove icon-white"></i></a> </div>
</td>
<td colspan="2">$<?= $data['price'] ?></td>
<td>$<?= $total ?></td>
</tr>
<?php }
} ?>
<tr>
<td colspan="6" style="text-align:right"><strong>TOTAL =</strong></td>
<td class="label label-important" style="display:block"> <strong> $<?= $grand_total ?> </strong></td>
</tr>
</tbody>
</table>
<script>
function addtocart(id){
if(id != ""){
$.ajax({
url:'<?php echo base_url(); ?>home/addtocart',
type:'POST',
dataType:'json',
data:{
'id' : id
},
success: function(data) {
location.reload();
}
});
} else {
return false;
}
return false;
}
function reducecart(row,qty){
if(qty != ""){
$.ajax({
url:'<?php echo base_url(); ?>home/reducecart',
type:'POST',
dataType:'json',
data:{
'row' : row,
'qty' : qty,
},
success: function(data) {
location.reload();
}
});
} else {
return false;
}
return false;
}
function remove_cart_product(row){
if(row != ""){
$.ajax({
url:'<?php echo base_url(); ?>home/remove_cart_product',
type:'POST',
dataType:'json',
data:{
'row' : row
},
success: function(data) {
location.reload();
}
});
} else {
return false;
}
return false;
}
</script>
</div>
</div></div>
</div>
</body>
</html>

How does this work?. Find this from Codeigniter shopping cart tutorial.

 

Add to cart

We activate ajax function while clicking the add to cart button. The ajax function pass the variable through the URL to the function inside the Home controller. The posted ID from view goes to the model to collect product data from the database. The product data from the database converted to cart array format and inserted into cart session. Then we encode the status success in JSON format and passes to the view.

Reduce item quantity

We activate the reduce cart ajax function while clicking the decrement button. We pass the row id of that item in the cart session and product ID to the ajax function. In the same way, as for add to cart, we collect the data at the controller. At the same time, the row ID is used to update the cart array. We decremented the item quantity using the same row ID. Like insertion process, we have the option to perform updating easily in this cart class. Across various process, in the shopping cart, we use this functionality.

Remove item

The remove cart product ajax function will activate while clicking the remove button. We pass the row ID of the product to the remove cart product function inside the home controller through ajax. We set cart item quantity of related row id to zero and updated. The product automatically removed from the cart with zero.

Empty Cart

The cart class gives an option to empty our cart. We destroy the cart array that created earlier by inserting various products. I have given the empty cart function inside the home controller. Here we don’t need to pass any product row ID. This functionality increases the developer-friendly functionality of Codeigniter.

 

Download and implement Codeigniter shopping cart tutorial source code

To implement Codeigniter shopping cart please download the source code by clicking the download button below. I have added a sample shopping cart code to Codeigniter source file. I’ve downloaded Codeigniter source file from codeigniter.com. Please follow the steps below to perform this.

  • Please make sure your server is active
  • Download the source file by clicking the button below
  • Place it inside your HTDOCS folder and unzip the file
  • Configure the database and import the SQL file given with source to PHPMyAdmin
  • Don’t need to reconfigure config file if you are downloading the source file
  • After that go for http://localhost/Codeigniter-shopping-cart-tutorial/ and enjoy your shopping cart

Download

Finally, hope you are happy with this Codeigniter shopping cart tutorial using cart class.

Moreover, know more & more about the latest Codeigniter features through the latest Codeigniter shopping cart tutorial which is available at future updates.

Adharsh

Leave a Reply

Your email address will not be published. Required fields are marked *