How to do ‘insert if not exists’ in MySQL and PHP?

Spread the love

Sometimes, we want to do ‘insert if not exists’ in MySQL and PHP.

In this article, we’ll look at how to do ‘insert if not exists’ in MySQL and PHP.

How to do ‘insert if not exists’ in MySQL and PHP?

To do ‘insert if not exists’ in MySQL and PHP, we run an insert select statement.

For instance, we write

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

to run an insert statement that selects the item from select.

Then we insert it if it doesn’t exist with

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

we run a selectr statement that selects the value based on the where clause to check if the value already exists.

Conclusion

To do ‘insert if not exists’ in MySQL and PHP, we run an insert select statement.

Leave a Reply

Your email address will not be published. Required fields are marked *