DELIMITER $$
CREATE PROCEDURE GetStudentsAndCount(IN start INT, IN offset INT)
BEGIN
-- First, select the students with LIMIT
SELECT * FROM student
LIMIT start, offset;
-- Then, select the total number of records
SELECT COUNT(*) AS total FROM student;
END$$
DELIMITER ;
This MySQL stored procedure, `GetStudentsAndCount`, accepts two input parameters, `start` and `offset`, for pagination:
require 'config.php'; // Database connection having $dbo
// Define pagination variables
$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;
// Call the merged stored procedure
$stmt = $dbo->prepare("CALL GetStudentsAndCount(:start, :limit)");
$stmt->bindParam(':start', $start, PDO::PARAM_INT);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
// Fetch the students
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Move to the next result set to get the total count
$stmt->nextRowset();
$total_records = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
$total_pages = ceil($total_records / $limit);
// Display records
foreach ($students as $student) {
echo $student['name'] . ' - ' . $student['class'] . '<br>';
}
// Pagination navigation
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
`$dbo`
object.`$limit`
defines records per page, and `$start`
calculates the starting point for fetching data based on the current page number.`GetStudentsAndCount`
, binding the parameters `:start` and `:limit` for pagination.Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.