tags:

views:

64

answers:

2

I have a database containing 40 pictures. These pictures are displayed using a pager.

I have a URL query: http://www.test.com/photo.php?id=15. This sets the current picture ID to 15. This picture is the 5th one on page 2.

How can I get the page a picture is on given only the ID?

SQL

select * from photo limit 40

PHP

$i=1;
while($r){
if($r[id]=$id) $cur_picRank = $i;
$i++;
} 
$curPage = ceil( $cur_picRank / $pagesize);

Is this correct?

A: 

You can't, for most cases ID cannot be quaranteed to be a perfect sequence.

But if you can make sure that the ID on your case is a perfect sequence.

page number can be found by ceiling

$page = ceil( $id / $pagesize);
Erwin
+1  A: 

Easy-peasy.
You just have to count pictures shown before.
if them ordered by id, just SELECT count(*) where id < $id
So, you will get a position and now can divide it by page size.
For the different ordering you have to get field value first (e.g. to order by name get a name by id and then use it in condition)

As for your approach, it is NOT correct. Selecting whole table to get just ONE row is always BAD idea.
Though this code would not work anyway. There is no loop exit condition and a counter doesn't count

Col. Shrapnel
Wow.great idea..thank you..
BRAVO