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

Feb 16, 2009 insic 61 Comments

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.

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.

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.

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

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

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.

For more details about CI database class check the userguide.

Your categorymodel.php should look like this now.

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.

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.

Also we need to autoload the database library.

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

For the categories table.

For the products table.

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.

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

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.

About the 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.

  • http://perishablepress.com/ Jeff Starr

    Nice! Thank you for this :)

  • Ryan Miller

    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

  • http://blog.insicdesigns.com insic2.0

    @Jeff Starr Thank you for reading too.

  • http://blog.insicdesigns.com insic2.0

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

  • http://www.duzodesign.com Timothy

    Nice work. Very thorough.

  • http://www.georgejipa.info George Jipa

    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();
    $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.

  • abadaba

    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.

  • http://blog.insicdesigns.com insic2.0

    @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.

  • http://blog.insicdesigns.com insic2.0

    @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.

  • http://www.davidrojas.net David Rojas

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

  • http://ntbg.org/ Matt G.

    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!

  • http://www.derekunderwood.com Derek Underwood

    excellent series of articles

  • http://www.ewaycorp.com/services.php Michel John

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

  • http://blog.insicdesigns.com insic2.0

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



  • http://blog.insicdesigns.com insic2.0

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

  • http://sifeng.blog.sohu.com/ maple

    Very good!

  • http://rizarohman.com Riza

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

  • Eduardo

    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?

  • http://blog.insicdesigns.com insic2.0

    @Eduardo you can use either of the two.

  • http://www.gern.se Gustav

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

  • http://blog.insicdesigns.com insic2.0

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

  • 10ha

    Just a note, if you follow Derek Allard’s tweet,
    a cart class has been added.

  • http://blog.insicdesigns.com insic2.0

    @10ha thanks for the heads up.

  • http://www.ejaedesign.com Jae Barclay
  • http://www.swaymedia.com Sirwan

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

  • http://www.noxmediastudio.com Asinox

    Nice :) thanks

  • http://www.quizzpot.com Crysfel

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

  • http://www.imediasolutions.org randomideas

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

  • bless

    nice work. i will be in constant touch

  • http://www.twenstudio.com Twen

    Thank you Very Much My Brother:)

  • http://www.marocplus.net Directory marocplus


  • http://m111m.net Topics


  • http://novatvmedia.com Ezrad Lionel

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

  • Felix Karlsson

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

  • http://wowcruit.com Chris

    Thanks. On to part 3

  • http://auto-oglas.com rodman

    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

  • http://mypress.ir hossein

    thanks… it was a very nice tutorial …

  • http://mypress.ir hossein

    whene will you publish part 4

  • raju

    please publish add item in a cart.

  • Pingback: CodeIgniter « Future Technology

  • http://pulsakumoerah.com tikko

    You are a nice !!!

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

  • matt

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

  • http://www.pctipstricks.net aman

    i am new in codeigniter, and this tutorial really helped me . thnxxxxx

  • http://none Max

    Please reupload sources of your project/ because I can’t download it.


  • http://www.ebspromo.com/ ebspromo

    Is there another installment coming to this minimal example? It really is nothing more than every-day data pull/presentation that most of us should already know how to do with the CI MVC architecture (even those having only read the user guide).

  • http://www.ebspromo.com ebspromo

    hmmm, guess I should say nevermind looking at the original age of the post. guess i’ll start my own and provide a more complete example on my blog when it’s nearing completion ;)

  • Pingback: Développer une boutique en ligne avec le framework MVC Codeigniter « Trois Point Zéro – webdesign, développement et actualité autour du web par Grégory BABONAUX, concepteur web freelance

  • anthony

    i keep getting a page not found error,, what could i be doing wrong? please advice

  • http://prohackingtricks.blogspot.com Hacking Tricks

    nice design, though am familiar with zend but i think i can still get a feel of this too.

  • http://www.philipstel.web.id/ Philips

    Thank you Insic.. I really like this stuff (part 1 and 2), it’s clean and easy to follow. IC is my most favorite Framework.

  • http://www.newpctrick.blogspot.com PC Tricks And Tips

    Thank you so much for sharing this information.So easy to understand with the help of screen shot.

  • Idris

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

    getwhere –> get_where

    • hman1

      and also, in the newer version of Code igniter you need this in the Test Controller consructor:
      $this->load->database(); otherwise you will get a non-object error.

  • http://philipstel.web.id Philips

    Can I get your email please ..??

  • joel

    I can’t download the application.
    Can Someone help me?

  • peter

    hi, getting error:

    Call to a member function getCategory() on a non-object

    Have set up all instructions.
    what should i do ?

  • oghenez

    i still get the default “Welcome to CodeIgniter!” after doing all the coding, what am i doing wrong?

    • http://www.facebook.com/arsalanworld Arsalan Ajmal

      Hey buddy, you must go to application>config>routes.php , there in the routes file replace welcome with test or the name of your controller you created! I hope this would work now

  • http://www.facebook.com/arsalanworld Arsalan Ajmal

    Thank you v.much insic, for your tutorial

  • Jeremy Smith

    I keep getting this error:

    “Severity: Warning

    Message: Invalid argument supplied for foreach()

    Filename: views/test_page.php”

    Looked at the relevant file but appears to be fine as it’s exactly like the one above it, I am confused could anyone help?