MySQL - Insert where not exists [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to ‘insert if not exists’ in MySQL?
I have a few inserts and I only want them to actually insert if there isn't already the same information in there.
I only want the insert to run using WHERE NOT EXISTS, would anybody be able to help me adding that to my queries?
Queries:
$db->Query("INSERT INTO `surfed` (site) VALUES('".$id."')");
Thanks so much!

Use the IGNOREkeyword
INSERT IGNORE INTO surfed (user, site) VALUES('".$data['id']."', '".$id."')
If you have a unique key constraint on the user-site combination then it would normally generate an error on duplicates and abort the insertion. Using ignore in the insert statement will ignore the error and just not insert anything.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. ... With IGNORE, the row still is not inserted, but no error is issued.
See here for more infos about it
SQLFiddle example

You should be able to go with mysql_num_rows. If that returns a value of 0, then there is nothing in your table matching what you want to insert. (WHERE NOT EXISTS).
So make something like "if mysql_num_rows = 0 then insert else do nothing".

First your two columns need to be a combined key, then you can use INSERT IGNORE as outlined by juergen d or use
ON DUPLICATE KEY UPDATE user=user
See similar question here:
INSERT ... ON DUPLICATE KEY (do nothing)
For the revised question of only having a site column, make sure the site column is a unique key or primary key and then use
$db->Query("INSERT INTO `surfed` (site) VALUES('".$id."') ON DUPLICATE KEY UPDATE site=site");

Related

Convert INSERT INTO into UPDATE [duplicate]

This question already has answers here:
Update a column in MySQL
(5 answers)
Closed 6 years ago.
Imagine I have some code like this:
$sql = "INSERT INTO tablename (column1, column2, column3) VALUES
('1','2','3')";
How would I convert this into an UPDATE query? I did some searching, but
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
doesn't make much sense to me. Thanks
INSERT and UPDATE queries look similar but they do different things.
Inserts => Inserts new nonexisting data into table
Update => Updates existing data inside of the table
That is why the UPDATE query has WHERE clause
So, you can use UPDATE to modify a row which is already inserted.
I don't know what exactly you are asking, because you are not clear in your question. But according to my thinking you want to know the difference.
Update query edit or update the data in the database. Like this
update table_name
set 'name'=something
where 'id'='some_id'
for more examples and practice go HERE
Insert insert query is just making a new data entry in the database in a table with a unique id, precisely.
HERE is the link for insert example.

Is there a way to add a row only if it doesn't already exist? [duplicate]

This question already has answers here:
"Insert if not exists" statement in SQLite
(4 answers)
Closed 9 years ago.
Using PHP PDO with SQLite, I can write a PDO call to check if a certain row exists (by checking for the primary key) in the table, and then if it doesn't, write another PDO call to create the row. But I feel like it should be somehow possible to do in one command… similar to the "CREATE TABLE IF NOT EXISTS". Is there anything like "INSERT ROW IF NOT EXISTS"?
Use
INSERT OR IGNORE INTO ...
where your table has some constraint (such as a PRIMARY KEY column) that will cause a conflict when a row is attempted to be inserted again.
Reference: http://www.sqlite.org/lang_conflict.html

Remove Duplicate entry ''' for key '' warning

I have a unique key set for a mysql database row so not to insert duplicate entries on a form submit. That works fine, but if there's a duplicate entry the page doesn't load. Instead the user receives the warning: Duplicate entry ''' for key ''
How do I go about turning that error off and loading the page even if there is a duplicate key, while still using the unique key on the row? I tried setting error report to off, but that didn't work.
mysql_query("INSERT INTO user
(formemail,UserIP,Timestamp,LP) VALUES('$email','$userip',NOW(),'$lp') ")
or die(mysql_error());
You need to change your SQL insert to use INSERT ... ON DUPLICATE KEY UPDATE Syntax so that the error isn't generated in the first place.
Don't try to hide the symptom, treat the problem.
Also, I must point out that the mysql library is being deprecated and should not be used for new code, you should, at the least, use mysqli or, preferably PDO. There is a good tutorial on PDO here if you are interested in learning.

MySQL Ignore is not working

I am trying to prevent duplicates from occuring using the following query, but it doesnt seem to work. Please could you tell me what the problem is?
INSERT IGNORE INTO Following SET `followingUserID` = '$accountIDToFollow', `followerUserID` = '$accountID'
INSERT IGNORE INTO
Following (`followingUserID`,`followerUserID`)
VALUE
('$accountIDToFollow','$accountID')
You were doing an UPDATE format before
If you are trying to do an update this is how it works
UPDATE followingUserID
SET
followingUserID = '$accountIDToFollow',
WHERE
followerUserID = '$accountID';
Of course you want to replace the were clause with the correct condition you want to do
As per MYSQL documentation,
If you use the IGNORE keyword, errors
that occur while executing the INSERT
statement are treated as warnings
instead. For example, without IGNORE,
a row that duplicates an existing
UNIQUE index or PRIMARY KEY value in
the table causes a duplicate-key error
and the statement is aborted. With
IGNORE, the row still is not inserted,
but no error is issued.
It means, the IGNORE does not prevent any record duplicate. You will have to put Unique constraints on your given fields.

mysql continue on errors

I have a PHP foreach loop and a mysql insert statement inside of it. The loop inserts data into my database. I've never ran into this issue before but what I think is happening is that the insert dies (I do not have an "or die" statement after the insert) when it reaches a duplicate record. Even though there may be duplicate records in the table, I need this to just continue. Is there something that I need to specify to do this?
I'm transferring some records from one table to another. Right now, I have 20 records in table #1 and only 17 in table #2. I'm missing 3 records but only one of those are duplicated which violates the constraint on the table. The other two records should have been added. Can someone give me some advice here?
What's happening is that PHP is throwing a warning when the mysql insert fails and stopping on that warning. The best way to accomplish your goal is:
Create a custom exception handler
Set PHP to use the exception handler for warnings.
Wrap the insert attempt into a try / catch
When you catch the exception / warning, either log or output the mysql error but continue script execution.
This will allow your script to continue without stopping while at the same time explaining to you the problem.
One way around this would be to simply query the database for the record that you're about to insert. This way, your series of queries will not die when attempting to insert a duplicate record.
A slightly more efficient solution would be to query for [i]all[/i] of the records you're about to insert in one query, remove all the duplicates, then insert the new ones.
Do you insert multiple rows with one INSERT statement?
INSERT INTO xyz (x,y,z) VALUES
(1,2,3),
(2,3,5),
(3,4,5),
(4,5,6)
Then you might want to consider prepared statements
...or adding the IGNORE keyword to your INSERT statement
INSERT IGNORE INTO xyz (x,y,z) VALUES
(1,2,3),
(2,3,5),
(3,4,5),
(4,5,6)
http://dev.mysql.com/doc/refman/5.0/en/insert.html says:
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead
You can still fetch the warnings but the insertion will not be aborted.
Not a good way cause you should figure out whats wrong, but to just prevent it from dieing try adding # in front of the function
#mysql_query = ...
INSERT INTO FOO
(ID, BAR)
VALUES(1,2),(3,4)
ON DUPLICATE KEY UPDATE BAR=VALUES(BAR)

Categories