简体   繁体   中英

Call the next and previous records in a MySQL query

How do I call the next and previous MySQL records, without referring to the ID?

In my table, I have the following records:

  • IDNO (Auto-increment, primary key)
  • Title
  • Slug (unique key)
  • Data
  • DateTime (Ymd H:i:s)

I have two pages - index.php and single.php. In index.php, my posts are called (10 at a time) and ordered by DateTime . Each entry links to single.php, where the single post is displayed, based on the URL variable slug and calling the appropriate record in my database. I would like, since the pages are making up a simple blog, to call the next post and the previous post, still in DateTime order (the next will link to the more recent post, the previous link to the less recent post). Any advice on how to do this? If it was based on IDNO, I could do it, but since it isn't and the posts are not naturally in DateTime order, but are ordered as such in my query, I am at a loss.

The query I use on each single.php page is:

SELECT * FROM site_posts WHERE slug = '".$_GET['SLUG']."'

I want the links to appear on this page, so I am only including that query.

For the next post

SELECT * FROM site_posts WHERE DateTime > $currentPostDateTime   
  ORDER BY DateTime ASC LIMIT 0,1  

and
for the previous post

SELECT * FROM site_posts WHERE DateTime < $currentPostDateTime   
  ORDER BY DateTime DESC LIMIT 0,1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM