php_nub_qq
php_nub_qq

Reputation: 16055

Get last inserted row's complex primary key

Consider the following table, completely random for the example

CREATE TABLE `test` (
  `key` int(11) NOT NULL,
  `id2` varchar(255) NOT NULL,
  `id3` varchar(255) NOT NULL,
  `text` varchar(255) NOT NULL,
  PRIMARY KEY (`key`,`id2`,`id3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I need to insert and get the unique identifier for the inserted row, which would be the complex primary key. If I had a single column primary key I would use PDO::lastInsertId, but if I use it in this case I get result string(1) "0" for statement INSERT INTO test VALUES (1, 1, 1, 'test'). Is there any way I could get the primary key columns of a complex key after insert? In this particular case from the statement above I need to get array(1, 1, 1)

Upvotes: 1

Views: 85

Answers (1)

LoïcR
LoïcR

Reputation: 5039

mySQL is able to return you the last inserted key only if the field is generated by the system, otherwise, it will not be possible to retrieve the last saved data with a function.

You could go for a generated identifier and retrieve every key with a second select, but I'm not sure the performance will suit your expectations. Sorry.

Upvotes: 1

Related Questions