FYI - my preferred method is not to use links with query strings but to add a hidden "page" field to the search form. When the pagination buttons are clicked they update the hdiden field with their page number and resubmit the form.
Example (The table used is "pupil" table from my sql tutorial)
<?php
include 'db_inc.php'; // creates pdo connection
$pdo = pdoConnect('jointute'); // use your own
$searches_per_page = 5;
$search = $_GET['search'] ?? ''; // set defaukt values
$page = $_GET['page'] ?? 1; //
//
// Record count
//
$res = $pdo->prepare("SELECT COUNT(*) FROM pupil
WHERE lname LIKE ?
");
$res->execute(["%{$search}%"]);
$number_of_pages = ceil($res->fetchColumn()/$searches_per_page);
$prev = $page > 1 ? $page - 1 : 1;
$next = $page < $number_of_pages ? $page + 1 : $number_of_pages;
$start = max(1, $page - 2);
$end = min($number_of_pages, $page + 2);
//
// Get data for display
//
$res = $pdo->prepare("SELECT fname
, lname
, classid
, dob
, timestampdiff(YEAR, dob, CURDATE()) as age
FROM pupil
WHERE lname LIKE ?
ORDER BY lname, fname
LIMIT ?,?
");
$res->execute(["%{$search}%", ($page-1)*$searches_per_page, $searches_per_page ]);
$pupils = '';
foreach ($res as $row) {
$pupils .= "<tr><td>" . join("</td><td>", $row) . "</td></tr>" ;
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Search example</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
$().ready (function() {
$(".paging").click( function() {
let page = $(this).val()
$("#page").val(page) // set page no in hidden form field
$("#searchform").submit() // resubmit the form
})
})
</script>
<style type='text/css'>
body {
background-color: black;
color: white;
}
td , th {
padding: 4px;
}
</style>
</head>
<body>
<form id='searchform'>
Search for <input type='text' name='search' value="<?=$search?>">
<input type='hidden' name='page' id='page' value='<?=$page?>'>
<input type='submit' value='Search'>
</form>
<?php
if ($number_of_pages > 1) {
echo "<br><br><button class='paging' value='$prev'><</button> ";
for ($p = $start; $p <= $end; $p++) {
echo "<button class='paging' value='$p'>$p</button> ";
}
echo "<button class='paging' value='$next'>></button>";
}
?>
<br><br>
<table border='1'>
<tr><th>First Name</th><th>Last Name</th><th>Class</th><th>DOB</th><th>Student Age</th></tr>
<?=$pupils?>
</table>
</body>
</html>