Building a basic PHP E-Commerce Application using CodeIgniter Framework – Part 2

part 2 - code igniter e-commerce turorial

Part 2 -Creating the application database model.

Now that we are done the CI installation. We are ready to start building our e-commerce application. What we need to do first is design our database structure. You can of course freely design your own structure, but for this tutorial I made it simple.


Now, Let say,

I want to categorize my products. So we must have a table for category.

Product category can have a child category.

Category can be deactivated and activated.

This is our table for categories looks like.

CREATE TABLE `categories` (
  `cat_id` int(11) NOT NULL auto_increment,
  `cat_name` varchar(255) NOT NULL,
  `cat_shortdesc` varchar(255) NOT NULL,
  `cat_longdesc` text NOT NULL,
  `cat_parentid` int(11) NOT NULL,
  `cat_status` tinyint(1) NOT NULL,
  PRIMARY KEY  (`cat_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Then our products,

Can only belong to one category at a time

Our products has a name, image, thumbnail, short description, long description

And can be activated and deactivated.

This is what I came up with our products table.

CREATE TABLE `products` (
  `prod_id` int(11) NOT NULL auto_increment,
  `prod_name` varchar(255) NOT NULL,
  `prod_shortdesc` varchar(255) NOT NULL,
  `prod_longdesc` text NOT NULL,
  `prod_thumbnail` varchar(255) NOT NULL,
  `prod_image` varchar(255) NOT NULL,
  `prod_status` tinyint(1) NOT NULL,
  `prod_category_id` int(11) NOT NULL,
  `prod_featured` tinyint(1) NOT NULL,
  `prod_price` float(4,2) NOT NULL,
  PRIMARY KEY  (`prod_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Insure you have a database installation on your local webserver. Using any mySQL client available in your end just throw this SQL to create the tables.

Creating the Categories Model

In creating a model in CodeIgniter you can name it anything you want as long as it don’t have any conflicts of names in other model or to your controller. It is a good practice to put a prefix or suffixes to your model’s name. My style in naming a model is chosen name suffixed by ‘Model’. So I have to name our model to ‘categoryModel’.

More details about creating model can be read in CI userguide. Now let’s create our basic model called categoryModel and our constructor.

<?php

class categoryModel extends Model{

	function categoryModel(){
		parent::Model();
	}

}

Save the file as categorymodel.php in your system/application/models/ directory.

Then add a function that will retrieve a category from the database.

	function getCategory($id){

		$data = array();

		$where = array('cat_id' => $id);

		$quer = $this->db->getwhere('categories',$where,1);

		if ($query-> num_rows() > 0){
			$data = $query->row_array();
		}

		$query->free_result();
		return $data;
	}

This function passes in an $id variable that is used to select one row matching that ID from the categories table. It then returns the data as an array for future use.

Now we can select our category one by one with the function we just made. Next we have to create a function that returns all the categories in our categories table.

	function getAllCategories(){
		$data = array();
		$query = $this->db->get('categories');

		if ($query->num_rows() > 0){
			foreach($query->result_array() as $row){
			$data[] = $row;
			}
		}
		$query-> free_result();
		return $data;
	}

For more details about CI database class check the userguide.

Your categorymodel.php should look like this now.

<?php

class categoryModel extends Model{

	function categoryModel(){
		parent::Model();
	}

	function getCategory($id){

		$data = array();

		$where = array('cat_id' => $id);

		$query = $this->db->getwhere('categories',$where,1);

		if ($query-> num_rows() > 0){
			$data = $query->row_array();
		}

		$query->free_result();
		return $data;
	}

	function getAllCategories(){
		$data = array();
		$query = $this->db->get('categories');

		if ($query->num_rows() > 0){
			foreach($query->result_array() as $row){
			$data[] = $row;
			}
		}
		$query-> free_result();
		return $data;
	}
}

We will be adding another functions in our category model later as we go on to the tutorial.

Creating the Products Model

Now create a new file name it productsmodel.php in your /system/application/models/ folder. And copy the code below.

<?php

class productsModel extends Model{

	function productsModel(){

		parent::Model();

	}

	function getProduct($id){

		$data = array();

		$where = array('prod_id' => $id);

		$query = $this->db->getwhere('products',$where,1);

			if ($query-> num_rows() > 0){
				$data = $query-> row_array();
			}

		$query->free_result();

		return $data;

	}

	function getAllProducts(){

		$data = array();

		$query = $this-> db-> get('products');

		if ($query-> num_rows() > 0){
			foreach ($query-> result_array() as $row){
			$data[] = $row;
			}
		}

		$query-> free_result();

		return $data;
	}
}

As you can see our product model is very similar to our category model. The only difference between the two in the model name and the name of the database table.

As we go ahead later on this series maybe we need to add more functions to this models like for example a function that will retrieved all the products by a category id. But that’s it for now.

Now we need to auto load our models so that it will be available globally and saves us time in loading it locally in our controller. To do so, open the file /system/application/config/autload.php. Find $autoload option and add the following line.

$autoload['model'] = array('categoryModel', 'productsModel');

Also we need to autoload the database library.

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

Insert a dummy data to your table. You can use my dummy data if you want.

For the categories table.

INSERT INTO `ci_tutorial`.`categories` (
`cat_id` ,
`cat_name` ,
`cat_shortdesc` ,
`cat_longdesc` ,
`cat_parentid`
)
VALUES
('1', 'Photo Books', 'This is a photo books', 'This is a long description of the photo book category.', '0'),
('2', 'Photo Calendar', 'This is a photo calendar', 'This is a long description of the Photo Calendar category.', '0'),
('3', 'Photo Tumblers', 'This is a photo Tumbler', 'This is a long description of the photo tumbler category.', '0'),
('4', 'Photo Magnets', 'This is a photo magnets', 'This is a long description of the Photo magenets category.', '0');

For the products table.

INSERT INTO `products` (`prod_id`, `prod_name`, `prod_shortdesc`, `prod_longdesc`, `prod_thumbnail`, `prod_image`, `prod_status`, `prod_category_id`, `prod_featured`, `prod_price`) VALUES
(1, 'Large Hard Cover Photo Book', 'Short Description of Large Hard Cover Photo Book', 'Long Description of Large Hard Cover Photo Book', '/uploads/products/thumb/lhc-photo-books.jpg', '/uploads/products/lhc-photo-books.jpg', 1, 1, 1, 20.50),
(2, 'Desktop Tumbler', 'Short Description  Desktop Tumbler', 'Long Description Desktop Tumbler', '/uploads/products/thumb/d-tumbler.jpg', '/uploads/products/d-tumbler.jpg', 1, 3, 0, 15.23);

To test our models if it’s working, open your test controller you just made in the first part of the tutorial. And populate the following code below.

<?php

class test extends Controller {

	function test()
	{
		parent::Controller();
		$this->load->library('parser');
	}

	function index()
	{
		$data['title']  = 'Building an e-commerce application using CodeIgniter ';
        $data['header'] = 'Header of the Test Page';
        $data['body']   = 'Test content here. Another content gooes here.';

        $id = '1'; //sample value of cat_id

        //test our category model
        $myCat = $this->categoryModel->getCategory($id);

        $data['myCat'] = $myCat['cat_name'];
        $data['allCategory'] = $this->categoryModel->getAllCategories();

        //test our product model
        $myProduct = $this->productsModel->getProduct($id);

        $data['myProduct'] = $myProduct['prod_name'];
        $data['allProducts'] = $this->productsModel->getAllProducts();

        $this->parser->parse('test_page', $data);
    }

}

Open your test view created in part 1 of this tutorial and populate the code below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

</head>
<body>

<h4>A Category With an ID of 1</h4>

<p>{myCat}</p>

<h4>All Category List</h4>
	<ul>
		<?php foreach($allCategory as $cat){?>
			<li>
			<?= $cat['cat_name']; ?>
			</li>
		<?php } ?>
	</ul>

<hr />

<h4>A Product With an ID of 1</h4>

<p>{myProduct}</p>

<h4>All Product List</h4>

	<ul>
		<?php foreach($allProducts as $product){?>
			<li>
			<?= $product['prod_name']; ?>
			</li>
		<?php } ?>
	</ul>

</body>
</html>

Now open your browser and go to the address of your application installation, in this tutorial our address is http://localhost/tutorial/. Since we have to view our test controller, type this url http://localhost/tutorial/test/

You must now see a list of categories and products we just have inserted lately to our database.

The third part of the tutorial will be posted soon. Thank you for reading.

PG

Author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

Related Post

Delicious

43 Responses to “Building a basic PHP E-Commerce Application using CodeIgniter Framework – Part 2”

  1. Nice! Thank you for this :)

  2. Great Job Insic!

    We still have to make an article together sometime :D let me know when you want to do it!

    <3 Ryan M

  3. @Jeff Starr Thank you for reading too.

  4. @Ryan Miller ok ill drop you an email. :)

  5. Nice work. Very thorough.

  6. Hy there!

    You said to save productsModel as productModel.php and the corect name is: productsModel.php. (cause in autoload it is specified as productsModel)
    You forgot to specify that it is necessary to modify application/config/autoload.php and replace:
    $autoload['libraries'] = array();
    with
    $autoload['libraries'] = array(‘database’);
    Otherwise the app can`t use the database. Anyway nice tut!

    P.S.: sorry for my english, but I`m not a native speaker.

  7. I am very excited for Part 3 of this series.  I like how you are taking your time to go over each step.  If you could cover how you do a common global layout for each page (i.e. same footer, header, left nav, shopping cart status) that would be really helpful too.
    Thanks!!

  8. @George Jipa thanks for the headsup. it must be a typo. yes it supposed to be productsmodel.php not productmodel.php.

    And I must forget to add this one above $autoload['libraries'] = array(’database’);

    Thank you so much.

  9. @abadaba Part 3 of the tutorial covers all about views covers those global layout you mention.  and hopefully we can take up shopping cart in part 5.

  10. Nice tutorial. I’m looking forward to part 3, don’t make us wait too long! :-)

  11. YAY… yer my new hero!  Can’t wait for part 3! 

    PS – I recently went through the shopping cart app in the book “Professional Codeigniter” and just from the beginnings of your tutorial here I can tell the final product at the end of your tutorial is going to be better in many ways than the example in the book!

  12. excellent series of articles

  13. Hey According to your post You told  to save productsModel as productModel.php but  the corect name is: productsModel.php.

  14. @Michel John sorry for that, i cant believe why I did not update it yet. Im doing it now. thanks

  15. 呵呵,我对代码不懂,看了就有点头痛,呵呵,但设计不错

  16. @BLACK if you are willing to learn, later on the headache is gone.

  17. Very usefull tips. by the way at present I used e-store soystem by prestashop. It’s look well system e-commerce

  18. Insic2.0,i’m began to learn CI a few days ago, andi’m in doubt if it’s better or not to use db->query instead of db->get, db->where…. can you explain this?

  19. @Eduardo you can use either of the two.

  20. Did you switch from Zend to Codelgniter?
    And, why?

  21. @Gustav hmmm not switch actually I still develop app using Zend it depends on my clients needs. :)

  22. @10ha thanks for the heads up.

  23. Hi insic,

    Super post – I do have some other questions that could use your insights. Would you mind emailing me separately? I didn’t see a contact form (jae@ejaedesign.com)

  24. This is good, but how long did all that take to write, i wanna write some tutorials too.

  25. I think it is a good tutorial, i like this framework and i’m looking forward for the next tut :D

  26. Awesome post. You did a real nice job… Were waiting for the part 3. God Bless.

  27. nice work. i will be in constant touch

  28. Thank you Very Much My Brother:)

  29. Coding chicks are so hot. Please give me a cage with the view of the rising sun when the amazonians take over.

  30. Can someone please explane this for me?
    `cat_parentid` int(11) NOT NULL
    I don’t know what it’s good for?

  31. Thanks. On to part 3

  32. wow this is such a useful tutorial, thanks for sharing on your blog! I know good tutorials aren’t easy to come by these days, but following this was so easy and it’ll be useful on my website

  33. thanks… it was a very nice tutorial …

  34. whene will you publish part 4

  35. please publish add item in a cart.

  36. You are a nice !!!

    Thanks for your clear tutorials.
    It saves me time and energy.
    Thanks.

  37. Use some polymorphism with your models… leave out things like Products and Categories in the functions.

Leave a Reply