Chapter 3: A 10,000 - Foot View of CodeIgniter
67
The Products Model
Now it ’ s time to build your model for the products table: MProducts. Create a file called mproducts.php in
the /system/application/models/ folder, and populate it with the following information:
class MProducts extends Model{
function MProducts(){
parent::Model();
}
function getProduct($id){
$data = array();
$options = array(‘id’ = > $id);
$Q = $this- > db- > getwhere(products,$options,1);
if ($Q- > num_rows() > 0){
$data = $Q- > row_array();
}
$Q- > free_result();
return $data;
}
function getAllProducts(){
$data = array();
$Q = $this- > db- > get(‘products’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[] = $row;
}
}
$Q- > free_result();
return $data;
}
}
Structurally speaking, this model is very similar to the model you created for Categories. In fact, the only
thing you ’ ve changed so far is the name of the model, the constructor call, and the name of the database
table employed by the two functions.
As with the Categories model, you ’ ll eventually create various specialized functions to get your work
done (e.g., you ’ ll need a function that will retrieve all products by category_id ), but for now you have
a good beginning.
Autoloading Your Models
Now that you have two bare - bones models built, open the /system/application/config/autoload.php
file and add them both to the model $autoload option:
$autoload[‘model’] = array(‘MProducts’, ‘MCats’);
Autoloading models makes them globally available to your entire application and saves time because
you don ’ t have to load them locally.