Jump to content

'next' button


dachshund

Recommended Posts

I've tried asking this question on here in the past, but never worked it out fully, so apologies for posting the same Q twice, but here it is:

 

Basically what I'm trying to do is add 'next' and 'previous' buttons to all my articles.

 

The articles are just like any other site, like this article for example: http://www.nytimes.com/2010/03/09/health/policy/09health.html?hp

 

So what I want is a next button which will basically find the next biggest id, and take you to that page.

 

The address would be http://www.address.com/view_article.php?id=(next largest id)

 

I've tried id+1, but that doesn't work, because the id's are not all in order - the site is ordered by date.

 

If anyone could help it would be much appreciated. I hope that all makes sense.

Link to comment
https://forums.phpfreaks.com/topic/194553-next-button/
Share on other sites

Well, the only simplified way I know is using two queries. If you already have the ID of the current record, you can select the next biggest record.

 

<?php
// Select the next biggest record and limit it by 1 so only that record is returned
$sql = "SELECT * FROM some_tbl WHERE id > $current_id LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
  $nextid = mysql_result($result, 0);
}
?>

 

To select the previous one it's the reverse, so instead you find the lowest using

 

$sql = "SELECT * FROM some_tbl WHERE id < $current_id LIMIT 1";

 

Bear in mind that code is just an example, all of the variables used within the query should be sanitised and validated accordingly.

Link to comment
https://forums.phpfreaks.com/topic/194553-next-button/#findComment-1023485
Share on other sites

Would this work?

 

<?php
$id = ; // current article id
$sql = "SELECT id FROM articles ORDER BY id LIMIT $id, 2";
$query = mysqli_query($con, $sql);

while ($row = mysqli_fetch_assoc)
{$ids[] = $row['id'];
}

$next = "article.php?id={$ids['1']};
?>

 

The code might be a bit off mind you. Just thought I would give you an idea...

Link to comment
https://forums.phpfreaks.com/topic/194553-next-button/#findComment-1023487
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.