2015-09-28 46 views
0

此查詢從數據庫中提取結果,但有太多結果導致頁面掛起,有沒有辦法對結果進行分頁?如何分頁我從這個查詢中得到的結果?

<?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 ?> 
+0

您不應該這樣關閉PHP標籤,特別是因爲它一直是PHP代碼。 – fpietka

回答

0

如果您使用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 ?> 
0

沒有測試,你可以嘗試以下內容。

/* 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>"; 
    } 
} 
相關問題