0

I am trying to get the last record from the database using lastInsertId() but it keeps retuning 0. I don't understand why this problem occurs. Here is my code. Thanks

$query = "SELECT url FROM links WHERE code = :code";
$get = $db->prepare($query);
$get->execute(array(
    ":code" => $code
));

if($get->rowCount()) {
    $url = $get->fetch(PDO::FETCH_OBJ)->url;

    $status = substr(get_headers($url)[0],9,3);

    if(intval($status) == 301) {
        $last = $db->lastInsertId();

        $query = "SELECT url FROM links WHERE id = :id";
        $send = $db->prepare($query);
        $send->execute(
            ":id" => $last
        );

        $lastUrl = $send->fetch(PDO::FETCH_OBJ)->url;
        header("Location:{$lastUrl}");
    }
    else {
        header("Location:{$url}");
    }

    die();
}
laurad
  • 91
  • 7
  • 3
    Returns the ID of the last `inserted` row or sequence value https://php.net/manual/ro/pdo.lastinsertid.php You dont insert anyhing – Mihai Feb 04 '15 at 10:52
  • I think it's [related post](http://stackoverflow.com/questions/20858818/pdo-lastinsertid-returns-zero0) And where you insert data? You just select them. – androschuk.a Feb 04 '15 at 10:54

2 Answers2

1

There's no INSERT in the code.

I guess you're looking for the biggest id in the table. Then the answer would be:

SELECT MAX(id) FROM links
Edson Medina
  • 9,862
  • 3
  • 40
  • 51
0

lastInsertId() works on the last query. Your query is SELECT type that is why it won't work. You can use lastInsertId() after INSERT query. If you wan to know last record you can use max(id) or sort it by id desc and get first one.

http://php.net/manual/en/pdo.lastinsertid.php

Robert
  • 19,800
  • 5
  • 55
  • 85
  • I have an insert query that runs if data is not in database, but if the user provides data that is already in database the code will go straight to the select query, how could I use the lastInsertId() then – laurad Feb 05 '15 at 08:15