PDO Get Previous and Next Record Question

Posted in CategoryGeneral Discussion
  • Terry Ogbemudia 2 years ago
    sorry I missed this question
  • Hder 2 years ago

    Solved:  added the ORDER by DESC.

    $stmt= $db->prepare("SELECT * FROM blog WHERE article_id<$id ORDER by article_id DESC LIMIT 0,1");
  • Hder 2 years ago

    Hi Terry, hope you can shed some insight to my issue.  The PDO SQL code for Next fetches the next record, but for Previous always returns the first record.  Don't understand why Previous does not work.  There are 7 records in this test set and the 'article_id' field is not contiguous (due to deletions) but is broken up as such:   24, 45,46,47, 48, 50, 51.  Code below:

            $id = 47;

            echo 'current id is:'.$id;

            //GET PREVIOUS ID

            $stmt= $db->prepare("SELECT * FROM blog WHERE article_id<$id LIMIT 0,1");



            echo '<br>';

            echo 'Previous ID is:'.$row['article_id'];    

            //GET NEXT ID

            $stmt= $db->prepare("SELECT * FROM blog WHERE article_id>$id LIMIT 0,1");



            echo '<br>';

            echo 'Next ID is:'.$row['article_id'];

    The resultant output is:

         current id is:47
         Previous ID is:24
         Next ID is:48

    The previous ID should be 46

Please login or register to leave a response.