This question already has an answer here:
Answer
Solution:
lastInsertId()
only returns the last auto-increment id generated if you call that function in the same session the id was generated in.
Every time you call $this->connect()
it opens a new connection, thus it's a new session and any state from the previous session (e.g. the last insert id) is reset.
You might have intended $this->connect()
to skip creating a new connection if it already has one.
class Db {
private $host = "localhost";
private $user = "root";
private $pwd = "";
private $dbName = "cms";
private $pdo;
public function connect() {
if (!$this->pdo) {
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbName;
$this->pdo = new PDO($dsn, $this->user, $this->pwd);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
return $this->pdo;
}
}
This opens a new connection the first time you call connect()
, but it saves the connection as an object variable. Each subsequent time time you call connect()
it just uses the same connection it had saved earlier. The connection stays open for the lifespan of this Db
object.
Source