简体   繁体   English

PDO 将 lastInsertId() 返回为零 (0),我不明白?

[英]PDO return lastInsertId() as Zero (0), i didn't understand?

This is my code ?这是我的代码? PDO return always the last inserted id as 0, I tried everything.! PDO 总是将最后插入的id返回为 0,我尝试了一切。!

$this->db()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO inbox (sender,recever) VALUES ('1','2')";
$this->db()->exec($sql);        
$project_id =$this->db()->lastInsertId();

The sql code table : sql代码表:

CREATE TABLE inbox(
id int(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sender int,
recever int
);

Try this尝试这个

//set persistent connection
$con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->use‌​r,$this->pass,array(‌​PDO::ATTR_PERSISTENT => TRUE));    
$stmt = $con->prepare("INSERT INTO inbox (sender,recever) VALUES ('1','2')");
$stmt->execute();
$id = $db->lastInsertId();

The problem is your db() method which creates a new connection every time it is called.问题在于您的db()方法每次调用时都会创建一个新连接。

Instead of such method, use a property.使用属性代替这种方法。 Assign your PDO instance to $this->db property and then use it whenever you need a PDO connection.将您的 PDO 实例分配给$this->db属性,然后在需要 PDO 连接时使用它。

While your current implementation is just terrible, and workaround you have been offered in the other answer is not guaranteed to work.虽然您当前的实现很糟糕,但不能保证您在另一个答案中提供的解决方法有效。 Let alone it shouldn't be used in the first place.更不用说它一开始就不应该使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM