How to replace some values if a user already exists? - php

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)

Related

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

Update and Insert in a Single Query

I have a table which contains pageid, department, position and active. While updating, I have to update active column if pageid is already exists, if not I will insert a new row with the pageid.
I am getting pageid values through checkbox and my update query is like this
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
department=VALUES(".$department."),
position=VALUES(".$position."),
active=VALUES(1)";
But everything is getting inserted twice in this case.
Where I am doing wrong? Can somebody guide me?
This should probably work for you:
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id),
active=VALUES(1)";

mysql: store a DEFAULT value as a variable

I am wondering how to store the value of a primary key, auto-incremented by "DEFAULT" so that I can insert it as a value in another table row.
So far I have:
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
I need the specific value created by "DEFAULT" to be stored, so that I can insert it into another table's row. How do I do this with either PHP or MySQL?
You don't. You use last_insert_id() to retrieve it AFTER you've performed the first insert.
INSERT INTO foo (bar) VALUES (baz)
SELECT #id := last_insert_id();
INSERT INTO other (id, parent) VALUES (null, #id)
INSERT INTO yetanother (id, parent) VALUES (null, #id)
Note that last_insert_id() is not smart and will return the id of the LAST insert you did. If you do two inserts, and then try to get the ids, you'll get the id of the second (last) insert.
MySQL:
You can find this in MySQL by using the LAST_INSERT_ID() function, as the last insert ID will be returned that you inserted for an AUTO_INCREMENT value.
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
sql2 = "INSERT INTO records (
sale_id,
customer_name,
other_info)
VALUES (
LAST_INSERT_ID(), <-------- correct sales_id
'$name',
'$info');

mysql table createing new row instead of updating

Instead of finding that a row exists where 'bookName' equals 'bookName' and just updating, it creates a brand new row. What is wrong with my command? thanks!
$query = mysql_query(
"INSERT INTO custombookinfo (userId, sendToAddress, work, caseStudies, url, entryPoint, date, bookName)
VALUES ('$userId', '$emailAddress', '$work', '$caseStudies', '$url', '$entryPoint', '$date', '$bookName')
ON DUPLICATE KEY UPDATE bookName = 'bookName'"
);
the INSERT query is correct but I think you have failed to define UNIQUE constraint on column bookName. Execute the following statement:
ALTER TABLE custombookinfo ADD CONSTRAINT tb_uq UNIQUE (bookName);
Depending on what you want to be UNIQUE in the table, you should create an index (PRIMARY or UNIQUE) for whether user_id, or bookName.
More details about INSERT ... ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

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