MirroredFate
MirroredFate

Reputation: 12816

Get primary key of a MySQL insert using PHP

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?

Upvotes: 1

Views: 213

Answers (3)

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14086

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');

Upvotes: 0

Jm Verastigue
Jm Verastigue

Reputation: 398

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

Upvotes: 1

Luke Cordingley
Luke Cordingley

Reputation: 685

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

Upvotes: 0

Related Questions