繁体   English   中英

mysql 在 PHP 中使用自定义分页结果编号

[英]mysql results numbering in PHP with custom pagination

我在基本的自定义 MVC 设计中有 PHP 代码,旨在搜索 MySQL 数据库中的记录,然后在分页页面中返回/输出结果。 我的问题是第 1 页中的结果编号为 1 -20,以及第 2 页、第 3 页等中的结果。

理想情况下,第 2 页的结果应为 21-40,第 3 页的结果应为 41-60...等

这是控制器的代码片段

function getCitation() {
    $limit = 20;
    $currentpage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $start_from =((($currentpage*$limit)-$limit)+1);
    $term = isset($_GET['searchterm']) ? $_GET['searchterm'] : null;
    //if(isset($_GET['mysearch']))
    if(isset($_GET['search1']) && empty($term) && ($_GET['choice'] == 'title' || $_GET['choice'] == 'author')){
        header ('Location: ' . '../index');     
    }
    $this->view->getCitation = $this->model->getCitation($term,$start_from,$limit);
    //The line below is critical for pagination in view.
    $this->view->getPages = $this->model->getPages($term, $limit);
    $this->view->render('search/index');
 }

模型看起来像这样

public function getCitation($term, $start_from, $limit){
    $sth = $this->db->prepare("SELECT * FROM citations_new WHERE title 
        LIKE ? LIMIT {$start_from}, {$limit}");
    $sth->execute(array('%'.$term.'%'));
    return $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
}
public function getPages($term, $limit){
    echo $term;
    $sth = $this->db->prepare("SELECT Count(*) FROM citations_new WHERE title 
        LIKE ?");
    //echo 1;
    $sth->execute(array('%'.$term.'%'));
    $results = $sth->fetchColumn();
    $total_records = $results;
    return $total_pages = ceil($total_records/$limit);
}

视图如下所示:

$x=1;
while($row = array_shift($this->getCitation())){
    echo $x++;
    echo $row['title'] . '<br>';
}
for($i=1; $i<=$this->getPages; $i++):?>
    <a href="?searchterm=<?php echo $_GET['searchterm'].'&search1=Submit+Query&page=' . $i; ?>">
    <?php echo $i;?></a>
<?php endfor;?>

当我回显$start_from =((($currentpage*$limit)-$limit)+1); 在控制器上,我能够看到正确的 start_number。 我怎样才能让我的结果按顺序编号?

除非我误会了,这不是你自己解决的吗? 为什么你不能在测试时设置计数器?

添加一点答案,所以我们需要设置一个viewdata数组,向它添加正确的信息然后我们需要将计数器从控制器传递给视图

控制器:

$viewdata = array();
$viewdata['results'] = $this->model->getCitation($term,$start_from,$limit);
$viewdata['pagecounter'] = ((($currentpage*$limit)-$limit)+1);

$this->view->getCitation = $viewdata;

看法:

$viewdata = $this->getCitation();


    $x= $viewdata['pagecounter'];
    while($row = array_shift($viewdata['results'])){
        echo $x++;
        echo $row['title'] . '<br>';
    }
    for($i=1; $i<=$this->getPages; $i++):?>
        <a href="?searchterm=<?php echo $_GET['searchterm'].'&search1=Submit+Query&page=' . $i; ?>">
        <?php echo $i;?></a>
    <?php endfor;?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM