WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to insert if something does not exist in MySQL database

When we create a database table we try to make sure that on certain tables we only allow the user to insert a unique record. To achieve this, we assign a primary key to the table but sometimes duplicate records can be inserted as there may not be any validations in place.

The code below allows you to insert records only if it doesn’t already exist in the table:


INSERT INTO user (Name,username,password)
SELECT * FROM (SELECT 'Name', 'Address', 'Postcode') 
AS tmp WHERE NOT EXISTS 	
(SELECT Name,username,password 
FROM user WHERE Name = 'Name' and username = 'Address' and password = 'Postcode');

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

Join the discussion

Related Posts

Wordpress / 20th January 2019

Create a new WordPress admin user in the database

Read More

MySQL / 27th July 2016

How to Add Admin User to WordPress with MySQL

Read More