user3788874
user3788874

Reputation: 67

Previous and next row in PHP

I have a table in phpmyadmin with a 'val' column and a 'num' column. These two columns have numbers ranging from 0 to 10. Using PHP I want to access this table in phpmyadmin and when my 'val' = 10, I want to get the 'num' value that is immediately before and after that 'val' = 10 value. So in the image I want to get when val = 10, the num = 9 and 4, and for the second val = 10, num = 4 and 10.

$s = $mysqli->query("SELECT `Num` FROM `user_entries` WHERE `Val` = 10");

I wasn't sure what to add next as I haven't found any function that is able to do this. How can I do this?

This is a smaller sample of the table I am using

Upvotes: 0

Views: 163

Answers (2)

Meeuuuhhhh
Meeuuuhhhh

Reputation: 388

I'm not sure you can do this the way your table is (you actually might be able to do so in PHP, but that could work how you want it one day, but not the day after .. (see this link)).

I would recommend to had a column, id or sort, depending on what you need, who would look like :

id  Val     Num
1   2       6
2   0       0
3   4       8
4   3       9
5   10      1
6   8       4
7   10      6
8   5       10

With this, i would recommend using MySQL to get what you want :

SELECT 
IFNULL((SELECT f2.Num FROM user_entries f2 WHERE f2.id = f.id-1),-1) AS previous_Val,
IFNULL((SELECT f2.Num FROM user_entries f2 WHERE f2.id = f.id+1),-1) AS next_Val
FROM user_entries f
WHERE Val = 10    
ORDER BY id 

This would return :

previous_Val    next_Val
9               4
4               10

In the case there is no previous_Val or next_Val, it would return -1.

You might need to see how you can use this, hope it helps.

Upvotes: 1

Bushra Shahid
Bushra Shahid

Reputation: 781

Your Query should be like this

"SELECT `Num` FROM `user_entries` WHERE `Val` = '10' ";

Upvotes: 0

Related Questions