Question

I know this sounds confusing: I have just built some basic prev/next pagination for mysql and i wanted to know, if the last page of my rows is .php?page=5 and someone puts .php?page=263 then i want to redirect them to .php?page=5

Any ideas on how to do this.. the info i currently have is, how many rows are returned after the LIMIT so if it was .php?page=263 then it would be 0 I also have the total number of rows in my database... the LIMIT is 10 :)

Thanks in advance!!

Was it helpful?

Solution

If you already have the total number of rows, and you know how many rows you will be displaying per page, then you can calculate the last page like so:

$totalPages = ceil( $rows / $perPage );

Then, simply restrict the current page to a reasonable limit:

$page = isset( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$page = min( max( $page, 1 ), $totalPages );

OTHER TIPS

The easiest thing to do is define some form of $max_page_number variable, then check that the page entered $_GET['page'] is either less than the maximum possible number, or, if not, compensate for that and redirect to the last page:

$max_page_number = 10; // or whatever the maximum/last page number is, $page_requested = $_GET['page'];

if ($page_requested <= $max_page_number) {

// show the page requested by the user
}

elseif ($page_requested > $max_page_number) {

// redirect to the relevant page

}

else {

// redirect to the splash page, or first page

}

it's also worth suggesting that you should check people can't enter index.php?page=-10 without it being caught, so you should really check for numbers less than the first page and greater than your last page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top