【发布时间】:2018-09-10 03:41:00
【问题描述】:
我在基本的自定义 MVC 设计中有 PHP 代码,旨在搜索 MySQL 数据库中的记录,然后在分页页面中返回/输出结果。我的问题是第 1 页中的结果编号为 1 -20 以及第 2 页、第 3 页等中的结果。
理想情况下,第 2 页的结果应该是 21-40,第 3 页的结果应该是 41-60...等等
这里是控制器的代码sn-p
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。如何让我的结果按顺序编号?
【问题讨论】:
-
在你的sql语句中添加
ORDER BY? -
@Dale 我添加了
ORDER BY ID DESC,但没有任何改变 -
code igniter 提供了分页库,所以请使用它
标签: php pagination