简体   繁体   中英

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:

$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. How is that possible??

Instead of selecting from the table after insertion, you should use 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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