Skip to content

Instantly share code, notes, and snippets.

@tinshade
Created October 17, 2020 09:09
Show Gist options
  • Save tinshade/4dccd2384e716c7b96ad78a4d43f8fe9 to your computer and use it in GitHub Desktop.
Save tinshade/4dccd2384e716c7b96ad78a4d43f8fe9 to your computer and use it in GitHub Desktop.
Simple pagination boilerplate using PHP and MySQL Database.
<html>
<head>
<title> Pagination </title>
</head>
<body>
<?php
//database connection
$conn = mysqli_connect('localhost', 'root', '', 'db_name');
if (! $conn) {
die("Connection failed" . mysqli_connect_error());
}
else {
mysqli_select_db($conn, 'pagination');
}
//define total number of results you want per page
$results_per_page = 2;
//find the total number of results stored in the database
$query = "select * from table_name";
$result = mysqli_query($conn, $query);
$number_of_result = mysqli_num_rows($result);
//determine the total number of pages available
$number_of_page = ceil ($number_of_result / $results_per_page);
//determine which page number visitor is currently on
if (!isset ($_GET['page']) ) {
$page = 1;
} else {
$page = $_GET['page'];
}
//determine the sql LIMIT starting number for the results on the displaying page
$page_first_result = ($page-1) * $results_per_page;
//retrieve the selected results from database
$query = "SELECT * FROM table_name LIMIT " . $page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $query);
//display the retrieved result on the webpage
while ($row = mysqli_fetch_array($result)) {
echo $row['id'] . ' ' . $row['index_name'] . '</br>';
}
//display the link of the pages in URL
for($page = 1; $page<= $number_of_page; $page++) {
echo '<a href = "pagination.php?page=' . $page . '">' . $page . ' </a>';
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment