Search code examples
phpmysqlpdo

MySQL next previous record issue


this is my script

 <?php

 if(isset($_GET['id']))
 {
    $id = $_GET['id'];
}
else
{
    $id = 1;
}

    $random = $conn->query("SELECT * FROM records ORDER BY RAND()");
    $row = $random->fetch();

    $stmt_1 = $conn->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
    $stmt_1->bindValue(1,$id);
    $stmt_1->execute();
    $stmt_1->setFetchMode(PDO::FETCH_ASSOC);
    $row = $stmt_1->fetch();
    $id = $row['id'];

    $stmt_1 = $conn->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DSC LIMIT 1");
    $stmt_1->bindValue(1,$id);
    $stmt_1->execute();
    $stmt_1->setFetchMode(PDO::FETCH_ASSOC);
    $row = $stmt_1->fetch();
    $id = $row['id'];

    ?>

But I have a problem with it. For example i have 4 records in database :

ID String
1  Test-1
2  Test-2
3  Test-3
4  Test-4

the query works fine it gives me the next record but not the id which i put like if i put id=1 returns id 2 or id=2 returns info for id 3 and the result is not accurate. So my question is what should I do id to return correct result not +1. I know it starts to count from 0 and i want to fix that in my script i want to make it to start from 1.


Solution

  • replace this

       $id = 1;
    

    by

       $id = 0;
    

    or replace this

        SELECT * FROM records WHERE id > ?
    

    by

       SELECT * FROM records WHERE id >= ?
                                       ^--//-will look for id equal to 1 or bigger