我从PHP插入一个MySQL表并在插入后立即运行查询以获取刚插入的行的键值,如下所示:
$stmt = $this->db->prepare("INSERT INTO user(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid, vTournaments, vDays, dAddedDate, eStatus) VALUES (?,?,?,?,4,'Pick-Up','Saturday',NOW(),'Active')");
$stmt->bind_param("ssss", $firstName, $lastName, $email, $pwd);
$stmt->execute();
$stmt->close();
$stmt = $this->db->prepare('SELECT iUserId FROM user WHERE vEmail=?');
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($iUserId);
while ($stmt->fetch()) {
break;
}
执行此代码后,$iUserId
具有正确的自动递增键值(例如1143),但是当我实际查看数据库表时,具有该键的行(1143)不存在。怎么可能?
答案 0 :(得分:2)
您应该使用mysqli::$insert_id
:
$stmt = $this->db->prepare('
INSERT INTO user
(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid,
vTournaments, vDays, dAddedDate, eStatus)
VALUES
(?,?,?,?,4,"Pick-Up","Saturday",NOW(),"Active")
');
$stmt->bind_param('ssss', $firstName, $lastName, $email, $pwd);
$stmt->execute();
$iUserId = $this->db->insert_id;
$stmt->close();
至于为什么插入的数据没有出现在其他连接中,似乎您的交易可能尚未提交:
$this->db->commit();