Skip to content
Advertisement

PHP get value of row field from inside of while loop

Suppose I have a table like this:

Table swipes

JavaScript

Based on which I have my setup like this:

JavaScript

As you can see right now I have ORDER BY swp_id DESC in first query which works fine. But when I try removing from 1st query and adding it in second query it doesn’t work. What I actually want to do is to get the time from the latest swipe.

As you can see in table given above for the 1st two rows with swp_id 1 & 2, Users 8 and 11 swiped user 1 first. Later, user 1 swiped users 8 & 11 as you can see in records with swp_id 3 & 4. Now, record 3 & 4 are the latest records. Hence, I want to fetch the swp_date from these records and not from 1 & 2. Right now, it’s returning date from records 1 and 2.

Advertisement

Answer

Suppose you want all the user_id’s and dates from users that swiped to user_id 1, but only if he(she) swiped that user too, and not to the left.

So extending your table a bit:

JavaScript

First part: select all the swipes from user 1 swp_by = 1 that are not left (the same as your first query):

JavaScript

Result 1:

JavaScript

Second part: find all the swipes “back” to user 1, so where swp_to = 1

JavaScript

Result 2:

JavaScript

Now you can cross reference the results finding the swp_to numbers from Result 1 (8, 11, 40) that have a swp_by in Result 2 (8, 11, 20). This can be done using a LEFT JOIN from the same table

JavaScript

Here’s a new fiddle *EDIT OP wanted latest date, adjusted with GREATEST for date

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement