【发布时间】:2015-05-19 16:54:52
【问题描述】:
我想在 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,但是,有没有更好的方法干吗?
【问题讨论】: