I have used the following sql on my website
$sql = "INSERT IGNORE INTO names VALUES ('akku#gmail.com','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 (akku#gmail.com) 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.
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
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/
Related
I am currently starting web development and am now working on a very simple script that posts entry data from a from to a mysql database. But the problem I have been encountering is that when I submit the form I get the following error:
Error: Duplicate entry '0' for key 'PRIMARY'
To me it seems a really weird error as the table is completely empty, ID is set to auto_increment and I am not trying to assign any value to it.
I am using Xampp for my localhost on Mac OS btw.
This is my form (.php):
This is my mysql entry script (.php):
The result is this:
This is the database setup:
The weird thing is that when the table is empty, and I insert through the form the first time, something does end up in the database. But it is missing "email" and "password" and shows "NULL". The second time I use the form, nothing is added in the database:
Your id column does not seem to be auto-incrementing. It is not generating a new id for every row. It just defaults to 0 if you don't supply a value for it.
Nonetheless there's a UNIQUE/PRIMARY constraint on that column, so the id 0 cannot occur more than once. Since you're not supplying an id and MySQL isn't generating one (because the column isn't auto-incrementing), you cannot insert more than one row.
You're issuing three separate INSERT INTO statements which will result in three separate rows to be inserted (if you could insert more than one row, see above), each with a different value set; but never one row with all values set.
So:
Make your id column actually auto-incrementing.
Prepare a single INSERT INTO statement which inserts all values in one go:
INSERT INTO members (name, email, password) VALUES (.., .., ..)
See Why shouldn't I use mysql_* functions in PHP? and stop using mysql_*. Learn about prepared statements, read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for why.
I have a MySQL query that looks like this:
INSERT INTO beer(name, type, alcohol_by_volume, description, image_url) VALUES('{$name}', {$type}, '{$alcohol_by_volume}', '{$description}', '{$image_url}')
The only problem is that name is a unique value, which means if I ever run into duplicates, I get an error like this:
Error storing beer data: Duplicate entry 'Hocus Pocus' for key 2
Is there a way to ensure that the SQL query does not attempt to add a unique value that already exists without running a SELECT query for the entire database?
You could of course use INSERT IGNORE INTO, like this:
INSERT IGNORE INTO beer(name, type, alcohol_by_volume, description, image_url) VALUES('{$name}', {$type}, '{$alcohol_by_volume}', '{$description}', '{$image_url}')
You could use ON DUPLICATE KEY as well, but if you just don't want to add a row INSERT IGNORE INTO is a better choice. ON DUPLICATE KEY is better suited if you want to do something more specific when there are a duplicate.
If you decide to use ON DUPLICATE KEY - avoid using this clause on tables with multiple unique indexes. If you have a table with multiple unique indexes ON DUPLICATE KEY-clause could be giving unexpected results (You really don't have 100% control what's going to happen)
Example: - this row below only updates ONE row (if type is 1 and alcohol_by_volume 1 (and both columns are unique indexes))
ON DUPLICATE KEY UPDATE beer SET type=3 WHERE type=1 or alcohol_by_volume=1
To sum it up:
ON DUPLICATE KEY just does the work without warnings or errors when there are duplicates.
INSERT IGNORE INTO throws a warning when there are duplicates, but besides from that just ignore to insert the duplicate into the database.
As it just so happens, there is a way in MySQL by using ON DUPLICATE KEY UPDATE. This is available since MySQL 4.1
INSERT INTO beer(name, type, alcohol_by_volume, description, image_url)
VALUES('{$name}', {$type}, '{$alcohol_by_volume}', '{$description}',
'{$image_url}')
ON DUPLICATE KEY UPDATE type=type;
You could also use INSERT IGNORE INTO... as an alternative, but the statement would still throw a warning (albeit, instead of an error).
Yes, there is. You can use the ON DUPLICATE KEY clause of mysql INSERT statement. The syntax is explained here
INSERT INTO beer(name, type, alcohol_by_volume, ...)
VALUES('{$name}', {$type}, '{$alcohol_by_volume}', ...)
ON DUPLICATE KEY UPDATE
type={$type}, alcohol_by_volume = '{$alcohol_by_volume}', ... ;
Yes, by first selecting the name from the database, and if the result of the query is not null (zero records), then the name already exists, and you have to get another name.
Quite simply - your code needs to figure out what it wants to do if something's trying to insert a duplicate name. As such, what you need to do first is run a select statement:
SELECT * FROM beer WHERE name='{$name}'
And then run an 'if' statement off of that to determine if you got a result.
if results = 0, then go ahead and run your insert.
Else ... whatever you want to do. Throw an error back to the user? Modify the database in a different way? Completely ignore it? How is this insert statement coming about? A mass update from a file? User input from a web page?
The way you're reaching this insert statement, and how it should affect your work flow, should determine exactly how you're handling that 'else'. But you should definitely handle it.
But just make sure that the select and insert statements are in a transaction together so that other folks coming in to do the same sort of stuff isn't an issue.
I need to insert this in a table but only if there isn't a replica of the row already. (both values should be equal). How can I change the code to work this way? Thanks
<?php
mysql_select_db("cyberworlddb", $con);
mysql_query("INSERT INTO Badges (UID, Website)
VALUES ('1', 'www.taringa.net')");
mysql_close($con)
?>
You could create a single index for the UID and Website columns and make that index unique, then use INSERT IGNORE. The result will be that if it is a duplicate, it will just be ignored.
If you need to be able to tell if the SQL inserted a row, then follow it up with a call to mysql_affected_rows() which should return 0 if it didn't do anything and 1 if it inserted the record.
Easiest thing to do is use INSERT IGNORE and have a unique key on the fields. It will insert if no row exists, otherwise do nothing.
What about a unique index on (UID, Website), which would cause the insert to fail?
First up, about the question. It is simple bad to check for "an exact" replica of row in RDBMS. That is just too costly. The right question to ask is what makes my row unique and what is the minimum I can get away with. Putting in unique constraints on big columns is a bad idea.
Answers saying that you should include UID in unique constraint are again just BAD. UID is most likely a generated key and the only input coming from outside is website name. So the only sane thing to do here is to put a unique constraint on website column.
Then the insert code should handle unique constraint errors coming out from the database. You can get the error number from DB handle, like
$errorNo = $mysql->errno ;
Then check for a particular code (1062 in case of MYSQL) that corresponds to unique key violation.
Before Entering data into a database, I just want to check that the database doesn't have the same username in the database already.
I have the username in SQL set as a key, so it can't be duplicated on that end, but I am looking at finding a more user-friendly error message then "KEY already exists".
Is there are simple way to check if the variable value already exists in a row?
Either preform a check before attempting the insert, or catch the exception and display it in a more clean and user-friendly way in your application.
Edit: Take a look at this tutorial on PHP exception handling. You probably want to wrap your query execution in a try-catch block, like so:
try
{
// do your query here (it's been forever since I've used PHP)
}
catch(Exception $e)
{
// display a clean error to the user
}
Except, instead of catching a general type Exception, you'll want to figure out what sort of exception you're actually getting (something like MySQLDuplicateKeyException, or whatever it may be - echo the exception you get when testing, and use that). This way, you won't display an error informing the user of an existing username, if in fact, there is another problem (like a DB connection error, for instance).
Good luck!
The technique to check whether data exists is to issue the query:
SELECT COUNT(*) FROM YourTable WHERE YourKeyCol = YourKeyValue
and then examine the first returned column of the only returned row in the dataset. If it contains 0, the data wasn't there, otherwise it was found.
But as others have pointed out, you can just go ahead and issue your INSERT. Examine the error code to determine whether it failed. This is more performant because, for those cases where the data is not already in the database, you will execute only one query instead of two.
There might be a special way to do this depending on what RDBMS you are using.
For example, using MySQL, you can say
INSERT INTO table (username,value) VALUES ('foo',123) ON DUPLICATE KEY UPDATE value = 123;
Since you've already set username to be a unique key, this will insert ('foo',123) into table only if foo is not already in the table. If it does exist, then the value is updated.
Or, you could use something like
INSERT IGNORE INTO table (username,value) VALUES ('foo',123)
which ignores the insert if foo is already in the table.
I can think of two ways to do this.
The first is simply to do a select statement beforehand on that username to detect any duplicates. If a row is returned then you know that that username already exists.
The other is that you can get mysql to return the error number using mysql_errno, you can then simply have an if statement that checks for a specific error number. The only problem with this that it may not indicate which field is a duplicate of the key.
I have used a pre select statement in my scripts.
Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.
I'm using PHP 4 and MySql 4.1.
This works if you have a unique index or primary key on the column (EmailAddr in this example):
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test#test.com')
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
See the MySql docs for more information.
If the column is a primary key or a unique index:
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
Most likely something like:
IF NOT EXISTS(SELECT * FROM myTable WHERE Email=#Email) THEN INSERT INTO blah blah
That can be rolled into one database query.
A slight modification/addition to naeblis's answer:
INSERT INTO table (email) VALUES (email_address)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
This way you don't have to throw email=email_address in there and you get the correct value for LAST_INSERT_ID() if the statement updates.
Source: MySQL Docs: 12.2.5.3
MySQL offers REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the
old row is deleted before the new row
is inserted.
I'm not sure if I got it, but what about a
try {
mysql_query($sql);
}
catch(Exception $e) {
}
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..
If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.