如何对从数据库中获取的数据进行分页

时间:2016-07-31 07:33:59

标签: php mysql mysqli

假设第一页中有13条记录是最新的5或9-13, 从第二页的4-8和第三页的1-3

我已经尝试了这个,但仅限于第一页

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysqli_login";

// Create connection
$connection= new mysqli($servername, $username, $password, $dbname);
$query = mysqli_query($connection, "SELECT name,submittedby,trn_date FROM new_record ORDER BY id DESC LIMIT 5")or die(mysqli_error($connection));
while ($row = mysqli_fetch_array($query)) {
    $fileName = $row['name'];
    $fileContents = file_get_contents("txt/$fileName");
    $poster = $row['submittedby'];
    $date = $row['trn_date'];
    echo ("posted by :$poster  |  posted date : $date");
    echo ("$fileContents");
}
?>

2 个答案:

答案 0 :(得分:0)

Here's an article that discusses this topic。您需要根据当前页面来偏移查询。所以它将是LIMIT 5 OFFSET <amount based on the page>

答案 1 :(得分:0)

您的代码应该是这样的

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$connection= new mysqli($servername, $username, $password, $dbname);

$current_page = 1; // 1=>refer to the first page, 2=> second page and so on..
if(!empty($_GET['page_no']){
$current_page = $_GET['page_no'];
}

$to = "5"; // it is no of record which you wants to show on each page, you can change it's value as per your need.
$from = ($current_page - 1) * $to;


$query = mysqli_query($connection, "SELECT name,submittedby,trn_date FROM new_record ORDER BY id DESC LIMIT $from , $to")or die(mysqli_error($connection));
while ($row = mysqli_fetch_array($query)) {
    $fileName = $row['name'];
    $fileContents = file_get_contents("txt/$fileName");
    $poster = $row['submittedby'];
    $date = $row['trn_date'];
    echo ("posted by :$poster  |  posted date : $date");
    echo ("$fileContents");
}
?>

你的网址应该是http://localhost/projects/?page_no=1 替换&#34; http://localhost/projects/&#34;与您的实际网址

希望这会有所帮助!!