I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance.

I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this:

```
if ($page > $no_of_paginations) {
 $page = $no_of_paginations;
}

```

However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query.

Any thoughts on how I can make this functional?

I'll post the pertinent code below:

```
<?php
$page = 0;
if(isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$cur_page = $page;
$page -= 1;
if((int) $_GET['imgs'] > 0){ 
    $per_page = (int) $_GET['imgs']; 
} else { 
    $per_page = 16; 
}
$start = $per_page * $page;

include"db.php";

$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";

$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());

echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) { 
    echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
  }
echo "</ul>";   

/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>

```

Thanks for your help!
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
You should use query:

```
$query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";

```

And instead of 

```
$query_pag_num = "SELECT COUNT(*) AS count FROM images";

```

use 

```
$query_pag_num = "SELECT FOUND_ROWS()";

```
If you do the "SELECT COUNT(\*) ..." query earlier in the script (at least before the other query), you will have $no\_of\_paginations earlier, and can use it to clamp $page to the correct range.