Using PHP I’m inserting a record in a MySQL database. If the record is new I get the insert_id but if it already exists I can’t get the id using a single query.
Both of the following queries allow me to add the record or skip if it already exists:
INSERT INTO `emails` (`email`) VALUE ('abc@example.com') ON DUPLICATE KEY UPDATE `id`=`id`
INSERT IGNORE INTO `emails` (`email`) VALUE ('abc@example.com')
What is the right way to get the right result in both cases?
EDIT: Here’s my table syntax:
CREATE TABLE `emails` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I suspect that it’s the value of LAST_INSERT_ID that ends up in insert_id.
Quote from the MySQL manual;
To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:
Source: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html