PHP MySQL结果num total rows和split for pages

时间:2013-12-01 13:08:35

标签: php mysql

有没有办法计算和拆分结果而不进行2次查询,

即时使用这样的查询:

$result = mysqli_query($con,"SELECT * from articles WHERE category = '$category'");

    $row = mysqli_fetch_row($result);
    $rows = $row[0];
    $page_rows = 20;
    $last = ceil($rows/$page_rows);
    $pagenum = 1;
    $limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;

    $result2 = mysqli_query($con,"SELECT * FROM articles order by id desc $limit");
    while($row = mysqli_fetch_array($result2)) {
    $id = $row['id'];
    }

这是有效的,但我不喜欢它有2个查询,更好的主意?谢谢

2 个答案:

答案 0 :(得分:0)

$pagenum = 1;
$rows_on_page = 20;
$start = (($pagenum - 1) * $rows_on_page);
$end = ($pagenum * $rows_on_page);
$result = mysqli_query($con, "SELECT * from articles WHERE category = '$category' ORDER BY id DESC LIMIT $start, $end");
while ($row = mysqli_fetch_array($con,$result) {
    ... do stuff with articles ...
    $pagenum++;
}

while循环可以防止你越过记录的末尾。

答案 1 :(得分:0)

尝试此查询,它将返回记录和分页的计数(查询中的标题是字段名称,根据您的表更改它):

SELECT aa.countt, title FROM articles , (SELECT COUNT(*) AS countt FROM articles WHERE category = '$category' ) AS aa ORDER BY id LIMIT 5,10