Chapter 3: A 10,000 - Foot View of CodeIgniter
66
The second function retrieves all categories from the database:
function getAllCategories(){
$data = array();
$Q = $this- > db- > get(‘categories’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[] = $row;
}
}
$Q- > free_result();
return $data;
}
This function is much simpler. All that ’ s needed is a call to $this - > db - > get() with an argument of
categories (the name of the database table), and all records from the database are retrieved as an array.
Your MCats model (stored in the /system/application/models/mcats.php file) should look like
this now:
class MCats extends Model{
function MCats(){
parent::Model();
}
function getCategory($id){
$data = array();
$options = array(‘id’ = > $id);
$Q = $this- > db- > getwhere(‘categories’,$options,1);
if ($Q- > num_rows() > 0){
$data = $Q- > row_array();
}
$Q- > free_result();
return $data;
}
function getAllCategories(){
$data = array();
$Q = $this- > db- > get(‘categories’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[] = $row;
}
}
$Q- > free_result();
return $data;
}
}
As you progress through the project, you ’ ll add more specialized functions (e.g., you will eventually
need an easy way to grab categories that have a certain parentid), but for right now, this is good
progress.