There is my code:
$sql = "INSERT INTO item SET
player = '$player',
amount = '$amount',
item = '$item',
allowed = '$allowed' ON DUPLICATE KEY UPDATE
amount = amount + $amount";
When I executing this query, in database creates new row despite the fact that it already exists...
Thanks for help.
In the comments, you say there are no keys on the table. That's a problem. You're asking the database ON DUPLICATE KEY UPDATE, but without a UNIQUE KEY, it has no idea what a DUPLICATE KEY is.
You need to add a UNIQUE KEY (or a PRIMARY KEY) on the field(s) you don't want being duplicated.
The syntax is not correct, this corrected version:
$sql = "INSERT INTO item SET
player = '$player',
amount = '$amount',
item = '$item',
allowed = '$allowed'
ON DUPLICATE KEY UPDATE
amount = `amount` + '$amount' ";
Other factor depends on your table structure and the key
I would do it like that:
$sql = "INSERT INTO DBNAME.item (player, amount, item, allowed)
values('$player', '$amount', '$item', '$allowed')
ON DUPLICATE KEY UPDATE
amount = amount + values(amount);";
Related
I have used the following code to Insert/update MySQL table but its not doing anything when duplicate record exists I used ON Duplicate Key update. the code works great to insert but i want to update if description is differ from the source so i added this ON DUPLICATE KEY UPDATE PURCHASE_DESCRIPTION = VALUES ('$pdesc')" but it not inserting also not updating
mysqli_query($con,
"INSERT INTO table_name
(STOCK_NO, PURCHASE_DESCRIPTION, SALES_DESCRIPTION, itemId, itype, ITEM_DESCRIPTION, uOfM, uConvFact, poUOfM, lead, suplId, suplProdCode, minLvl, maxLvl, ordLvl, ordQty, unitWgt, sales, bomRev, makebuy) VALUES
('{$itemid}', '{$pdesc}', '{$sdesc}', '{$itemId}', '{$itype}', '{$itemdsc}', '{$uOfM}', '{$uConvFact}', '{$poUOfM}', '{$lead}', '{$supplId}', '{$suplProdCode}', '{$minLvl}', '{$maxLvl}', '{$ordLvl}', '{$ordQty}', '{$unitWgt}', '{$sales}', '{$bomRev}', '{$makebuy}')
ON DUPLICATE KEY UPDATE PURCHASE_DESCRIPTION = VALUES ('$pdesc')"
);
//STOCK_NO is the primary Key
Your SQL is incorrect. Take a look:
mysqli_query($con,
"INSERT INTO table_name
(STOCK_NO, PURCHASE_DESCRIPTION, SALES_DESCRIPTION, itemId, itype, ITEM_DESCRIPTION, uOfM, uConvFact, poUOfM, lead, suplId, suplProdCode, minLvl, maxLvl, ordLvl, ordQty, unitWgt, sales, bomRev, makebuy) VALUES
('{$itemid}', '{$pdesc}', '{$sdesc}', '{$itemId}', '{$itype}', '{$itemdsc}', '{$uOfM}', '{$uConvFact}', '{$poUOfM}', '{$lead}', '{$supplId}', '{$suplProdCode}', '{$minLvl}', '{$maxLvl}', '{$ordLvl}', '{$ordQty}', '{$unitWgt}', '{$sales}', '{$bomRev}', '{$makebuy}')
ON DUPLICATE KEY
-- HERE --
UPDATE PURCHASE_DESCRIPTION = '{$pdesc}'
");
Another option is UPDATE PURCHASE_DESCRIPTION = VALUES(PURCHASE_DESCRIPTION)
You can read more here: http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
I am using ON DUPLICATE UPDATE on my query, some of the result didn't store it. I tried all the possible way, but those still remain the same. here are the database picture.
Those NULL, is the row which didn't store successfully; the result should be 1 instead of NULL.
if($remark){
$query3 = "INSERT INTO `audit_section_remarkrecord` SET remark = '$remark', form_details_subquestion_id = '$form_details_subquestion_id', form_details_section_id = '$form_details_section_id', audit_section_no = '$audit_no' ON DUPLICATE KEY UPDATE
form_details_section_id = '$form_details_section_id' , remark = '$remark'";
$result3 = $db->query($query3);
$query4 = "UPDATE `remarkrecord_update_details` SET form_details_section_id = '$form_details_section_id', userlog = '$user_staff', ipaddress = '$ip' WHERE form_details_subquestion_id = '$form_details_subquestion_id' AND audit_section_no = '$audit_no' ";
$result4 = $db->query($query4);
}else{
}
}
Table Structure
Try changing one of your columns you are inserting value to primary key or add UNIQUE constraint to the column.
ALTER TABLE audit_section_remarkrecord ADD UNIQUE KEY (your column);
As there is currently only a unique key on the Primary Key, an auto-increment, you are going to have difficulty generating a unique key clash on an insert on duplicate key update (IODKU). Therefore, some other unique key needs to be created (even a composite), that will trigger the clash of a unique key and allow IODKU to work as expected.
I'm trying to check to see if there is a duplicate record and then either insert or update. I have made to_number field (which is a phone number) a UNIQUE field. There is a PRIMARY KEY "id" that is auto-increment. Not sure if this is what's causing the headache. Here is my code and then below that the error.
$sql = "INSERT INTO DC**** (id, dcsrep, name, to_number, amount, date, digits, details)
VALUES ('', '$dcsrep', '$name', '$to_number', '$amount', '$date', '$digits', '$details')
ON DUPLICATE KEY UPDATE dcsrep = values($dcsrep), name = values($name), to_number = values($to_number), amount = values($amount), date = values($date), digits = values($digits), details = values($details)";
Error: INSERT INTO ***Auth (id, dcsrep, name, to_number, amount, date, digits, details) VALUES ('', 'notreal#notreal.com', 'Test Johnson', '+15555551212', '150.00', '2015-12-16', '1234', 'Testing again.') ON DUPLICATE KEY UPDATE dcsrep = values(notreal#notreal.com), name = values(Test Johnson), to_number = values(+15555551212), amount = values(150.00), date = values(2015-12-16), digits = values(1234), details = values(Testing again.)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#notreal.com), name = values(Test Johnson), to_number = values(+15555551212),' at line 2
From the documentation:
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement.
But you are not providing the column names, you are providing the values again.
So, either you provide the column name again:
ON DUPLICATE KEY UPDATE dcsrep = values(dcsrep), ...
or you skip the VALUES() function and provide the value:
ON DUPLICATE KEY UPDATE dcsrep='$dcsrep', ...
Note:
There is no reason to update all columns when you only want to update the phone number. If all other fields stay the same anyway, just update the column that holds the phone number.
i have this code that work well.
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses";
mysql_query($sql);
i put this into this page :
> http://localhost/msigilearnv2/tools/calender/copy_database.php
when first runs the page it will copy table from at_courses to phpc_events..
when second runs.. how i can prevent duplication data? because it keep add same data. i put ignore but still not works
I am sharing you one of the alternative. Lets say you have a record in the database and cid value is '1'.
First step check the value if it is already exists in the database.
$sql = "SELECT cid FROM phpc_events";
$returned = mysql_query($sql);
if(mysql_num_rows($returned) > 0){
while( $row = mysql_fetch_array($returned) ){
$PhpcArray [] = $row; //stores result returned in array to ensure less resource used
}
}
$sqlC = "SELECT anotherId FROM at_courses";
$returnedC = mysql_query($sqlC);
if(mysql_num_rows($returnedC) > 0){
while( $rowC = mysql_fetch_array($returnedC) ){
if( in_array( $rowC['anotherId'], $PhpcArray ) ){
// do nothing as id is already exists in phpc_events
}
else{
// do insertion because id in at_courses is not exist yet in phpc_events
}
}
}
Hope this helps.
Another alternative.
By the way you can also try this query if it matches your column as I don't know how your table structure looks like
SELECT cid
FROM at_courses
WHERE cid NOT IN (
SELECT cid FROM phpc_events
)
This query will return the cid in the at_courses which is not yet occur in phpc_events. Then do the insertion for those cid returned from at_courses table.
Thank you.
My MySQL isn't great, but you will need to do something the like:
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses"
left join phpc_event on phpc_events.cid = at_courses.cid //(and others you want matched for dups
where phpc_events.cid is null
;
If you have a primary key in your tables, you can replace INSERT with REPLACE. This will insert new records or replace them if the primary key already exists.
alter the table by adding UNIQUE constraint
ALTER TABLE phpc_events ADD CONSTRAINT your_field UNIQUE (cid, owner, subject, description, ctime)
I was trying to upload a csv file to update a table in my db, but also wanted to prevent duplication. Initially a single DUPLICATE worked but when i added the second condition it didn't work.
I got "Duplicate entry '1' for key PRIMARY". How can i achieve my aim.
thanks for your help.
$sql = "INSERT INTO biodata (student_number, fname, lname, course_name, level)
VALUES('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]')
DUPLICATE KEY UPDATE student_number = student_number
AND course_name = course_name";
mysql_query($sql) or die (mysql_error());
Replace AND with comma , in the UPDATE part.
Use the VALUES() syntax to refer to the values passed.
Also, you don't need to update the Primary or Unique Key (that activated the ON DUPLICATE KEY UPDATE):
$sql = "
INSERT into biodata
(student_number, fname, lname, course_name, level)
VALUES
('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]')
ON DUPLICATE KEY UPDATE
--- student_number = VALUES(student_number),
--- removed
fname = VALUES(fname),
lname = VALUES(lname),
course_name = VALUES(course_name),
level = VALUES(level)
" ;
What the above code does:
If the INSERT fails (there is already a student with this student_number you are trying to Insert), the UPDATE is activated and the 4 other fields are updated.
It's your choice which fields to update. If you want to update for example, only the course_name field, just keep that line and remove the rest.
I think you misunterstood the meaning of the
ON DUPLICATE KEY UPDATE
construct. IT does not define a condition for when a duplciate key occurs, but the solution if such an event hast happened. So you can modify the key in some way, that does not result in a duplicate.
The conditions for duplicates is defined via the indexes and (primary) keys within the table definition. So according to your code above, you would add a unique key over student_number and course_name in the table definition.
For more references take a look at the docu.