简体   繁体   English

插入后获取最后一个ID(始终返回0)

[英]Get last ID after insert (always return 0)

I have an Sql class like this: 我有一个像这样的Sql类:

        class Sql extends PDO {
            private $connection;
            public function __construct() {
                $this->connection = new PDO("mysql:host=localhost;dbname=myDB", "root", "root");
            }

 (...)

Then I'm trying to insert a data in my db using another class "user.php". 然后我尝试使用另一个类“user.php”在我的数据库中插入数据。 Using the "getConection" (sql class method). 使用“getConection”(sql类方法)。 Like this: 像这样:

class User {
    private $iduser;
    private $deslogin;
    private $despassword;
    private $datecad;

    (getters & setters)

public function insert() { //query & select are a SQL class method
        $sql = new Sql();
        $sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS))", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        ));

            echo $sql->getConnection()->lastInsertId(); //getConnection is a Sql Class method that returns the private connection.
    }

Why my echo always returns 0? 为什么我的回声总是返回0?

Its because you need same connection object regarding insert query to get last inserted ID but you are creating new connection for getting last inserted ID. 这是因为您需要插入查询相同的连接对象来获取最后插入的ID, 但是您正在为获取最后插入的ID 创建新连接 That's why you are always getting 0 as result. 这就是为什么你总是得到0结果。

See the reference : 参见参考文献:

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

EDIT 编辑

From your code reference its problem in your insert Have you mark there is one extra closing bracket 从您的代码引用它insert问题您是否标记有一个额外的结束括号

change your code to: 将您的代码更改为:

$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS)", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        )); //<------there must be only one bracket after::LOGIN, :PASS

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

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