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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号