On Duplicate Key Error - php

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.

Related

How to replace some values if a user already exists?

I don't know how to replace some data if a "user" already exists.
I've tried ON DUPLICATE KEY UPDATE but I came to realize that this will probably not work. Because the only value that isn't updated is 'user' in my code but the other 3 values are constantly updated every 5 minutes.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES ('$Name'), world = VALUES ('$World'), status = VALUES ('$status')
The idea is if, for example, user "bob" already exists update his other 3 values bot, world, status, instead of creating a new line and so on.
Edit: this is how I have it setup in Mysql
The argument to VALUES() should be the name of a column, not a string. You put the name of the column that you would have inserted into.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES (bot), world = VALUES (world), status = VALUES (status)

ON Duplicate Key update doesn't work

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

updating the mysql table if query store_num exits

Everyone!
I am working on application using php and mysql. Basically, initially, I am inserting the new data entries using html form into the database where store# is my primary key. For now I can not update the existing store# (as its my primary key) and get a message saying "Duplicate entry for store 967 (example)".
I want to update the "store" table if entery exists. Here is my code posted below, but I am getting another error message
Error: 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 '['967'],address=['500 kipling avenue 1'],dsm_name=['n/a'],phone=['416-967-' at line 1
I am not sure if I am using the if conditional at right spot.
**$sql = "INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
$mysqli_query = "SELECT * from 'stores' WHERE $store = 'store_num'";
if ($mysqli_query == TRUE){
$sql = "UPDATE `stores` SET `store_num`=['$store'],`address`=['$address'],`dsm_name`=['$dsm'],`phone`=['$phone'],`router_type`=['$router'],`high_speed_pri`=['$highspeedpr'],`dsl_log`=['$dsllog'],`dsl_pass`=['$dslpas'],`secondary_conn`=['$secondary_conn'],`sec_dsl`=['$secdsl'],`sec_pass`=['$sec_pass'] WHERE 1";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>**
Replace instead of Insert
Since your update statement includes all the same fields as Insert, you can simply use a REPLACE Statement. As stated on the linked documentation:
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. See
Section 13.2.5, “INSERT Syntax”.
So, changing the code to the following should work:
$sql = "REPLACE INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
Error Reason
Your problem is with the syntax in the update statement. What is store_num, is it a number or a string?
You should change your syntax to not include the square brackets in the actual mysql query.
If $Store is Number:
=['$store'], to =$store
If $Store is Text:
=['$store'], to ='$store'
Final Recommendation
Even better though will be use prepared statements which are also secure and avoid against SQL injection attacks.
You can do this logic with a single query, using on duplicate key update. First, you have to define store_num as a unique key, if it is not already a unique or primary key:
CREATE UNIQUE INDEX idx_stored_storenum on stores(store_num);
Then use this insert:
INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`,
`dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`
)
VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr',
'$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')
ON DUPLICATE KEY UPDATE address = values (address),
dsm_name = values(dsm_name),
. . .
sec_pass = values(sec_pass);
Your particular problem is the square braces, which MySQL doesn't recognize.

ON DUPLICATE UPDATE - Does not work

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);";

Double DUPLICATE KEY UPDATE entry error

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.

Categories