A shopping cart is a software package and Ecommerce application that acts as an online store’s catalog and ordering process.

When a user is browsing your site at that time Cart Class allows the items to be added to a session that stays active . These items can be retrieved and displayed in a standard “shopping cart” format

In this tutorial, we are going to explain how we can use “Cart class in CodeIgniter”. This cart class allows us to add and remove products to a shopping cart and to update them.

The Cart Class only provides the core “cart” functionality.  It does not provide shipping, credit card authorization, or other processing components.


To start with first you need to initialize the class by loading cart library.

Syntax

Load cart library in your controller’s constructor

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

This function allows you to add items to the shopping cart, insert() method will return the unique $rowid if you successfully insert a single item

$insert_data = array( 'id' => $this->input->post('id'),
 'name' => $this->input->post('name'),
 'price' => $this->input->post('price'),
'qty' => 1 );

 // This function add items into cart.
$this->cart->insert($insert_data);

This function allows you to update items to the shopping cart.

 $data = array( 'rowid' => $cart['rowid'];,
 'price' => $cart['price'];,
'amount' => $price * $cart['qty'];,
'qty' =>$cart['qty'];
);

// This function update item into cart.
$this->cart->update($data);

This function returns an array of the items added in the cart.

$this->cart->contents();

This function allows you to destroy the cart, which stores the session of the cart.

$this->cart->destroy();

Below is our complete code with download and live demo option 

Click on Add to Cart option to add the items in to the list from where you can update their quantity and can remove them too.

CodeIgniter Shopping Cart


Steps to run Downloaded file:

  1. Download the shopping cart project by given url and extract them.
  2. Copy it on to your local server base folder.
  3. Create database “shopping” in mysql.
  4. Go to database and import “shopping.sql”  file which you will find in downloaded project’s folder.
  5. After importing it run the program using below url.
http://localhost/codeigniter_cart/index.php/shopping

Note : Here we are displaying the products and their information in front end which is fetched from database table naming Products. If you wish to add more items to display then you have to manually update it from database. Whereas when user clicks on Place Order button then all the cart information get stored in database table naming customers, orders , order_detail.


Controller File: shopping.php

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

class Shopping extends CI_Controller {

public function __construct()
{
parent::__construct();
//Load Library and model.
$this->load->library('cart');
$this->load->model('billing_model');
}

public function index()
{
//Get all data from database
$data['products'] = $this->billing_model->get_all();
//send all product data to "shopping_view", which fetch from database.
$this->load->view('shopping_view', $data);
}

function add()
{
// Set array for send data.
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);

// This function add items into cart.
$this->cart->insert($insert_data);

// This will show insert data in cart.
redirect('shopping');
}

function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
// Destroy data which store in session.
$this->cart->destroy();
}else{
// Destroy selected rowid in session.
$data = array(
'rowid' => $rowid,
'qty' => 0
);
// Update cart data, after cancel.
$this->cart->update($data);
}

// This will show cancel data in cart.
redirect('shopping');
}

function update_cart(){

// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];

$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);

$this->cart->update($data);
}
redirect('shopping');
}

function billing_view(){
// Load "billing_view".
$this->load->view('billing_view');
}

public function save_order()
{
// This will store all values which inserted from user.
$customer = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'phone' => $this->input->post('phone')
);
// And store user information in database.
$cust_id = $this->billing_model->insert_customer($customer);

$order = array(
'date' => date('Y-m-d'),
'customerid' => $cust_id
);

$ord_id = $this->billing_model->insert_order($order);

if ($cart = $this->cart->contents()):
foreach ($cart as $item):
$order_detail = array(
'orderid' => $ord_id,
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price']
);

// Insert product imformation with order detail, store in cart also store in database.

$cust_id = $this->billing_model->insert_order_detail($order_detail);
endforeach;
endif;

// After storing all imformation in database load "billing_success".
$this->load->view('billing_success');
}
}
?>

View File : shopping_view.php

<html>
<head>
<title>Codeigniter cart class</title>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">

