简体   繁体   English

MySQL行已插入但未保存?

[英]MySQL row inserted but not saved?

I am inserting a row into a MySQL table from PHP and running a query right after the insert to get the key value of the row that was just inserted like so: 我正在从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;
}

After this code executes, $iUserId has the correct auto incremented key value (1143 for instance), but when I actually look at the database table, the row with that key (1143) does not exist. 执行此代码后, $iUserId具有正确的自动递增键值(例如1143),但是当我实际查看数据库表时,具有该键的行(1143)不存在。 How is that possible?? 那怎么可能?

Instead of selecting from the table after insertion, you should use mysqli::$insert_id : 而不是在插入后从表中选择,您应该使用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();

As to why the inserted data is not appearing from other connections, it seems likely that your transaction has not been committed: 至于为什么未从其他连接中显示插入的数据的原因,似乎您的事务尚未提交:

$this->db->commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM