如何获取插入行PDO PHP的自增主键?
How to get auto-increment Primary key of inserted row PDO PHP?
我想在PHP中使用PDO向数据库插入一个新行,主键是自增的,所以我没有插入PK的值。这是代码:
public function insertQuestion($text){
try{
$sql = "INSERT INTO question(text) VALUES(:question)";
$stm = $this->prepare($sql);
$stm->execute(array(
':question' => $text,
));
$question = new Question();
$question->text = $text;
$question->id = -1; // How do I get the PK of the row just inserted?
}catch(PDOException $e){
if ($e->getCode() == 1062) return FALSE; // fails unique constraint
else echo $e->getMessage();
}
}
但是,我需要存储插入 $question 对象的新行的 PK,我还有其他唯一的属性,所以我可以执行 SELECT 语句来查找 PK,但是,有更好的方法吗?
调用 PDO 对象的 lastInsertId。
$stmt->execute([':question' => $text]);
return $pdo->lastInsertId();
在数据库中插入记录后,编写另一个查询以降序从主键列值中获取顶部记录。
例如select prim_key_id 来自 table 的前 1 名按 prim_key_id desc;
排序
我想在PHP中使用PDO向数据库插入一个新行,主键是自增的,所以我没有插入PK的值。这是代码:
public function insertQuestion($text){
try{
$sql = "INSERT INTO question(text) VALUES(:question)";
$stm = $this->prepare($sql);
$stm->execute(array(
':question' => $text,
));
$question = new Question();
$question->text = $text;
$question->id = -1; // How do I get the PK of the row just inserted?
}catch(PDOException $e){
if ($e->getCode() == 1062) return FALSE; // fails unique constraint
else echo $e->getMessage();
}
}
但是,我需要存储插入 $question 对象的新行的 PK,我还有其他唯一的属性,所以我可以执行 SELECT 语句来查找 PK,但是,有更好的方法吗?
调用 PDO 对象的 lastInsertId。
$stmt->execute([':question' => $text]);
return $pdo->lastInsertId();
在数据库中插入记录后,编写另一个查询以降序从主键列值中获取顶部记录。
例如select prim_key_id 来自 table 的前 1 名按 prim_key_id desc;
排序