<script type="text/javascript">
// To conform clear all data in cart.
function clear_cart() {
var result = confirm('Are you sure want to clear all bookings?');

if (result) {
window.location = "<?php echo base_url(); ?>index.php/shopping/remove/all";
} else {
return false; // cancel button
}
}
</script>
</head>
<body>
<div id='content'>
<div id='tag'>
<!-- Formget Fugo logo image -->
<img src="<?php echo base_url(); ?>images/head_cart.jpg"/>
</div>
<div id="cart" >
<div id = "heading">
<h2 align="center">Products on Your Shopping Cart</h2>
</div>

<div id="text">
<?php $cart_check = $this->cart->contents();

// If cart is empty, this will show below message.
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add to Cart" Button';
} ?> </div>

<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<tr id= "main_heading">
<td>Serial</td>
<td>Name</td>
<td>Price</td>
<td>Qty</td>
<td>Amount</td>
<td>Cancel Product</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping/update_cart');
$grand_total = 0;
$i = 1;

foreach ($cart as $item):
// echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
// Will produce the following output.
// <input type="hidden" name="cart[1][id]" value="1" />

echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr>
<td>
<?php echo $i++; ?>
</td>
<td>
<?php echo $item['name']; ?>
</td>
<td>
$ <?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], 'maxlength="3" size="1" style="text-align: right"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
$ <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>

<?php
// cancle image.
$path = "<img src='http://localhost/codeigniter_cart/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td><b>Order Total: $<?php

//Grand Total.
echo number_format($grand_total, 2); ?></b></td>

<?php // "clear cart" button call javascript confirmation message ?>
<td colspan="5" align="right"><input  class ='fg-button teal' type="button" value="Clear Cart" onclick="clear_cart()">

<?php //submit button. ?>
<input class ='fg-button teal'  type="submit" value="Update Cart">
<?php echo form_close(); ?>

<!-- "Place order button" on click send "billing" controller -->
<input class ='fg-button teal' type="button" value="Place Order" onclick="window.location = 'shopping/billing_view'"></td>
</tr>
<?php endif; ?>
</table>
</div>
<div id="products_e" align="center">

<h2 id="head" align="center">Products</h2>
<?php

// "$products" send from "shopping" controller,its stores all product which available in database.
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$description = $product['description'];
$price = $product['price'];
?>

<div id='product_div'>
<div id='image_div'>
<img src="<?php echo base_url() . $product['picture'] ?>"/>
</div>
<div id='info_product'>
<div id='name'><?php echo $name; ?></div>
<div id='desc'> <?php echo $description; ?></div>
<div id='rs'><b>Price</b>:<big>
$<?php echo $price; ?></big></div>
<?php

// Create form and send values in 'shopping/add' function.
echo form_open('shopping/add');
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> </div>
<div id='add_button'>
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add to Cart',
'name' => 'action'
);

// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</div>
</div>

<?php } ?>

</div>
</div>
</body>
</html>

View File : billing_view.php

<?php
$grand_total = 0;
// Calculate grand total.
if ($cart = $this->cart->contents()):
foreach ($cart as $item):
$grand_total = $grand_total + $item['subtotal'];
endforeach;
endif;
?>
<html>
<head>
<title>Codeigniter cart class</title>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"/>
</head>
<body>
<div id="bill_info">

<?php // Create form for enter user imformation and send values 'shopping/save_order' function?>
<form name="billing" method="post" action="<?php echo base_url() . 'index.php/shopping/save_order' ?>" >
<input type="hidden" name="command" />
<div align="center">
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Order Total:</td><td><strong>$<?php echo number_format($grand_total, 2); ?></strong></td></tr>
<tr><td>Your Name:</td><td><input type="text" name="name" required=""/></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" required="" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" required="" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" required="" /></td></tr>
<tr><td><?php
// This button for redirect main page.
echo "<a class ='fg-button teal'  id='back' href=" . base_url() . "index.php/shopping>Back</a>"; ?>
</td><td><input class ='fg-button teal' type="submit" value="Place Order" /></td></tr>

