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

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

问题描述:

lets say if there are 13 records the latest 5 or from 9-13 in the first page, from 4-8 in second page and 1-3 in the third page

i've tried this but its for the first page only

<?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");
}
?>

Your code should be like this

<?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");
}
?>

your url should be something like http://localhost/projects/?page_no=1 replace "http://localhost/projects/" with your actual url

Hope this will help!!

Here's an article that discusses this topic. You need to offset your query based on the current page. So it will be LIMIT 5 OFFSET <amount based on the page>.