Professional CodeIgniter

(singke) #1

Chapter 4: Creating the Main Web Site


99


Updating the MProducts Model


Before you work with the controller, you ’ ll need to create a new function in the MProducts model, one
that will allow you to extract a variable number of products that match a grouping. Here is that new
function, called getProductsByGroup(). It accepts three arguments: The first limits the result set, the
second passes in a grouping string to match against, and the third tells the function which product ID to
skip (in this case, the product you ’ re skipping is the one that has been displayed on the page).

function getProductsByGroup($limit,$group,$skip){
$data = array();
if ($limit == 0){
$limit=3;
}
$this- > db- > select(‘id,name,shortdesc,thumbnail’);
$this- > db- > where(‘grouping’, $group);
$this- > db- > where(‘status’, ‘active’);
$this- > db- > where(‘id !=’, $skip);
$this- > db- > orderby(‘name’,’asc’);
$this- > db- > limit($limit);
$Q = $this- > db- > get(‘products’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[] = $row;
}
}
$Q- > free_result();
return $data;
}

Building the product() Controller Function


Now it ’ s time to build the controller. By now the pattern should be pretty established in your mind. Your
controller function for product() looks like this:

function product($id){
$product = $this- > MProducts- > getProduct($id);
if (!count($product)){
redirect(‘welcome/index’,’refresh’);
}
$data[‘grouplist’] = $this- > MProducts-
> getProductsByGroup(3,$product[‘grouping’],$id);
$data[‘product’] = $product;
$data[‘title’] = “Claudia’s Kids | “. $product[‘name’];
$data[‘main’] = ‘product’;
$data[‘navlist’] = $this- > MCats- > getCategoriesNav();
$this- > load- > vars($data);
$this- > load- > view(‘template’);
}
Free download pdf