</table>
</div>
</form>
</div>
</body>
</html>

View File : billing_success.php

<html>
<head>
<title>Codeigniter cart class</title>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
</head>
<body>
<div id='result_div'>
<?php
// this will show you thank you message.
echo "<h1 align='center'>Thank You! your order has been placed!</h1>";
echo "<span id='go_back'><a class='fg-button teal' href=" . base_url() . "index.php/shopping>Go back</a></span>";
?>
</div>
</body>
</html>

Model File : billing_model.php

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

class Billing_model extends CI_Model {

// Get all details ehich store in "products" table in database.
public function get_all()
{
$query = $this->db->get('products');
return $query->result_array();
}

// Insert customer details in "customer" table in database.
public function insert_customer($data)
{
$this->db->insert('customers', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}

// Insert order date with customer id in "orders" table in database.
public function insert_order($data)
{
$this->db->insert('orders', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}

// Insert ordered product detail in "order_detail" table in database.
public function insert_order_detail($data)
{
$this->db->insert('order_detail', $data);
}
}
?>

CSS File: style.css

body{
background-color:#E0E0E0;
margin:0 auto;
font-family: 'Raleway', sans-serif;
}
#content{

width:979px;
margin:0 auto;
}
#result_div {
background-color: #FFF;
width: 640px;
height: 175px;
margin: 0 auto;
margin-bottom: 10px;
margin-left: 445px;
margin-top: 300px;
}
h1{
padding:20px;
background-color:#333333;
width: 600px;
color:#FFF;
}
#products_e{
background-color: #FFFFFF;
width: 979px;
position: absolute;
margin-top: 10px;
}
#cart{
width:979px;
height:auto;
margin-top: -20px;
position:relative;
background-color:#FFFFFF;
}
h2{
font-family: 'Raleway', sans-serif;
padding:20px;
background-color:#333333;
color:#FFF;
}
#product_div{
width: 310px;
height:500px;
background: #fff;
position: relative;
float: left;
padding: 5px;
margin: 2px;
border: 1px solid #E0E0E0;
}
div#image_div {
width: 300px;
height: 250px;
}
div#info_product {
height: 165px;
}
tr {
background: white;
}
#bill_info{
background-color:#FFF;
width:640px;
margin:0 auto;
margin-bottom:10px;
}
h1{
padding:20px;
background-color:#333333;
color:#FFF;
}
div#text {
color: #08BBB7;
margin-left: 255px;
margin-top: -19px;
margin-bottom: 10;
font-family: 'Raleway', sans-serif;
}
#heading{
padding-bottom:10px
}
#table{
font-size:15px;
background-color:#E1E1E1;
width:100%;
}
tr{
bgcolor:#FFFFFF;
}
#main_heading{
font-weight:bold;
bgcolor:#FFFFFF;
}
div#name {
font-weight: 700;
font-size: 17px;
margin-bottom: 10px;
}
div#desc {
font-size: 15px;
margin-bottom: 11px;
min-height: 105px;
line-height: 1.4;
}
div#add_button {
margin-top: 23px;
}
span#go_back {
margin-left: 245px;
}

.fg-button{
position: relative;
top: 0;
border-radius: 4;
font-size: 18px;
padding: 8px 28px;
text-decoration: none;
border: 0px solid;
cursor: pointer;
border-bottom-width: 3px;
outline: none;
-webkit-transition: 0.3s background;
-moz-transition: 0.3s background;
transition: 0.3s background;
}
.fg-button:active{
top: 2px;
}
.fg-button.teal{
color: #fff;
border-color: #04A5A1;
background-color:#08BBB7;
}
.fg-button.teal:hover{
background: #0ACFCB;
}
.fg-button.teal:active{
background: #09cbc7;
top: 2px;
border-bottom-width: 1px;
}

Conclusion:

This was all about how we can implement  core shopping cart  using CodeIgniter cart class. Hope you like it, keep reading our other blogs