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.
Steps to run Downloaded file:
- Download the shopping cart project by given url and extract them.
- Copy it on to your local server base folder.
- Create database “shopping” in mysql.
- Go to database and import “shopping.sql”  file which you will find in downloaded project’s folder.
- 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
21 Replies to “CodeIgniter Shopping Cart Sample”
Cool you should include disquis.com so people can disqus it 😀
satisfy with shopping cart example it’s very usefull to me learning applyinh in shopping website
what if i cant name my database shopping, what do i do, ive renamed it all to the new name but nothing
navigate to codeigniter_cart/application/config/database.php, change the database name ‘shopping’ as u wish, from line 54(most probably).. 🙂
Thank you so much … 🙂
Good tutorial,pls also attach payments option like paypal
— phpMyAdmin SQL Dump
— version 4.0.4
— http://www.phpmyadmin.net
—
— Host: localhost
— Generation Time: Dec 17, 2014 at 06:57 AM
— Server version: 5.6.12-log
— PHP Version: 5.4.16
SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
SET time_zone = “+00:00”;
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
—
— Database: `shopping`
—
CREATE DATABASE IF NOT EXISTS `shopping` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `shopping`;
— ——————————————————–
—
— Table structure for table `customers`
—
CREATE TABLE IF NOT EXISTS `customers` (
`serial` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) COLLATE latin1_general_ci NOT NULL,
`email` varchar(80) COLLATE latin1_general_ci NOT NULL,
`address` varchar(80) COLLATE latin1_general_ci NOT NULL,
`phone` varchar(20) COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
— ——————————————————–
—
— Table structure for table `orders`
—
CREATE TABLE IF NOT EXISTS `orders` (
`serial` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`customerid` int(11) NOT NULL,
PRIMARY KEY (`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
— ——————————————————–
—
— Table structure for table `order_detail`
—
CREATE TABLE IF NOT EXISTS `order_detail` (
`orderid` int(11) NOT NULL,
`productid` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`price` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
— ——————————————————–
—
— 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=11 ;
—
— Dumping data for table `products`
—
INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`) VALUES
(1, ‘Google Nexus 6’, ‘The Qualecomm @ snapdragon 805 quard-core processor provides lightning fast multi tasking and the Adreno 420 Gpu gives you brilliant graphics.’, 699, ‘images/mobile.jpg’),
(2, ‘Ipad Air 2’, ‘Full HD Recording,\nWi-Fi Enabled,\nFaceTime,\n8 MP Primary Camera,\nA8X Chip with M8 Motion Co-processor,\n1.2 MP Secondary Camera,\n9.7-inch LED Touchscreen’, 396, ‘images/ipad.jpg’),
(3, ‘Home Theater’, ‘ Home Theater 4.1 with USB and FM Wired Home Audio Speaker’, 64, ‘images/sound.jpg’),
(4, ‘Samsung Split AC’, ‘Out Door Unit Stand.\nExtra copper wire if any.\nDrain Pipe extension if any.\nPlumbing and Masonry Work.\nWiring extension from Meter to site, Power point/MCB fitting and any other electrical work,Carpentry work.’, 461, ‘images/ac.jpg’),
(5, ‘Nikon DSLR Camera’, ‘(Black, Body with AF-S DX NIKKOR 18-55mm f/3.5-5.6G VR II Lens) 2 Years Nikon India Warranty and Free Transit Insurance.’, 850, ‘images/camera.jpg’),
(6, ‘Tea maker’, ‘Morphy Richards 1.5 Ltr – Tea Maker Silver Black’, 41, ‘images/teamaker.jpg’);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Very useful for the codeigniter shopping cart for biginers
How can I add pictures to the products through sql statement/query or in php code?
Thank you so much sir, i’ve fully satisfied u r code.
the code is has been useful for me in learning shopping cart implementation in CodeIgniter
Ok after few times i get the download link, it is easy and simple to understand thank you so much
Thanks your article really helped me, but my requirement is slight different, I have option cart fields also.
I added items to cart like this.
$data = array(
‘id’ => $product_details->id,
‘qty’ => 1,
‘price’ => 1,
‘name’ => $product_details->title,
‘options’ => array(‘size’ => $size, ‘color’ => $color ”)
);
$this->cart->insert($data);
Here in above code you can see that I’ve two option values ‘size’ and ‘color’, inserting those value is not problem I did exactly as u taught but, while update I got problem. I tried to update doing this
foreach ($this->input->post() as $key => $value) {
$data = array(
‘rowid’ => $key,
‘options’ => array(‘color’ => ‘aa’, ‘size’ => ‘bb’)
);
$this->cart->update($data);
}
But didn’t work out. will you please help me to get rid of this problem.
nyc and working
thanks friends u tell me this code very use full
Simple and Very neat explanation
1. The Cart library is DEPRECATED , so in this case is it safe to use cart library.
2. ideally by when the code igniter team is expected to come up with the solution for cart class problems
Nice tutorial, but:
Sometime happen that is not possible add more differents items to the cart ( in the shopping page):
on a clean installation, I’ve tried to put other 6 items in the database: sometime I can add all the items to the cart, sometime I can add only 7/8 (differents) items, after this pressing on button “add” does not run….
Thank in advance
Chico
download script not received
Excellent. Served me perfect as a starter, the CI cart library still works well even though deprecated. The blessing of having the source code.
hello greetings
I’m not able to download the script
Shopping Cart