Aqu Akhil
Aqu Akhil

Reputation: 41

Mysql INSERT IGNORE INTO ignore only one column

I have used the following sql on my website

$sql = "INSERT IGNORE INTO names VALUES ('[email protected]','19','akku');";

This code only works if both three values are same. .I need to Insert the data to the database only if first value ([email protected]) is not exists on the database. Else it should display "email already exists". Also it should work even if the second and third values are different.

Upvotes: 2

Views: 1982

Answers (2)

Caius Jard
Caius Jard

Reputation: 74605

Make the email address the primary key of your table. Don't use the IGNORE keyword in the statement. Catch the error that arises when a duplicate email is entered (attempting to insert the duplicate into MySQL will cause an exception in your front end code) and display an "email already exists" message

The database doesn't care what your values are so I don't really understand what you mean by "it only works if the last two are he same" unless you have a trigger that raises an error if you attempt to insert differing values for your last two columns

Upvotes: 2

xRahul
xRahul

Reputation: 364

You can use SELECT first to find if the data is there, and then insert if it isn't or update if it is. This would be the best way as you can use php to handle any case using this.

Second way would be to make first value primary key. This way your insert would throw an error and you can catch that to do whatever you want.

Third way, in which if you want to update data if it exist would be using- INSERT ON DUPLICATE KEY UPDATE https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/

Upvotes: 1

Related Questions