I can't shorten it, but it looks like this line is wrong:
$pages=mysql_num_rows($total)%5;
The modulo operator will give you the remainder after the division (for positive numbers anyway), it looks like you want the integer quotient (use either the floor() or ceil() function). Just happens to work right with 6 rows (quotient=1, remainder=1).