Let’s say I have a table named WORDS where there is just a primary key (ID), and a column WORD. The WORD column should be unique varchar, and the ID is an auto-incrementing integer field.
In SQL Terms,
CREATE TABLE WORDS(
ID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
WORD VARCHAR(35) NOT NULL,
UNIQUE(WORD)
);
While going through a list of words in PHP, I’d like to insert a new word to the WORDS table. If it’s already present, I’d like nothing to happen – and if it isn’t present I’d like it to be inserted.
I found the best solution to this was using INSERT IGNORE. I have to go one step further now though… my PHP script needs to know the primary key of the word after its inserted into the table. If it wasn’t already present, this is easy – I can just use mysql_insert_id. If it was present though, I seem to have to do a query on the table to get what the primary key for that word already was.
Is there a neat way to do:
“Insert this into the table if it’s not already there, and give me the
primary key it’s in either way.”
by any chance?
There is no easy way to do this. But you can cut it down to a function
This is a short function to do everything that you basically asked.