Good afternoon, we have a table with news id | 5 | 7 | 15 | 20 | : id | 5 | 7 | 15 | 20 | id | 5 | 7 | 15 | 20 |

And request:

 $query = "select * from articleviews order by articleid desc limit 1"; $results = mysql_query($query,$connection) or die(mysql_error()); $lastid = mysql_fetch_array($results); //Previous link $previousid = $_GET['id']-1; if ($previousid < 1) { $previous = ""; } else { $previous = '/article.php?id='.$previousid; } //Next link $nextid = $_GET['id']+1; if ($nextid > $lastid['id']) { $next = ""; } else { $next = '/article.php?id='.$nextid; } 

But in the end, only the id from the open news is inserted into the link. For example, on news with id 15, the previous link will be on news with id 14, not 7. Help to bring existing id to news.

    3 answers 3

     select (select id from articleviews where id < ? order by id desc limit 1) as prev, (select id from articleviews where id > ? order by id limit 1) as next 

      You will have to request the identifiers of the next and previous records using separate requests.

      Previous record ID:

       SELECT articleid AS previousid FROM articleviews WHERE articleid < $lastid ORDER BY articleid DESC LIMIT 1 

      The ID of the following entry:

       SELECT articleid AS nextid FROM articleviews WHERE articleid > $lastid ORDER BY articleid DESC LIMIT 1 

        Use the request:

         select min(id) as prev,max(id) as next from ( select id from articleviews where id>=(select coalesce(max(id),?) from articleviews where id < ?) order by id limit 3 ) A 

        In place ? You must bind your current ID. At the output in the array of results immediately lie prev and next . If the received variables are equal to the current ID or NULL, then the specified ID was the first or last, do not display such a link.

        • And why in the first where then don't just write id <= ? + 1 id <= ? + 1 If a match by id is expected? - Alexey Shimansky
        • one
          @ Alexey Shimansky Take ? = 15 by the given example in the question. then? + 1 = 16, take 3 entries that <= 16: 5,7,15. We did not receive the following ID for 15, i.e. 20 - therefore exactly as it is written - Mike
        • @Mike, I twisted-twisted in my head. your request will not work if id = 1. Null, Null will return - splash58
        • @ splash58 I agree, I fixed it, but somehow it comes out too cleverly: ( - Mike
        • @Mike, I think you immediately very casuistically approached this request. although the idea itself is not bad - about three consecutive - splash58