php - 分页器类

标签 php mysql pagination smarty

大家。我正在一个使用 php 和 mysql 数据库的 smarty 模板网站上工作。 这是一个比我的第一个问题更具体的问题,第一个问题询问如何将方法传递给类。我认为重新打包问题比编辑旧问题更容易。

我为我的图片库编写了一个分页器脚本,它在页面上显示图像。如果用户选择了一个类别,则仅显示特定类别中的图像,并且结果总是分页的。 脚本如下所示。

$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);

}

该脚本调用我的数据库类中的两个方法: $db->num_images_gallery 看起来像这样:

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;  
}

和方法 $db::get_images_gallery() 如下所示:

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;
    }

我现在想创建一个名为 paginate 的类,并将此脚本放入其中,以便我可以分页显示我的网站产品。 主要问题是我需要使用不同的函数来获取产品表中的产品数量,然后返回分页结果。我如何将上面的脚本转换为一个类,在其中我可以更改所使用的函数。我几乎在我的 previous question 上得到了答案,但问题不够具体。 谢谢 安德鲁

最佳答案

有一个用于分页的 Smarty 插件。

您可以在这里找到它:http://www.phpinsider.com/php/code/SmartyPaginate/

从链接页面中提取的简单示例:

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}

关于混合 DB 类和 Paginator 类的问题,没关系:
您的数据库类将处理从数据库获取数据
SmartyPaginate 类将处理分页
你的index.php只需在适当的地方调用每一个来设置事情。

这个想法是为了保持职责隔离。
您的数据库类不会处理分页,您的分页类也不会包含数据库代码。

从您的其他问题来看,我认为您正在尝试为当前的问题做一些过于复杂的事情。

我建议您将所有与数据库相关的代码移至数据库处理类内部和 index.php 外部

例如:

$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

这是数据库逻辑,它生成(部分)SQL 字符串,因此请将其移动。
它取决于 2 个参数,因此请找到一种方法来使它们可用。
在这种情况下,我建议仅将两者作为参数传递。

而不是:

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

用途:

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

此外,您的分页器导航规则应该位于您的分页器类内。

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);

}

在这种情况下,我希望附加组件能够自动为您处理。

然后,您可以将整个 block 移动,该 block 将执行获取和准备图像数据的所有逻辑到一个函数(如果有的话,在您的 ImageGalery 类中)

$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++;
}

最后,在你的index.php上,你所要做的就是:
验证您收到的参数
调用您的 ImageGalery 类来获取图库数据(传递所需的参数)
调用您的 Pagination 类来进行分页(设置导航链接等)
设置您需要的Smarty模板变量
并显示它。

仍有很大的改进空间,但我希望这几个步骤能够帮助您的图像画廊代码更加清晰。

关于php - 分页器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736397/

相关文章:

php - CakePHP - 如何将页面标题设置为项目名称?

使用最近邻插值调整 PHP 图像大小?

mysql - AVG 返回 null 但不应返回 null

php - 如何在 Laravel 中链接数据库关系(多个 has_many?)

php - 显示中间行包含变量的查询中的 11 个连续行

mongodb - Spring数据mongo分页

php - 处理 URL 参数 - 以斜杠分隔的名称值对

php检测文档索引是否为localhost

php - 通过 PDO 查询将 MySQL 数据库的每一行存储在一个对象中?

mysql - Laravel3 group_by + sum + 分页?