Build Shopping Cart with Session in CodeIgniter Framework


Create new database named learn_codeigniter_with_real_apps. This database have 1 table: Product table.

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` double NOT NULL,
  `quantity` int(11) NOT NULL,
  `description` text NOT NULL,
  `status` tinyint(1) NOT NULL,
  `photo` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 1', 2, 5, 'Description 1', 0, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 2', 7, 3, 'Description 2', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 3', 2, 7, 'Description 3', 1, 'thumb3.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 4', 3, 8, 'Description 4', 1, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 5', 8, 2, 'Description 5', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 6', 9, 11, 'Description 6', 1, 'thumb3.gif');

Structure of Product Table

Data of Product Table




Create new folder named assets in root project. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

$config['base_url'] = 'http://localhost:9092/LearnCodeIgniterWithRealApps/';

In CodeIgniter Project, Open autoload.php file in config folder. Add url helper to helper config as below:

$autoload['helper'] = array('url');

In CodeIgniter Project, Open autoload.php file in config folder. Add database and session libraries to libraries config as below:

$autoload['libraries'] = array('database', 'session');

In CodeIgniter Project, Open database.php file in config folder. Add values as below connect to database:

$db['default'] = array(
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '123456',
	'database' => 'learn_codeigniter_with_real_apps'
);

Create new PHP file named product_model.php in models folder as below:

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

class Product_model extends CI_Model
{

    function findAll()
    {
        return $this->db->get('product')->result();
    }

    function find($id)
    {
        return $this->db->where('id', $id)->get('product')->row();
    }

}




In CodeIgniter Project, Open autoload.php file in config folder and set value for model config as below:

$autoload['model'] = array('product_model' => 'productModel');

In controllers folder, create new controllers as below:

Create new PHP file named product.php in controllers folder as below:

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

class Product extends CI_Controller
{

    public function index()
    {
        $data['products'] = $this->productModel->findAll();
        $this->load->view('product/index', $data);
    }

}

Create new PHP file named cart.php in controllers folder. This file contains Shopping Cart operators as below:

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

class Cart extends CI_Controller
{

    public function index()
    {
        $data['items'] = array_values(unserialize($this->session->userdata('cart')));
        $data['total'] = $this->total();
        $this->load->view('cart/index', $data);
    }

    public function buy($id)
    {
        $product = $this->productModel->find($id);
        $item = array(
            'id' => $product->id,
            'name' => $product->name,
            'photo' => $product->photo,
            'price' => $product->price,
            'quantity' => 1
        );
        if(!$this->session->has_userdata('cart')) {
            $cart = array($item);
            $this->session->set_userdata('cart', serialize($cart));
        } else {
            $index = $this->exists($id);
            $cart = array_values(unserialize($this->session->userdata('cart')));
            if($index == -1) {
                array_push($cart, $item);
                $this->session->set_userdata('cart', serialize($cart));
            } else {
                $cart[$index]['quantity']++;
                $this->session->set_userdata('cart', serialize($cart));
            }
        }
        redirect('cart');
    }

    public function remove($id)
    {
        $index = $this->exists($id);
        $cart = array_values(unserialize($this->session->userdata('cart')));
        unset($cart[$index]);
        $this->session->set_userdata('cart', serialize($cart));
        redirect('cart');
    }

    private function exists($id)
    {
        $cart = array_values(unserialize($this->session->userdata('cart')));
        for ($i = 0; $i < count($cart); $i ++) {
            if ($cart[$i]['id'] == $id) {
                return $i;
            }
        }
        return -1;
    }

    private function total() {
        $items = array_values(unserialize($this->session->userdata('cart')));
        $s = 0;
        foreach ($items as $item) {
            $s += $item['price'] * $item['quantity'];
        }
        return $s;
    }
}

In CodeIgniter Project, Open routes.php file in config folder. Set value for default_controller as below:

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




In views folder, create new views as below:

Create new folder named product in views folder. In this folder, create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Product List</title>
	</head>
	<body>
		<h3>Product List</h3>
        <table border="1" cellpadding="2" cellspacing="2">
        	<tr>
        		<th>Id</th>
        		<th>Name</th>
        		<th>Photo</th>
        		<th>Status</th>
        		<th>Description</th>
        		<th>Price</th>
        		<th>Quantity</th>
        		<th>Sub Total</th>
        		<th>Action</th>
        	</tr>
        	<?php foreach ($products as $product) { ?>
        		<tr>
        			<td><?php echo $product->id; ?></td>
        			<td><?php echo $product->name; ?></td>
        			<td><img src="<?php echo base_url(); ?>assets/images/<?php echo $product->photo; ?>" width="50"></td>
        			<td><?php echo $product->status ? 'active' : 'inactive'; ?></td>
        			<td><?php echo $product->description; ?></td>
        			<td><?php echo $product->price; ?></td>
        			<td><?php echo $product->quantity; ?></td>
        			<td><?php echo $product->price * $product->quantity; ?></td>
        			<td>
        				<a href="<?php echo site_url('cart/buy/'.$product->id); ?>">Buy Now</a>
        			</td>
        		</tr>
        	<?php } ?>
        </table>
	</body>
</html>

Create new folder named cart in views folder. In this folder, create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Cart Info</title>
	</head>
	<body>
		<h3>Cart Info</h3>
        <table border="1" cellpadding="2" cellspacing="2">
        	<tr>
        		<th>Id</th>
        		<th>Name</th>
        		<th>Photo</th>
        		<th>Price</th>
        		<th>Quantity</th>
        		<th>Sub Total</th>
        		<th>Action</th>
        	</tr>
        	<?php foreach ($items as $item) { ?>
        		<tr>
        			<td><?php echo $item['id']; ?></td>
        			<td><?php echo $item['name']; ?></td>
        			<td><img src="<?php echo base_url() ?>assets/images/<?php echo $item['photo']; ?>" width="50"></td>
        			<td><?php echo $item['price']; ?></td>
        			<td><?php echo $item['quantity']; ?></td>
        			<td><?php echo $item['price'] * $item['quantity']; ?></td>
        			<td align="center">
        				<a href="<?php echo site_url('cart/remove/'.$item['id']); ?>">X</a>
        			</td>
        		</tr>
        	<?php } ?>
        		<tr>
        			<td colspan="6" align="right">Total</td>
        			<td><?php echo $total; ?></td>
        		</tr>
        </table>
        <br>
        <a href="<?php echo site_url('product'); ?>">Continue Shopping</a>
	</body>
</html>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/product/index

Output

Click Buy Now link to select product add to cart

Output

I recommend you refer to the books below to learn more about the knowledge in this article: