Welcome to WebmasterWorld Guest from 50.16.112.199

Forum Moderators: coopster & jatar k

increment id number for next/prev links

   
6:17 pm on Mar 7, 2013 (gmt 0)

10+ Year Member



I've got a mysql table with an auto incremented ID field in it. When I loop for output to the page, I start the output for each iteration with the following so I can refer back to it via an anchor in the url:


// after query and while loop
<a name="'.$row['id'].'"></a>


What I'd like to do is to have a next/prev style link in each iteration that grab the $id, increments it by one and parses a link, if there is a next or prev $id, something like this:


// query then loop
while ($row = mysql_fetch_array($result)) {

// increment $id to create var for NEXT link
$n = intval($row['id']);
$next = $n++;

// decrement $id to create var for PREV link
$p = intval($row['id']);
$prev = $p--;

// output PREV link
if($prev > intval($row['id'])) {
echo '<a href="page.php#'.$prev.'">Previous</a> | ';
} else {
echo 'Previous | ';
}

// output NEXT link
if($next < intval($row['id'])) {
echo '<a href="page.php#'.$next.'">Next</a>'.PHP_EOL;
} else {
echo 'Next'.PHP_EOL;
}


But using the above returns nothing. Can someone point me in the right direction?

Thanks in advance!
6:25 pm on Mar 8, 2013 (gmt 0)

5+ Year Member



First problem, as you said "with an auto incremented ID" so what happens if you delete some records in your table? You'll get no result. So the thing you should do in your loop is to get the previous and next id with a query with the current id. Just like that :

Previous row :

SELECT id
FROM yourTableName
WHERE id < $row["id"]
ORDER BY id DESC
LIMIT 1

Next row :

SELECT id
FROM yourTableName
WHERE id > $row["id"]
ORDER BY id ASC
LIMIT 1


This way you'll be sure to get the REAL previous and next id ;)
10:15 pm on Mar 8, 2013 (gmt 0)

10+ Year Member



Good call, I hadn't thought of that. Just trying to cheat my way through a pagination type of setup without going crazy with the PHP. I'll definitely be implementing something like that into my query. Thanks!
10:24 pm on Mar 8, 2013 (gmt 0)

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



Is page.php#44 really the URL?

I can recommend starting the link with a leading slash.

At the first page will you grey out "previous"?
At the last page will you grey out "next"?
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month