php mysql 下一个,php-mysql从数据库中获取下一个和上一个ID

I have the following table:

**id** **username** **activity**

1 user1 activity-like

2 user1 activity-share

3 user3 activity-like

4 user4 activity-like

5 user1 activity-share

6 user6 activity-like

8 user1 activity-share

9 user3 activity-like

10 user5 activity-share

(Note: there is no id = 7)

I am trying to use php-mysql to fetch the activity made by user1 and get the id. In this case the activities have the id (1, 2, 5, and 8).

$currentId = 5;

I want to get the next and previous ids if they exist (in this case 2 and 8).

$fetch = mysql_query("SELECT * FROM `main` WHERE `username` = 'user1' AND id > '$id'");

if(mysql_num_rows($fetch) == 1){

while (){

}

$result = $fetch['id'];

}

I am not sure how to write the query for that.

解决方案

You can do something like this:

For next id,

SELECT id from tablename where username = 'user1' AND id > $currentId ORDER BY ID ASC LIMIT 1;

For previous id,

SELECT id from tablename where username = 'user1' AND id < $currentId ORDER BY ID DESC LIMIT 1;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值