On duplicate key update not working - php

I try to use on duplicate key update in my query but it still duplicate some value.
My query is like this:
$insert=mysqli_query($conn,"insert into tbl_staffdistribution(db_user,db_name,db_responsible,db_date)values('$user','$name','$responsible','$formatteddatetimein') on duplicate key update db_user='$user',db_name='$name',db_responsible='$responsible',db_date='$formatteddatetimein'")or die(mysqli_error($conn));
I have db_id in my database is a primary key auto increment.
The problem is that I have a duplicate value in my database and that should not happen How can I solve this problem ??

In order to do this. you should be having a unique key within your table so that you can use it for on duplicate key update as such. The unique key can be your primary or some other field from your table. You can do something like this within your query:
ON DUPLICATE KEY UPDATE someID = VALUES(someID)
A clear cut explanation from MySQL.

Related

Mysql duplicate row prevention [duplicate]

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

Mysql on duplicate key update is not working

I am trying to use following code segment to update the database when inserting duplicates. But instead of updating it still inserting duplicate rows. Why?
$import = "INSERT INTO data(Product,Courier,Received_Date,Acc_No,Received_By,Delivered_Date,Month,Year,Bill_Run,Dispatch_Type,Status,Bounce_Code) values('$data[0]','$data[1]','$Received_Date','$data[3]','$data[4]','$Delivered_Date','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]') ON DUPLICATE KEY UPDATE Acc_No = '$data[3]'
For 'ON DUPLICATE KEY UPDATE' to work you need a unique or primary key constraint on a table. Only if you would get a key conflict on inserting the 'ON DUPLICATE KEY UPDATE ' code is executed.
Add primary key constraint on the table:
ALTER TABLE table_name add primary key(col_name)
add Unique Key in column name table
enter link description here
enter link description here
enter link description here

Insert or Update if duplicate based on unique index

Here is what I want to do. Insert if the unique index (code) doesn't exist in the table already. If it exists then simply update the row.
I can't use primary key because it is Auto Increment ID. Here is the code
$sql="INSERT INTO codes (code,registration,country)
VALUES ('$war','$regi','$country') ON DUPLICATE KEY UPDATE code='$war', registration='$regi', country='$country'";
But it doesn't work because I think it is checking for duplicate primary key. So when I try to insert the row in which the value of column code is same as previous row I get Duplicate entry 'xxx' for key 'code' error. So how to make this work for unique index code ?
Ahmar
ON DUPLICATE KEY UPDATE works with UNIQUE indexes as well as PRIMARY KEY values. Try setting one of the values you are trying to update to be UNIQUE on your database table.
All you have to do is set code to be a unique index. Then, anytime you try to do an insert where code matches it will update instead.
Alter this code as needed
alter table `table` add unique index(`code`);
You are correct, having a primary key on your table will not allow you to insert duplicate key values.
In the past, I have used something like this:
SELECT COUNT(*)
FROM codes
WHERE code = '$war'
Then if the count is > 0, you know there's a duplicate and you do:
UPDATE codes
SET registration = '$regi', country = '$country'
WHERE code = '$war'
Otherwise you do:
INSERT INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
However, if we assume you're using MySQL, you might be able to make use of either INSERT IGNORE or REPLACE.
If you use:
INSERT IGNORE codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
The values will be inserted if the code does not already exist. If the code does exist, no record is inserted and MySQL will silently discard the statement without generating an error.
I think what you probably want is this:
REPLACE INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
REPLACE INTO behaves just like INSERT INTO if the record is new. But if the primary key is duplicated, it will perform an UPDATE instead.
Again, INSERT IGNORE and REPLACE INTO are for MySQL only.
Reference: http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm

MYSQL ON DUPLICATE KEY UPDATE didn't update

I have a mysql on duplicate key statement.
mysql_query("INSERT INTO statistics (classify, apply) VALUES ('$classify', 1)
ON DUPLICATE KEY UPDATE apply = apply + 1");
id classify apply
1 A 1
but it didn't update the existing row and it keep add another row, Where is the problem?
It's probably the column classify is not unique. You need to have a UNIQUE field in the table to make ON DUPLICATE KEY UPDATE work. If you have not set one, you can execute this statement below.
ALTER TABLE statistics ADD CONSTRAINT tb_uq UNIQUE (classify)
ON DUPLICATE KEY will update a row only when you try to insert a record that would throw a duplicate keys error (like the name states). So this happens only if you are a using a unique key or a primary key for that column. It looks like you didn't created a unique key for the classify column.

ON DUPLICATE KEY insert new row instead of updating

I have a little problem.
This is the SQL code I get:
INSERT INTO matches (match_id, league_name, league_id, test_one)
VALUES (866860, 'Portugal',1,'testing')
ON DUPLICATE KEY
UPDATE league_name =
CASE match_id
WHEN 866860
THEN 'Portugal' END,
league_id =
CASE match_id
WHEN 866860
THEN 1 END,
test_one =
CASE match_id
WHEN 866860
THEN 'testing' END
The problem is, that it always insert a new row instead of updating the existing one.
Is it because I need to make the "match_id" as AUTO_INCREMENT or anything else (at the moment, my "id" field is AUTO_INCREMENT)
AUTO_INCREMENT is irrelevant here. But ON DUPLICATE KEY requires a key. More specifically, a unique key, such as primary key or a unique index.
Given the column names, I suspect that match_id fails to be a primary key.
Update: You also write a complicate set of CASE ... END constructs. Have a look at the VALUES() function.
You are telling your database to update information "ON DUPLICATE KEY"; if none of the other fields are UNIQUE keys, the database will insert a new row.
You can either SELECT the id before this query (or making it a sub-query) or add another key to this table that will result in a unique value for each row. I don't know about your schema, but you might be able to create a multi-part key which spans match_id and league_id.

Categories