Welcome to WebmasterWorld Guest from 54.147.134.218

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

increment id number for next/prev links

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

Junior Member

10+ Year Member

joined:Apr 24, 2004
posts: 127
votes: 0


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)

Junior Member

5+ Year Member

joined:Nov 16, 2008
posts: 136
votes: 0


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)

Junior Member

10+ Year Member

joined:Apr 24, 2004
posts: 127
votes: 0


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)

Senior Member

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

joined:July 3, 2002
posts:18903
votes: 0


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"?
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members