user3011784
user3011784

Reputation: 839

how to get next result from mysql in php (after certain ID)

I'm not sure how to manage this sql/php problem.

I have an sql query

SELECT * 
FROM   blogimage 
       INNER JOIN blog 
               ON blogimage.blog_id = blog.blog_id 
WHERE  blog.active = '1' 
ORDER  BY blog.date DESC, 
          blog.blog_id DESC, 
          blogimage.position ASC 

It gives me a list of results (say 100 result)

I want to say: IN THE ORDER described in the sql query above, find the blogimage_id = 1234 and give me the next blogimage_id result after that one.

Not sure if I'm explaining my question properly.

and how do I store that in a PHP variable?

Can that be done?

EXAMPLE RESULT OF MY QUERY

blogimage_id
2171
2162
2163
2170
2164

SO if I want to check blogimage_id = 2170, I need to get the result 2164. So adding WHERE blogimage_id > 2170 won't work...

Upvotes: 1

Views: 236

Answers (3)

UpVs
UpVs

Reputation: 1958

1. If you have not just id of the item, but also blog.date and blogimage.position, then you can use this query:

SELECT
    * 
FROM
    blogimage INNER JOIN blog USING(blog_id)
WHERE
    blog.active = '1' 
    AND blog.date <= :date 
    AND blog.blog_id < :id 
    AND blogimage.position < :position
ORDER BY 
    blog.date DESC, 
    blog.blog_id DESC, 
    blogimage.position ASC
LIMIT 1

:date - a date of the item
:id - its ID
:position - blogimage.position

2. If you don't, then you need retrieve all the IDs in the same order from the table first:

SELECT
    blog_id
FROM
    blogimage INNER JOIN blog USING(blog_id)
WHERE
    blog.active = '1'
ORDER BY 
    blog.date DESC, 
    blog.blog_id DESC, 
    blogimage.position ASC

This query should be very fast, because it uses primary key.

And then programmatically get the ID you need:

$ids = array_column('blog_id', $result); // $result - the result of the query above
$key = array_search($id, $ids); // $id - the given ID
if (false !== $key && array_key_exists($key+1, $ids)) {
    $idYouNeed = $ids[$key+1]; // this is what you want
} else {
    $idYouNeed = null; // there is no given ID in the table or it's the last one
}

Upvotes: 2

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48177

SELECT * 
FROM   blogimage 
       INNER JOIN blog 
               ON blogimage.blog_id = blog.blog_id 
WHERE  blog.active = '1' 
  AND  blogimage_id > 1234
ORDER  BY blog.date DESC, 
          blog.blog_id DESC, 
          blogimage.position ASC 
limit 1,1

Upvotes: 0

arpan.r
arpan.r

Reputation: 1981

if i understand your question properly you need to limit your sql to give you the second record? to achieve that you need to add limit clause

select * from blogimage INNER JOIN blog ON blogimage.blog_id = blog.blog_id WHERE blog.active = '1' order by blog.date DESC, blog.blog_id DESC, blogimage.position ASC limit 1,1

Upvotes: 0

Related Questions