[英]How do I paginate the results I get from this query?
该查询正在从数据库中提取结果,但是有太多结果导致页面挂起,是否可以对结果进行分页?
<?php $results = $wpdb->get_results("SELECT * FROM ns_light WHERE donation_id != 0 AND light_date BETWEEN '2015-02-01' AND '2016-01-31' ORDER BY light_date DESC", OBJECT) ?>
<?php foreach ( $results as $l ) : ?>
<?php include('single-light-loop.php') ?>
<?php endforeach ?>
如果您使用的是MYSQL,则非常简单。
<?php
$pag = $_GET['p'];
$limit = 10; // how many rows per page?
$pag *= $limit
if(empty($pag)){$pag=1}
?>
<?php $results = $wpdb->get_results("SELECT * FROM ns_light WHERE donation_id != 0 AND light_date BETWEEN '2015-02-01' AND '2016-01-31' ORDER BY light_date DESC LIMIT ".$pag.",".$limit, OBJECT) ?>
<?php foreach ( $results as $l ) : ?>
<?php include('single-light-loop.php') ?>
<?php endforeach ?>
如果不进行测试,则可以按照以下方式尝试一些操作。
/* Number of records per page */
$maxRows=10;
/* The total number of expected rows: uses db result 'dbrecordcount' */
$totalRows=$db->dbrecordcount;
/* Current page within paged results: retrieve `page` from querystring if using GET method */
$pageNumber=$_GET['page'];
/* How many pages of results are there */
$totalPages=( $maxRows > 0 ) ? abs( ceil( $totalRows / $maxRows ) - 1 ) : 0;
/* Where does paging begin */
$startRow=$pageNumber * $maxRows;
$sql="select
( select count(*) from `ns_light` where `donation_id` != 0 and `light_date` between '2015-02-01' and '2016-01-31' ) as 'dbrecords',
* from `ns_light`
where `donation_id` != 0 and `light_date` between '2015-02-01' and '2016-01-31'
order by `light_date` desc
limit $startRow, $maxRows;"
/* Display pagination links if there are sufficient number of records */
if( $totalPages > 0 && $totalRows > $maxRows ){
/* First record link */
if( $pageNumber==0 ) {
echo "First";
} else {
echo "<a href='?page=0'>First</a>";
}
/* Previous record link */
if( $pageNumber > 0 ){
echo "<a href='?page=".max( 0, $pageNumber - 1 )."'>Previous</a>";
} else {
echo "Previous";
}
/* Next record link */
if( ( $pageNumber + 1 ) > $totalPages ){
echo 'Next';
} else {
echo "<a href='?page=".min( $totalPages, $pageNumber + 1 )."'>Next</a>";
}
/* Last record link */
if( $pageNumber==$totalPages ){
echo 'Last';
} else {
echo "<a href='?page=".$totalPages."'>Last</a>";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.