Update and Insert in a Single Query - php

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

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)

How can I copy a data inserted from table to be inserted in another table?

I have two tables
transaction_tbl
order_tbl
I inserted data in transaction_tbl with a primary key autoincrement transaction_no.
Now, I need to insert data in order_tbl with columns
orderitem_no(AI, PK),
transaction_no,
product_sku,
quantity
How can I sync the transaction_no from transaction table in one process?
I just assign data to variables then:
My current code is
$sql0 = "INSERT INTO transaction_tbl (transaction_no, transaction_date, customer_name) VALUE ('', now(), '$customer_name');";
$x=0;
while ($x!=5){
$sql1 = "INSERT INTO order_tbl
(orderitem_no, transaction_no, product_sku, quantity)
VALUE ('', '', '$product_sku', '$quantity');";
$x=$x+1;
}
Nothing next. Sorry, Im super lost.
Im planning to run ths sql's in one process.
transaction_no in transaction_tbl is auto increment.
I have fk_trans_no in order_tbl.
And then I totally lost. orderitem_no is auto increment but what will I do to the transaction_no?

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

PHP/SQL After insert value to table and set one value as unique, no more values can be inserted

I try to create normalized db.
When I insert values FIRST time, everything is working perfectly, but (I think cause of set values as UNIQUE) it do not want to add.
This is my queries ( I can show database as well if needed )
$query = "INSERT INTO userMore (userEmailG, userGenderG, userAboutG, userBirthdayG, userLanguageG) values ('$userEmailG','$userGenderG', '$userAboutG', '$userBirthdayG', '$userLanguageG');";
$query .= "INSERT INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT INTO dvlaInfoMore (sixMonthRate, twelveMonthRate, wheelPlan, revenueWeight, typeApproval, taxStatus, taxed, taxDetails, mot, motDetails) values ('$sixMonthRate', '$twelveMonthRate', '$wheelPlan', '$revenueWeight', '$typeApproval', '$taxStatus', '$taxed', '$taxDetails', '$mot', '$motDetails');";
$query .= "INSERT INTO dvlaInfoBasic (id_uDInfoM, plateNumber, make, model, yearOfManufacture, cylinderCapacity, dateofFirstRegistration, co2Emissions, fuelType, colour, vin, transmission)
values (LAST_INSERT_ID(), '$plateNumber', '$make', '$model', '$yearOfManufacture', '$cylinderCapacity', '$dateofFirstRegistration', '$co2Emissions', '$fuelType', '$colour', '$vin', '$transmission');";
$query .= "INSERT INTO userLocation (latitude, longitude, postCode) values ('$latitude', '$longitude', '$postCode');";
$query .= "INSERT INTO userChioce (doWithCar) values ('$doWithCar');";
$query .= "INSERT INTO userStatus (userIdG) values ('$userIdG');";
$query .= "INSERT INTO userMain (userIdG, id_uB, id_uDInfoB, id_uChoice, id_uLoc, id_uStat) values ('$userIdG', (SELECT id_uB FROM userBasic WHERE userEmailG='$userEmailG'), (SELECT id_uDInfoB FROM dvlaInfoBasic WHERE plateNumber ='$plateNumber'), LAST_INSERT_ID(), (SELECT id_uLoc FROM userLocation WHERE postCode='$postCode'),(SELECT id_uStat FROM userStatus WHERE userIdG='$userIdG'))";
So, first time userMore added then userBasic then dvlaInfoMore then dvlaInfoBasic and so one
I set in userBasic column userNameG as UNIQUE, so IF inserted email which already exist, it do not want to go further, BUT if not, everything added correctly.
ALL what I want that it will continue inserting different cars and then by using existing email display result in table userMain.
P.S. if I try to add different car from by using same email address it doesn't work., basically do not add anything.
As you suspected yourself, INSERT with an existing key defined as UNIQUE will fail.
One workaround is to use the REPLACE INTO statement instead of INSERT (see manual).

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

Categories