Home > Back-end >  PDO->lastInsertId always return 0
PDO->lastInsertId always return 0

Time:12-06

I have a class for work with DataBase. I use PDO. I want get last id when i insert record, but function always return 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

public function createClient($data) {      
        $data = [
            'id' => 3,
            'name' => 'Joe',
            'number' => '333-333-55',
            'email' => '[email protected]',
        ];
        $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

CodePudding user response:

I assume idClient the auto-increment column of your client table.

If you specify the value in your INSERT statement (in your example the value is 3), then this overrides the auto-increment feature. No id is generated.

LAST_INSERT_ID() only reports value that were generated automatically. Since you specified the value yourself, you already know it, so there's no need.

  • Related