Posts tagged: cart

Shopping Cart for CodeIgniter

Despite much Googling, I haven’t been able to find a ready made shopping cart for the CodeIgniter PHP framework. Unfortunately one of my current projects requires such a thing, so I decided to roll my own. Starting from the code here: http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart, I made a few changes to fit the CodeIgniter way of doing things.

The revised version looks like this:

  1. <?php
  2. // Based on http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart
  3. class Cart extends Controller {
  4. function Cart()
  5. {
  6. parent::Controller();
  7. $this->load->library('session');
  8. $this->load->helper('url');
  9. }
  10. function index()
  11. {
  12. $cart = $this->session->userdata('cart');
  13. if ($cart) {
  14. $items = explode(',',$cart);
  15. $contents = array();
  16. foreach ($items as $item) {
  17. $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
  18. }
  19. }
  20. if ($contents)
  21. {
  22. $id_list = '';
  23. foreach(array_keys($contents) as $val)
  24. $id_list .=  $this->db->escape($val) .',';
  25. $id_list = substr($id_list,0,len($id_list) - 1);
  26. $query_string = "SELECT * FROM stock_table WHERE id IN(".$id_list.")";
  27. $query = $this->db->query($query_string);
  28. f ($query->num_rows() > 0)
  29. {
  30. $basket = array();
  31. foreach ($query->result() as $row)
  32. {
  33. $basket[] = array('id' => $row->id, 'caption' => $row->caption, 'price' => $row->price,
    'qty' => $contents[$row->id], 'total' => $contents[$row->id] * $row->price);
  34. }
  35. }
  36. }
  37. $data = array();
  38. if ($basket)
  39. {
  40. $data['basket'] = $basket;
  41. $grand_total = 0;
  42. foreach($basket as $item)
  43. $grand_total += $item[total];
  44. $data['grand_total'] = sprintf("%01.2f", $grand_total);
  45. }
  46. else
  47. $data['grand_total'] = sprintf("%01.2f", 0);
  48. $data['page'] = 'cart_view';
  49. $data['title'] = "Your basket";
  50. $this->load->view('template/container',$data);
  51. }
  52. function add_item($item_id='')
  53. {
  54. $cart = $this->session->userdata('cart');
  55. if ($cart) {
  56. $cart .= ','.$item_id;
  57. } else {
  58. $cart = $item_id;
  59. }
  60. $this->session->set_userdata(array('cart' =>
  61. $cart));
  62. redirect('/cart/', 'refresh');
  63. }
  64. function delete_item($item_id='')
  65. {
  66. $cart = $this->session->userdata('cart');
  67. if ($cart) {
  68. $items = explode(',',$cart);
  69. $newcart = '';
  70. foreach ($items as $item) {
  71. if ($item_id != $item) {
  72. if ($newcart != '') {
  73. $newcart .= ','.$item;
  74. } else {
  75. $newcart = $item;
  76. }
  77. }
  78. }
  79. $cart = $newcart;
  80. }
  81. $this->session->set_userdata(array('cart' =>
  82. $cart));
  83. redirect('/cart/', 'refresh');
  84. }
  85. function delete_all()
  86. {
  87. $this->session->unset_userdata('cart');
  88. redirect('/cart/', 'refresh');
  89. }
  90. function update_cart()
  91. {
  92. if ($cart) {
  93. $newcart = '';
  94. foreach ($_POST as $key=>$value) {
  95. if (stristr($key,'qty')) {
  96. $id = str_replace('qty','',$key);
  97. $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
  98. $newcart = '';
  99. foreach ($items as $item) {
  100. if ($item_id != $item) {
  101. if ($newcart != '') {
  102. $newcart .= ','.$item;
  103. } else {
  104. $newcart = $item;
  105. }
  106. }
  107. }
  108. for ($i=1;$i<=$value;$i++) {
  109. if ($newcart != '') {
  110. $newcart .= ','.$id;
  111. } else {
  112. $newcart = $id;
  113. }
  114. }
  115. }
  116. }
  117. }
  118. $this->session->set_userdata(array('cart' =>
  119. $newcart));
  120. redirect('/cart/', 'refresh');
  121. }
  122. function checkout()
  123. {
  124. }
  125. }

The associated view looks like this:

  1. <p>Basket Total: &pound;<?=$grand_total?></p>
  2. <?php
  3. if (isset($basket))
  4. {
  5. ?>
  6. <form method="post" id="cart-form" action="<?=site_url().'update_cart'?>">
  7. <table>
  8. <tr><td>ID:</td><td>Desc:</td><td>Price:</td><td>Quantity:</td><td>Total:</td><td>Delete?</td></tr>
  9. <?php
  10. foreach ($basket as $val)
  11. {
  12. ?>
  13. <tr><td><?=$val['id']?></td><td><?=$val['caption']?></td><td><?=$val['price']?></td>
    <td><input type="text" name="qty'<?=$val['id']?>'" value="<?=$val['qty']?>" size="3" maxlength="3" /></td>
    <td><?=$val['total']?></td><td><a href="<?=site_url().'delete_item/'.$val['id']?>">[x]</a></td></tr>
  14. <?php
  15. }
  16. ?>
  17. </table>
  18. <input type="submit" name="submit" value="Update Cart" />
  19. </form>
  20. <p><a href="<?=site_url().'delete_all'?>">Empty Cart</a></p>
  21. <p><a href="<?=site_url().'checkout'?>">Checkout</a></p>
  22. <?php
  23. }
  24. else
  25. {
  26. ?>
  27. <p>Your shopping basket is empty.</p>
  28. <?php
  29. }
  30. ?>

The code also assumes a database “stock_table” with the following structure:

  1. --
  2. -- Table structure for table `stock_table`
  3. --
  4. CREATE TABLE IF NOT EXISTS `stock_table` (
  5. `id` int(10) unsigned NOT NULL auto_increment,
  6. `caption` varchar(20) NOT NULL,
  7. `quantity` int(10) NOT NULL default '0',
  8. `price` float NOT NULL,
  9. PRIMARY KEY  (`id`)
  10. ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

This code has yet to be put to the test in a production environment, so use it entirely at your own risk. You will also notice that the checkout function has not been completed. This is a project for another day, and it’s worth looking at the CodeIgniter PayPal library http://codeigniter.com/wiki/PayPal_Lib/ to help you.

WordPress Themes