简体   繁体   English

为什么在我的代码PDO中lastInsertId()返回0?

[英]Why in my code PDO lastInsertId() returns 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. 我正在尝试使用lastInsertId()从数据库中获取最后一条记录,但它一直在重新调整0。我不明白为什么会发生此问题。 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();
}

There's no INSERT in the code. 代码中没有INSERT。

I guess you're looking for the biggest id in the table. 我想您正在寻找表格中的最大ID。 Then the answer would be: 那么答案将是:

SELECT MAX(id) FROM links

lastInsertId() works on the last query. lastInsertId()适用于最后一个查询。 Your query is SELECT type that is why it won't work. 您的查询是SELECT类型,这就是为什么它不起作用的原因。 You can use lastInsertId() after INSERT query. 您可以在INSERT查询之后使用lastInsertId()。 If you wan to know last record you can use max(id) or sort it by id desc and get first one. 如果您想知道最后一条记录,则可以使用max(id)或按id desc对其进行排序,以获得第一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM