user2806214 user2806214 - 2 months ago 4
PHP Question

on last page next link vanishes and previous link never showed up start to end

I can not understand what i am not doing.

<?php
$sql = "SELECT COUNT(*) from customers";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$rows = $row[0];
$page_rows = 3;
$last = ceil($rows/$page_rows);
if($last<1) {
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])) {
$pagenum = preg_replace('#[^0-9]#','',$_GET['pn']);
}
if($pagenum<1) {
$pagenum=1;
} else
if($pagenum>$last) {
$pagenum = $last;
}

$start = ($pagenum-1)*$page_rows;
$end = $page_rows;
$textline ="page<b>$pagenum</b> of <b>$last</b>" ;
$paginationCtrl='';
if($last!=1) {
if($pagenum>1) {
// here i am giving the previous link to variable pagination.
$previous = $pagenum-1;
$paginationCtrl .= '<a href="'.$_SERVER['PHP_SELF'].'? pn='.$previous.'">Previous</a>&nbsp;&nbsp;';

//If i print this this variable then it shows it value.

for($i=$pagenum-4; $i<$pagenum; $i++) {
if($i>0) {
$paginationCtrl .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a>&nbsp;&nbsp;';
}
}
}
$paginationCtrl=''.$pagenum.'&nbsp;';
for($i=$pagenum+1; $i<=$last; $i++) {
$paginationCtrl .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a>&nbsp;&nbsp;';
if($i>=$pagenum+4) {
break;
}
}
if($pagenum!=$last) {
// Here i am defiinig next link which appeared untill the last page is clicked. if user is on last page it also disappeared.

$next = $pagenum+1;
$paginationCtrl .= '&nbsp;&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next</a>';
}
}
?>
<div class="box-body">
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
<?php
$sql2 = "SELECT * from customers order by customer_id DESC LIMIT $start,$end";
$query2 = mysql_query($sql2);
while($row = mysql_fetch_array($query2)) { ?>
<tr>
</tr>
<?php } ?>
<tr><td></td></tr>
</tbody>
</table>


Here it shows like 1 2 3 next and if i am on page 2. it shows like 3 next.

<div><?php echo $paginationCtrl; ?> </div>


if i have 3 pages total. and i am on page 2 the previous link is not appearing. and if i am on last page the next link also disappeared. and paginationctrl variable only showing page 3. no previous pages or links shown

Answer

on last page next link vanishes

Yes, but it is good. On last page, there is not a next page.

If you want show a not active “next” link you can change your code in something like this:

if( $pagenum!=$last )
{
    $next = $pagenum+1;
    $paginationCtrl .= '&nbsp;&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next</a>';
}
else
{
    $paginationCtrl .= '&nbsp;&nbsp;<div class="inactive">Next</div>';
}

previous link never showed up start to end

You have a typo. Replace this line:

$paginationCtrl=''.$pagenum.'&nbsp;';

with:

$paginationCtrl .= '' . $pagenum . '&nbsp;';