mysql结果编号在PHP中具有自定义分页

时间:2018-09-06 10:40:33

标签: php 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。我如何才能按顺序对结果进行编号?

1 个答案:

答案 0 :(得分:0)

除非我误解了,否则您自己解决不了吗? 为什么您不能像进行测试那样设置计数器?

为答案添加一点点, 所以我们需要设置一个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;?>