
Next and previous links in PHP, MySQL
If you see a WordPress site, you will notice that at the bottom of the blog listing page, there will be links to next and previous pages.
They are useful to move the user to next or previous page.
If user is at the last page, then the next button will not be displayed.
Similarly, if user is at the first page, then the previous button will be hidden.
We are achieve this in PHP and MySQL. Following is the code to do that:
<?php
// Create a new PDO connection to the MySQL database
$pdo = new PDO("mysql:host=localhost; dbname=test", "root", "root", [
PDO::ATTR_PERSISTENT => true // Enables persistent connection for better performance
]);
// Define the number of records to show per page
$per_page = 2;
// Get the current page number from the query string, default to 1 if not set
$page = $_GET["page"] ?? 1;
// Calculate the offset for the SQL query
$skip = ($page - 1) * $per_page;
// Fetch the users for the current page, ordered by ID in descending order
$sql = "SELECT * FROM users ORDER BY id DESC LIMIT $skip, $per_page";
$stmt = $pdo->prepare($sql); // Prepare the SQL statement
$stmt->execute([]); // Execute the query
$users = $stmt->fetchAll(PDO::FETCH_OBJ); // Fetch all results as objects
// Query to get the total number of users in the database
$sql = "SELECT COUNT(*) AS total_count FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
$total_count = $row->total_count ?? 0; // Get the total count or default to 0
// Calculate the total number of pages required
$total_pages = ceil($total_count / $per_page);
// Determine if there are more pages
$has_more_pages = ($page * $per_page) < $total_count;
// Initialize previous and next page variables
$previous_page = $next_page = null;
// Determine the previous page number
if ($page > 1)
{
$previous_page = $page - 1;
}
// Determine the next page number
if ($page < $total_pages)
{
$next_page = $page + 1;
}
?>
<!-- Loop through and display each user -->
<?php foreach ($users as $user): ?>
<p><?php echo $user->name; ?></p>
<?php endforeach; ?>
<!-- Pagination controls -->
<?php if ($next_page > 0): ?>
<a href="?page=<?php echo $next_page; ?>">Previous</a>
<?php endif; ?>
<?php if ($previous_page > 0): ?>
<a href="?page=<?php echo $previous_page; ?>">Next</a>
<?php endif; ?>
Comments has been added with each line for explanation.
Even if you are working in any other language like Node.js and MongoDB, you can still achieve this because now you have the algorithm to do that.
We implemented this technique in one of our project: Multi-purpose platform in Node.js and MongoDB
From there, you will get the idea how you can render next and previous links if you are working in Node.js and MongoDB as backend and React as frontend.