views:

288

answers:

1

Hi,everyone. I am working on a site with smarty templates using php and a mysql database. This is a more specific question than my first one which asked how to pass methods to a class. I thought it would be easier to repackage the question than edit the old one.

I have written a paginator script for my image gallery which displays images on the page. If a user has selected a category then only images in a particular category are shown and the results are always paginated. The script is shown below.

$page_num = (isset($_GET['page_num']))?$_GET['page_num']:1;   //if $_GET['page_num'] is set then assign to var  $page_num. Otherwise set $page_num = 1 for first page
$category = (isset($_GET['req1']))?$_GET['req1']:'null';        //if $_GET['req1'] is set assign to $category other set $category to null

$items_pp = 5;
$total = $db->num_images_gallery($category);     //returns the number of records in total('null') or in a particular category('category_name')
$pages_required = ceil($total/$items_pp);  //total records / records to display per page rounded up
if($page_num > $pages_required){//in case the current page number is greater that the pages required then set it to the amount of pages required
    $page_num = $pages_required;
}
if($page_num < 1){//in case the current page num is set to less that one set it back to 1
    $page_num = 1;
}
$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14
$result = $db->get_images_gallery($category,$limit);

$i = 0;
while($row = $result->fetch_assoc()){
    $images[$i]['file']         =$row['file'];
    $images[$i]['file_thumb']   = str_replace('.','_thumbnail.',$row['file']);//show the thumbnail version of the image on the page
    $images[$i]['title']        = $row['title'];
    $images[$i]['description']  = $row['description'];
    $i++;
}
if(!empty($images)){
$smarty->assign('images',$images);}else{
$smarty->assign('message',"There are no images to display in the ".ucwords(str_replace('_',' ',$category))." category");}

if($total > 0 && $pages_required >= 1){//only display this navigation if there are images to display and more than one page

    $smarty->assign('page_scroll',$page_num . ' of ' . $pages_required);
    $page_scroll_first = "<a href='".$_SERVER['REDIRECT_URL'] . "?page_num=1"."' >FIRST</a> <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=" . ($page_num-1)."' >&lt;&lt;PREVIOUS</a>";
    $page_scroll_last =  " <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=". ($page_num+1) . "'>NEXT&gt;&gt;</a> <a href='" . $_SERVER['REDIRECT_URL'] . "?page_num=".$pages_required."'>LAST</a>";
    if($page_num == 1){$page_scroll_first = "FIRST &lt;&lt;PREVIOUS";}
    if($page_num == $pages_required){$page_scroll_last = "NEXT&gt;&gt; LAST";}
    $smarty->assign('page_scroll_first',$page_scroll_first);//just use if statements to set the values for page scroll first and page scroll last and then assign them here
    $smarty->assign('page_scroll_last',$page_scroll_last);
    $smarty->assign('page_num',$page_num);

}

The script calls on two methods from my database class: $db->num_images_gallery which looks like this:

function num_images_gallery($cat='null'){

 $query = ($cat == 'null')?
 "SELECT COUNT(*) AS images FROM images
 LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
 WHERE images.gallery='1' AND image_categories.gallery = '1'"//no images should be shown in a category which is not intended to be shown at all
 :
 "SELECT COUNT(*) AS images FROM images
 LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
 WHERE category = '{$cat}'
 AND images.gallery='1' AND image_categories.gallery = '1'";

 $result = $this->connection->query('SELECT COUNT(*) AS images FROM (?)',$x);
 $row = $result->fetch_assoc();
 $row_count = $row['images'];
 echo $row_count;
 return $row_count; 
}

and the method $db::get_images_gallery() which looks like this:

function get_images_gallery($category,$limit){
    $query = ($category=='null')?
     "SELECT `file`,title,images.description,sizes,images.gallery,category FROM images
     LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id) WHERE images.gallery='1' AND image_categories.gallery = '1' {$limit}"
     :
     "SELECT `file`,title,images.description,sizes,images.gallery,category FROM images
     LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
     WHERE category = '{$category}' AND images.gallery='1' AND image_categories.gallery = '1' {$limit}";
     $result = $this->connection->query($query);
     return $result;
    }

I now want to create a class called paginate and put this script in it so i can display my site products paginated. The main problem is that i need to use different functions to get the num of prodducts in my product table and then return the paginated results. How do i turn the script above into a class where i can change the functions which are used. I almost got an answer on my previous question, but the question was not specific enough. Thanks andrew

+1  A: 

There's a Smarty Add-On for pagination.

You can find it here: http://www.phpinsider.com/php/code/SmartyPaginate/

For a quick example, extracted from the linked page:

index.php

session_start();
require('Smarty.class.php');
require('SmartyPaginate.class.php');

$smarty =& new Smarty;

// required connect
SmartyPaginate::connect();
// set items per page
SmartyPaginate::setLimit(25);

