pdo lastInsertedId()返回0

时间:2018-12-03 12:15:24

标签: php mysql pdo

你好,请帮我我上次插入的索引返回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();
    }
}

感谢您的帮助。 我尝试在所有相同的问题持续存在的问题中提出建议

1 个答案:

答案 0 :(得分:1)

To retrieve the lastInsertID your code connects to the database for the second time, and the driver might just not share insert IDs over multiple connections:

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

Instead, keep the PDO object created in connect(), and reuse it to query the last ID.

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

See also PHP PDO documentation, especially comments section.