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
Related
I have one form let's say bill form. i have 3 tables.
bill (billId->primary key)
billdetails (billdetailId->primary key, billId-> foregin key)
fintran (finalId -> primary key, there are total 10 inputs in form.
On submit first 5 input should go in bill table and other 5 input should go in bill details. And all will go in final table. i used below query for this.
BEGIN;
$sql = mysqli_query($conn,"INSERT INTO `bill`(`societyId`, `unitId`, `memberId`, `area`, `arrear`, `invoiceNumber`, `invoiceDate`, `dueDate`, `billingPeriod`, `total`, `interestOnArrear`, `totalDue`, `email`, `penalty`, `principalArrears`, `interestArrears`, `advancedAdjusted`, `netPending`) VALUES ('".$societyId."','".$unitId."','".$memberId."','".$area."','".$arrear."','".$invoiceNumber."','".$invoiceDate."','".$dueDate."','".$billingPeriod."','".$total."','".$interestOnArrear."','".$totalDue."','".$email."','".$penalty."','".$principalArrears."','".$interestArrears."','".$advancedAdjusted."','".$netPending."')");
$memo = $_REQUEST['memo'];
$charge = $_REQUEST['charge'];
$sql= mysqli_query($conn,"INSERT INTO `billdetail`(`biilId`, `memo`, `charge`) VALUES (LAST_INSERT_ID(),'".$memo."','".$charge."')");
$sql= mysqli_query($conn,"INSERT INTO `fintran`(`societyId`, `docId`, `docTypeName`, `docDate`, `unitId`, `unitName`, `memberId`, `memberName`, `comboId`, `ledgerId`, `ledgerName`, `debit`, `credit`, `netValue`) VALUES ('".$societyId."',LAST_INSERT_ID(),'bill','','".$unitId."','".$unitId."','".$memberId."','".$memberId."','','".$charge."','','','','')");
COMMIT;
after insert data i want billId i.e primary key of bill table in both billdetails and fintran table. but with this query i'm able to get this in only billdetail table. In fintran table i get primary key of billdetail table. please help me with the same.
No, you can't insert into multiple tables in one MySQL command. You can however use transactions.
Check this : MySQL Insert into multiple tables? (Database normalization?)
I have two tables cw_users and ref_users, both have a column named id.
I'm using ISAM so can't use a foreign key.
So now I wanted to insert id from cw_users into ref_users if it didn't exist.
This is what I did, but didn't help:
$id = $_SESSION['id'];
$ref_code=md5($id);
mysql_query("INSERT INTO ref_users (id) VALUES ('$id') WHERE NOT EXISTS (SELECT FROM cw_users where id='$id')");
The correct syntax is INSERT IGNORE INTO
INSERT IGNORE INTO ref_users (id)
VALUES ('$id')
It will insert if the value does not exist, and ignore the statement if it does.
Note that this will only work if id is the Primary Key
EDIT: It seems from your comments that you would be much better off using ON DUPLICATE KEY UPDATE.
Try this query
INSERT INTO ref_users(id, ref_code)
VALUES ('$id', '$ref_code')
ON DUPLICATE KEY UPDATE
ref_code = '$ref_code'
...WHERE NOT EXISTS (SELECT id FROM ...
why not run normal insert, it will fail if row exists?
Your query is
"INSERT INTO ref_users (id) VALUES ('$id') WHERE NOT EXISTS (SELECT FROM cw_users where id='$id')"
You can't use were case in insert query . you can use normal insert .
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
I have this PHP/MySQL script which adds a comment into my DB:
$SQL = "INSERT INTO blog_comments (article_id, author_name, comment, path, posted, status) ";
$SQL .= "VALUES (:article_id, :name, :comment, :next_path, Now(), 'Live');";
$STH = $DBH->prepare($SQL);
$STH->bindParam(':article_id', $article_id);
$STH->bindParam(':name', $name);
$STH->bindParam(':comment', $comment);
$STH->bindParam(':next_path', $next_path);
$STH->execute();
Is there any way to modify this so that it doesn't insert the same [author_name], [article_id] and [comment] into this table? I know it's possible for one column by adding UNIQUE to my table, but not sure about multiple columns.
you can add a UNIQUE constraint for multiple columns
CREATE TABLE
(
.....
CONSTRAINT tab_uq UNIQUE (author_name, comment)
)
or by altering the existing table,
ALTER TABLE myTable ADD UNIQUE (author_name, comment);
call those columns as composite primary key..
that way, they will have a unique entry.
You can make a unique key of multiple fields
I guess you could check the db for a result before inserting data
you can also check INSERT ... ON DUPLICATE KEY UPDATE dev.mysql.com
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.