This question already has answers here:
pdo lastInsertId returns zero(0)
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
您好,请帮我我上次插入的索引返回0。

public function insert($client) {
    $sql = "insert into client (nom,adresse,tel) values (:nom,:adresse,:tel)";
    $stmt = $this->connect()->prepare($sql);
    $nom = $client->getNom();$adresse = $client->getAdresse();$tel = $client->getTel();
    $stmt->bindParam(':nom', $nom, PDO::PARAM_STR);
    $stmt->bindParam(':adresse', $adresse, PDO::PARAM_STR);
    $stmt->bindParam(':tel', $tel, PDO::PARAM_STR);
    $query = $stmt->execute();
    $lastId = $this->connect()->lastInsertId($sql);
    if ($query) {
        $client->setId($lastId);
        $this->liste[$lastId] = $client;
        $_SESSION['listeClient'] = $this->liste;
        return TRUE;
    }
}


我的数据库连接

protected function connect() {
    $this->servername = "localhost";
    $this->username = "root";
    $this->password = "";
    $this->dbname = "pdo";
    $this->charset = "utf8mb4";
    try {
        $dsn = "mysql:host=" . $this->servername . ";dbname=" . $this->dbname . ";charset=" . $this->charset;
        $pdo = new PDO($dsn, $this->username, $this->password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (\Exception $e) {
        echo "connection failed: " . $e->getMessage();
    }
}


谢谢你的帮助。
我尝试所有关于永久性问题的建议

最佳答案

要检索lastInsertID,您的代码将第二次连接到数据库,并且驱动程序可能不会通过多个连接共享插入ID:

$lastId = $this->connect()->lastInsertId($sql);


相反,请保留在connect()中创建的PDO对象,然后重用它来查询最后一个ID。

$pdo = $this->connect();
$stmt = $pdo->prepare($sql);
...
$lastId = $pdo->lastInsertId();


另请参见PHP PDO documentation,尤其是注释部分。

关于php - pdo lastInsertedId()返回0 ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53593682/

10-16 16:39