I'm trying to create a pagination where the selected page is at the center (if possible). However my code does not work. Below the image shows the output when selecting different pages.

In the first 2 page it works well, however problem starts when clicked on page 6, it shows page 8 however only 7 pages exist. When clicked on page 7 the page 7 marks also vanishes.
In the middle 2 pages the selected page no appears in the middle, which is correct however.
<?php
include 'backend_connection.php';
$sql = "SELECT count(`id`) FROM `activity`";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$totalRows = $row[0];
$page_rows = 5;
$lastPage = ceil($totalRows/$page_rows);
if($lastPage < 1){
$lastPage = 1;
}
if(isset($_GET['page_no'])){
$currPage = preg_replace('[^0-9]', '', $_GET['page_no']);
} else {
$currPage = 1;
}
if ($currPage < 1) {
$currPage = 1;
} else if ($currPage > $lastPage) {
$currPage = $lastPage;
}
$limit = 'LIMIT ' .($currPage - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT `id`, `name` FROM `activity` ORDER BY name $limit";
$query = mysqli_query($con, $sql);
$paginationCtrls = '';
if($lastPage != 1){
if ($lastPage>1 && $lastPage<5) {
for($i=1;$i<=$lastPage;$i++) {
if ($i==$currPage)
$paginationCtrls .= '<a href="#"><b>'.$i.'</b></a> ';
else
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?page_no='.$i.'">'.$i.'</a> ';
}
} else {
if ($currPage>3)
$firstPage=$currPage-2;
else
$firstPage=1;
$endPage=$firstPage+5;
if ($currPage>$lastPage-1) {
$firstPage=$currPage-5;
$endPage=$lastPage;
}
for($i=$firstPage;$i<$endPage;$i++) {
if ($i==$currPage)
$paginationCtrls .= '<b><a href="#">'.$i.'</a></b> ';
else
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?page_no='.$i.'">'.$i.'</a> ';
}
}
}
$list = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$name = $row["name"];
$list .= '<p><a href="details.php?id='.$id.'">'.$name.'</p>';
}
mysqli_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#pagination_controls { font-size:21px; }
div#pagination_controls > a{ color:#06F; min-width: 70px; }
div#pagination_controls > a:visited{ color:#06F; min-width: 70px;}
</style>
</head>
<body>
<div>
<h2><?php echo 'Total rows '.$totalRows; ?></h2>
<p><?php echo 'Pages '.$currPage.' of '.$lastPage; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>