Search code examples
mysqlsql-order-bylimit

How to choose the previous id from the last id with PDO


I want to choose the previous id from the last id. How can I do it? Database is mysql.

example:

id name
1   asd
2   adas
3   ads
4   dsf -> I want to choose this 
5   rew

id name  ---------------------------------------|
1   asd                                         |
2   adas                                        |
3   ads                                         |
4   dsf                                         |
5   rew -> I want to choose this if I add any "name"
6   zxc

I tried this lines so far:

$sql = $db->prepare("SELECT * FROM answerController ORDER BY id DESC LIMIT 2");
$sql->execute();
$data = $sql->fetch();

Solution

  • You need to provide the offset for the limit to start at.

    SELECT * FROM answerController ORDER BY id DESC LIMIT 1, 2
    

    https://dev.mysql.com/doc/refman/8.0/en/select.html

    the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1)

    So it should be:

    $sql = $db->prepare("SELECT name FROM answerController ORDER BY id DESC LIMIT 1, 2");
    $sql->execute();
    $data = $sql->fetch(PDO::FETCH_ASSOC);
    echo $data['name'];