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
Related
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.
For example:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE it will ignore the error, but it still won’t update.
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
Check out REPLACE:
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.
Example:
REPLACE INTO `tablename` (`id`, `name`, `age`) VALUES (1, "A", 19)
When using batch insert use the following syntax:
INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
name = VALUES (name),
...
Any of these solution will work regarding your question:
INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
or
INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
or
REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
Try this:
INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'
Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.
In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);
And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);
Note, just make sure to delete first all the data that has the same name and age value across the other rows.
DELETE table FROM table AS a, table AS b WHERE a.id < b.id
AND a.name <=> b.name AND a.age <=> b.age;
After that, it should trigger the ON DUPLICATE event.
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name = VALUES(name), age = VALUES(age)
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):
INSERT live-db.table1
SELECT *
FROM test-db.table1 t
ON DUPLICATE KEY UPDATE
ColToUpdate1 = t.ColToUpdate1,
ColToUpdate2 = t.ColToUpdate2,
...
As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.
No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.
When using SQLite:
REPLACE into table (id, name, age) values(1, "A", 19)
Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).
In case, you want to keep old field (For ex: name). The query will be:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name=name, age=19;
In my case i created below queries but in the first query if id 1 is already exists and age is already there, after that if you create first query without age than the value of age will be none
REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19
for avoiding above issue create query like below
INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19
may it will help you ...
Following are some of the possible approaches:
Using INSERT INTO
The INSERT statement allows you to insert one or more rows into a table
First, specify the table name and a list of comma-separated columns inside parentheses after the INSERT INTO clause.
Secondly, put a comma-separated list of values of the corresponding columns inside the parentheses following the VALUES keyword.
INSERT INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");
Using INSERT INTO with WHERE NOT EXISTS clause
INSERT INTO table_name (column_name_1, column_name_2, column_name_3)
SELECT * FROM (SELECT "col_value_1", "col_value_2","col_value_3") AS tmp_name
WHERE NOT EXISTS (
SELECT column_name2 FROM table_name WHERE column_name = "sample_name"
) LIMIT 1;
Using REPLACE INTO
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.
REPLACE INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");
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'm trying to update a row or insert a new one if it exists. If there's an UPDATE I just like to update the "updated" column with the current timestamp otherwise "added" AND "updated" get the same value (timestamp)
//1385982893 is from PHP with time() cause it's needed elsewhere too
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), added = values(added),updated = 1385982893
ID is the primary key. code is UNIQUE
The problem is that "added" always gets updated with the current timestamp (like updated)
You just need to to remove the added = values(added) and it won't get updated:
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code),updated = 1385982893
Then do not set added in Update
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), updated = 1385982893
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 .
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