dtlh12053 2013-01-20 18:35
浏览 31
已采纳

MySQL行已插入但未保存?

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??

  • 写回答

1条回答 默认 最新

  • duanbu1421 2013-01-20 18:58
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算