doulaozhi6835 2014-04-15 10:38
浏览 11
已采纳

使用SQL和PHP获取下一篇文章

I've made a very rough and basic CMS as a learning exercise. My next challenge is to create a pagination (next post, previous post).

Ideally, I need to get the next post, if post_status is set to published.

At the moment I get a post like so:

SELECT post_title, post_content, post_id, post_status FROM posts WHERE post_id='$id' AND post_status='published'

In my mind, I would increment the $id on the PHP side, like $id++. So if I'm on post_id=19, I try and get post_id=20. However, what happens if that post is not set to published — how do I get the next entry, WHERE post_status='published'? This could be 21, 23, etc.

  • 写回答

2条回答 默认 最新

  • drcrc28428 2014-04-15 10:43
    关注

    You can do this way, say you have an

    $id = 19;
    
    
    SELECT post_title,
    post_content, 
    post_id, 
    post_status 
    FROM posts 
    WHERE post_status='published'
    AND post_id > '$id' 
    order by post_id
    LIMIT 1
    

    This will check posts having id > 19 with post_status='published' and then get the next to 19 by ordering and limit 1

    UPDATE As danielsmile commented on getting the previous one for getting last one before $id = 19; would be pretty same as above

    SELECT post_title,
        post_content, 
        post_id, 
        post_status 
        FROM posts 
        WHERE post_status='published'
        AND post_id < '$id' 
        order by post_id DESC
        LIMIT 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100