// assign your db results to the template
$smarty->assign('results', get_db_results());
// assign {$paginate} var
SmartyPaginate::assign($smarty);
// display results
$smarty->display('index.tpl');

function get_db_results() {
    // normally you would have an SQL query here,
    // for this example we fabricate a 100 item array
    // (emulating a table with 100 records)
    // and slice out our pagination range
    // (emulating a LIMIT X,Y MySQL clause)
    $_data = range(1,100);
    SmartyPaginate::setTotal(count($_data));
    return array_slice($_data, SmartyPaginate::getCurrentIndex(),
        SmartyPaginate::getLimit());
}

index.tpl

{* display pagination header *}
Items {$paginate.first}-{$paginate.last} out of {$paginate.total} displayed.

{* display results *}    
{section name=res loop=$results}
    {$results[res]}
{/section}

{* display pagination info *}
{paginate_prev} {paginate_middle} {paginate_next}

Regarding your question about mixing the DB class and the Paginator class, it's all ok:
Your DB class will handle fetching data from DB
The SmartyPaginate class will handle the pagination
And your index.php just make the calls to each one where appropriate to set things out.

The idea is to keep responsibilities isolated.
Your DB class won't handle pagination, nor will your pagination class contain DB code.

From your other question, I think you were trying to do something too much convoluted for the problem at hand.

I'd suggest you to move all code that is DB-related inside your DB handling class and outside your index.php

This, for example:

$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14

This is DB logic, it generates (part of) an SQL string, so move it around.
It depends on 2 parameters, so find a way to get them available.
In this case, I'd suggest just passing both as parameters.

Instead of:

$result = $db->get_images_gallery($category,$limit);

Use:

$result = $db->get_images_gallery($category,$no_items, $page);

Also, your pager navigation rule should be inside your paginator class..

if($total > 0 && $pages_required >= 1){//only display this navigation if there are images to display and more than one page

    $smarty->assign('page_scroll',$page_num . ' of ' . $pages_required);
    $page_scroll_first = "<a href='".$_SERVER['REDIRECT_URL'] . "?page_num=1"."' >FIRST</a> <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=" . ($page_num-1)."' >&lt;&lt;PREVIOUS</a>";
    $page_scroll_last =  " <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=". ($page_num+1) . "'>NEXT&gt;&gt;</a> <a href='" . $_SERVER['REDIRECT_URL'] . "?page_num=".$pages_required."'>LAST</a>";
    if($page_num == 1){$page_scroll_first = "FIRST &lt;&lt;PREVIOUS";}
    if($page_num == $pages_required){$page_scroll_last = "NEXT&gt;&gt; LAST";}
    $smarty->assign('page_scroll_first',$page_scroll_first);//just use if statements to set the values for page scroll first and page scroll last and then assign them here
    $smarty->assign('page_scroll_last',$page_scroll_last);
    $smarty->assign('page_num',$page_num);

}

In this case, I hope the Add-On will handle it automatically for you.

You could then move this whole block, which does all your logic for fetching and preparing images data to a function (inside your ImageGalery class if you have one)

$total = $db->num_images_gallery($category);     //returns the number of records in total('null') or in a particular category('category_name')
$pages_required = ceil($total/$items_pp);  //total records / records to display per page rounded up
if($page_num > $pages_required){//in case the current page number is greater that the pages required then set it to the amount of pages required
    $page_num = $pages_required;
}
if($page_num < 1){//in case the current page num is set to less that one set it back to 1
    $page_num = 1;
}
$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14
$result = $db->get_images_gallery($category,$limit);

$i = 0;
while($row = $result->fetch_assoc()){
    $images[$i]['file']         =$row['file'];
    $images[$i]['file_thumb']   = str_replace('.','_thumbnail.',$row['file']);//show the thumbnail version of the image on the page
    $images[$i]['title']        = $row['title'];
    $images[$i]['description']  = $row['description'];
    $i++;
}

Finally, on your index.php, all you have to do is:
Validate the parameters you received
Call your ImageGalery class to fetch the galery data (pass the parameters it needs)
Call your Pagination class to do the pagination (setting up navigation links, etc)
Set the Smarty template variables you need
And display it.

There is still lots of room for improvement, but I hope those few steps will help get your Image Galery code more clear.

Carlos Lima
damn i've spent so long on this pagination stuff i wish i had known there was a smarty add on which could hadle it.
andrew
Heh. If you'd googled for 'smarty pagination' or 'php pagination' that'd be right on the first results :P Anyway, I hope my answer helped. Not only on the pagination add-on but on the general re-structuring tips.
Carlos Lima
Also, don't forget to go back on your questions and give up-votes to those answers that helped you, as well as marking an accepted answer if you found one to solve your problem or which explains it better.
Carlos Lima