我想在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();
在数据库中插入记录后,编写另一个查询,以按降序从主键列值中获取顶部记录。
例如通过prim_ key_id desc从表顺序中选择prim_;