我想使用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,但是有更好的方法吗?
发布于 2015-03-17 10:03:04
调用PDO对象的lastInsertId。
$stmt->execute([':question' => $text]);
return $pdo->lastInsertId();
发布于 2015-03-17 10:06:01
仅在数据库中插入记录之后,编写另一个查询,以从主键列值中按降序从主键列值中获取顶级记录。
例如,通过prim_key_id desc从表顺序中选择prim_key_id top 1;
https://stackoverflow.com/questions/29096095
复制相似问题