Professional CodeIgniter

(singke) #1

Chapter 4: Creating the Main Web Site


82


Open the MProducts model (/system/application/models/mproducts.php). This model contains two
bare - bones functions: getProduct() and getAllProducts(). At first glance, the getProduct()
function looks promising, as you could call it four times and then check in each case for a featured
designation of TRUE (or category IDs), but this approach feels too heavy - handed. In other words, it ’ s
like using a bulldozer where a shovel (or even a spoon) would suffice. It would be better for all involved
to use a more specific query to get what we want and use that instead.

Instead, let ’ s create two simple functions that will pull out the information needed to build the home
page. The first new function, getMainFeature() ,selects a random featured item for the home page.
The second function, getRandomProducts() ,selects random products from different categories (but
never one that was chosen as the main feature on the same page).

Retrieving the Main Featured Product


Here ’ s what the getMainFeature() function looks like. Notice the use of the built - in Active Record
methods to get what you want, which is a random featured product from the products table:

function getMainFeature(){
$data = array();
$this- > db- > select(“id,name,shortdesc,image”);
$this- > db- > where(‘featured’,’true’);
$this- > db- > where(‘status’, ‘active’);
$this- > db- > orderby(“rand()”);
$this- > db- > limit(1);
$Q = $this- > db- > get(‘products’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data = array(
“id” = > $row[‘id’],
“name” = > $row[‘name’],
“shortdesc” = > $row[‘shortdesc’],
“image” = > $row[‘image’]
);
}
}
$Q- > free_result();
return $data;
}

Pay special attention to the $this - > db - > orderby( “ rand() ” ) directive. It builds an “ order by rand() ”
SQL snippet. Combining this directive with $this - > db - > limit(1) retrieves exactly one random item.
The query is further limited by the $this - > db - > where( ‘ featured ’ , ‘ true ’ ) directive, which filters
the result set to those records that have the featured field set to TRUE.

In other words, the resultant SQL query is :

select id, name, shortdesc, image
from products
where featured=’true’ and status=’active ‘
order by rand()
limit 1
Free download pdf