简体   繁体   English

PDO->lastInsertId 总是返回 0

[英]PDO->lastInsertId always return 0

I have a class for work with DataBase.我有一个 class 用于使用数据库。 I use PDO. I want get last id when i insert record, but function always return 0;我使用 PDO。我想在插入记录时获取最后一个 ID,但 function 始终返回 0;

 class Database {
        private $db;
        private $error;

        public function __construct() {
            $config = require "config/db.php";
            $conn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['db'].';charset=UTF8';
            $options = array(
                \PDO::ATTR_PERSISTENT => true,
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
            );
            try {
                $this->db = new \PDO($conn, $config['username'], $config['password'], $options);
            } catch (\PDOException $e) {
                $this->error = $e->getMessage();
                echo $this->error;
            }
        }

         public function queryInserUpdate($sql, $params = []) {
            $stmt = $this->db->prepare($sql);
            if ( !empty($params) ) {
                foreach ($params as $key => $value) {
                    $stmt->bindValue(":$key", $value);
                }
            }
            $stmt->execute();
            $lastId = $this->db->lastInsertId();
            return $lastId;
        }

I call function in other class. Insert operation works, but return id = 0我在其他 class 中调用 function。插入操作有效,但返回 id = 0

public function createClient($data) {      
        $data = [
            'id' => 3,
            'name' => 'Joe',
            'number' => '333-333-55',
            'email' => 'joe@joe.com',
        ];
        $sql = "INSERT INTO clients (idClient, name, number, email) VALUES (:id, :name, :number, :email)";
        $stmt= $this->db->queryInserUpdate($sql, $data);
        if(isset($stmt)){
            echo $stmt;
        } else {
            return "error";
        }
    }

I read that this is because he connects to the database again, but I do not understand where我读到这是因为他再次连接到数据库,但我不明白在哪里

I assume idClient the auto-increment column of your client table.我假设idClient是您的client表的自动增量列。

If you specify the value in your INSERT statement (in your example the value is 3), then this overrides the auto-increment feature.如果您在 INSERT 语句中指定值(在您的示例中该值为 3),那么这将覆盖自动递增功能。 No id is generated.没有生成 id。

LAST_INSERT_ID() only reports value that were generated automatically. LAST_INSERT_ID() 仅报告自动生成的值。 Since you specified the value yourself, you already know it, so there's no need.既然你自己指定了这个值,你已经知道了,所以没有必要。

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

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