dpx49470
dpx49470
2013-07-19 00:50

使用PHP获取MySQL插入的主键

已采纳

I have looked through the documentation for this, but it is all about auto-increment.

I generate a key using a trigger and MySQL's UUID() function (I need these keys to be unique across databases that may or may not ever interact).

I use a trigger to generate the UUID()

How would I retrieve that key on an insert?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongshou2017 dongshou2017 8年前

    Pass the UUID created by the trigger on a variable (@last_uuid)

    CREATE TRIGGER ai_uuidtable
    AFTER INSERT ON uuidtable
    FOR EACH ROW
    SET @last_uuid = NEW.uuid;
    

    Then you can retrieve the value using a query

    SELECT @last_uuid
    
    点赞 评论 复制链接分享
  • duanjianlu0506 duanjianlu0506 8年前

    You could move the UUID generation to the PHP side instead of using MySQL. Here is one example: https://stackoverflow.com/questions/4049455/how-to-create-a-uuid-in-php-without-a-external-library

    点赞 评论 复制链接分享
  • doujiao3074 doujiao3074 8年前

    You have to make TWO queries :

    SELECT UUID();
    

    save it in a variable ( $uuid ) and then run the INSERT query:

    INSERT INTO table (id, text) VALUES ($uuid, 'text');
    
    点赞 评论 复制链接分享

为你推荐