0

Hello please help me my last inserted index return 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;
    }
}

my dbconnection

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();
    }
}

Thanks for your help. I try all sugestent in précédent questions the same probleme persiste

  • 1
    You need to use `$query` to get the last ID not a new connection which is what it looks like you are doing now. Try `$lastId = $query->lastInsertId($sql);`. – Dave Dec 03 '18 at 12:52

1 Answers1

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.

Lyth
  • 2,103
  • 2
  • 29
  • 35