douwenpin0428 2018-01-21 18:00
浏览 76
已采纳

如何获取表的自动增量主键

I have a small MySQL database of sellers where there is a table, in which each seller has an auto-increment primary key (and there is not any other unique key attribute). Now I want to retrieve each seller data from the php script

// Nothing wrong with this code
    $stmt = $this->conn->prepare("SELECT * FROM seller WHERE id= ? LIMIT 1");
    $stmt->bind_param("i", $ud);
    $stmt->execute();
    $result = $stmt->get_result();

But.. to retrieve data with this query, I need to have the primary key ( i.e. autoincrement id of the seller ). How would I know what is the primary key of the record inserted?

  • 写回答

3条回答 默认 最新

  • doujiejujixi27244 2018-01-25 10:41
    关注

    insert_id attribute of the prepared statement saved me. Now just after my insert statement I can get the last inserted primary key of the table-

    $stmt->execute();
    $sid = $stmt->insert_id;
    

    This is equivalent to the LAST_INSERT_ID() function in mysql. Make sure you use this in the same session, just after insertion of the table row. Otherwise, it returns a null set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员