Php lastInsertId返回0
事实上,有很多关于这个的帖子。但即使我检查了这些,仍然找不到问题 DBC类Php lastInsertId返回0,php,pdo,Php,Pdo,事实上,有很多关于这个的帖子。但即使我检查了这些,仍然找不到问题 DBC类 protected function connect(){ $dns = "mysql:host=" . $this->server . ";dbname=" . $this->database; $pdo = new PDO($dns, $this->username, $this->password); $pdo->setAttribute(PDO::ATTR_
protected function connect(){
$dns = "mysql:host=" . $this->server . ";dbname=" . $this->database;
$pdo = new PDO($dns, $this->username, $this->password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
和插入函数
public function insert_row($created_at){
$sql = "INSERT INTO empty_rows (created_at) VALUES (?)";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$created_at]);
$id = $this->connect()->lastInsertId();
echo $id;
}
我认为它应该返回最后一个插入的Id,但它只返回0。我错过了什么 $lastInsertId()
返回在同一连接上插入的ID。每次调用$this->connect()
时,您都会获得一个新连接
您需要保存$this-connect()
的结果,以便使用相同的连接
public function insert_row($created_at){
$sql = "INSERT INTO empty_rows (created_at) VALUES (?)";
$connect = $this->connect();
$stmt = $connect->prepare($sql);
$stmt->execute([$created_at]);
$id = $connect->lastInsertId();
echo $id;
}
通常,如果您继续创建新连接,您的应用程序速度会显著降低。我建议您更改connect()
方法,使其只在第一次连接
protected function connect(){
if (!isset($this->pdo) {
$dns = "mysql:host=" . $this->server . ";dbname=" . $this->database;
$this->$pdo = new PDO($dns, $this->username, $this->password);
$this->$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
return $this->$pdo;
}
事实上,inserrt并没有失败。将插入该行。我正在检查DB@Barmaryes它有@Barmar$this->connect()不是一个单例,非常确定如果你重新连接该值是lostOh,我理解,谢谢你的指点。我将检查这个作为答案。