<?php
$tpags = ceil($rows / $nritems);
$pag = intval($_GET['pag']);

if ($pag && $pag > 0 && $pag <= $tpags) {
$start = ($pag - 1) * $nritems;
$end = $start + $nritems;
} else {
// if pag isn't set, show first set of results
$start = 0;  
$end = $nritems;
}
?>

<?php
function paginate($reload, $pag, $tpags) {
$adjacents = 6;
$prevlabel = "&lsaquo;";
$nextlabel = "&rsaquo;";
$out = "";

if ($pag <= 0 OR $pag =='') {
$pag = 1;
}	
// previous
	if ($pag > 1) {
$out.= "<li><a href=\"" . $reload . "&pag=" . ($pag - 1) . "\">" . $prevlabel . "</a>\n</li>";
} else {
$out.= "<li><span>" . $prevlabel . "</span>\n</li>";
}
	
// pages
$pmin = ($pag > $adjacents) ? ($pag - $adjacents) : 1;
$pmax = ($pag < ($tpags - $adjacents)) ? ($pag + $adjacents) : $tpags;
for ($i = $pmin; $i <= $pmax; $i++) {
if ($i == $pag) {
$out.= "<li><span class=\"active\">" . $i . "</span>\n</li>";
} elseif ($i == 1) {
$out.= "<li><a href=\"" . $reload . "\">" . $i . "</a>\n</li>";
} else {
$out.= "<li><a href=\"" . $reload . "&pag=" . $i . "\">" . $i . "</a>\n</li>";
}
}

// next
if ($pag < $tpags) {
$out.= "<li><a href=\"" . $reload . "&pag=" . ($pag + 1) . "\">" . $nextlabel ."</a>\n</li>";
} else {
$out.= "<li><span>" . $nextlabel . "</span>\n</li>";
}
$out.= "";
return $out;
}
?>