dongzheng4556 2011-09-30 01:59
浏览 59
已采纳

mysql_insert_id和mysql_pconnect

I've been using mysql_pconnect to establish all DB connections on my PHP site, with the theory that it's more efficient (debatable, I know).

I went to use mysql_insert_id to get the ID from a recent INSERT and it occurred to me that given the multi-threaded nature of web requests, I can't guarantee that another PHP script using the same pconnection has made a DB INSERT before my call to mysql_insert_id.

This is kind of a huge deal as I see no other way to guarantee atomicity of the INSERT and ID retrieval, as the ID is not returned by the INSERT query (or I don't know how to get it).

So basically I can never use mysql_pconnect if I want to have thread-safe INSERTS and ID retrieval?

  • 写回答

2条回答 默认 最新

  • donglin8467 2011-09-30 02:27
    关注

    mysql_insert_id() returns the last id within context of the current connection session. Thus avoiding race-condition problems. There's a bunch of notes/comments regarding this on the php.net manual for mysql_insert_id()

    More Info:

    This should be easy to test:

    <?php
    // connection already established
    mysql_query("INSERT INTO table VALUES('foo', 'bar')");
    sleep(15);
    echo mysql_insert_id();
    

    Then see if you can fool it by slamming it with requests during the sleep period.. and check the insert_id results.

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

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM