MySQL INSERT else if exists UPDATE - php

I'm building a config table with two columns, config_name and config_value. I insert multiple rows in one statement:
INSERT INTO ".$dbPrefix."config (config_name,config_value) VALUES
('domain','$domain'),
('forest_root','$fr_if'),
('userGroup','$userGroup'),
('adminGroup','$adminGroup');
The config_name column is a primary key. How would I change this statement to automatically update the config_value if the config_name already exists?

You could try this syntax:
INSERT INTO table (field) VALUES (value) ON DUPLICATE KEY UPDATE field=value
Docs can be found here.

You're trying to do an upsert, and I think this may help:
http://database-programmer.blogspot.com/2009/06/approaches-to-upsert.html

Related

Insert values into mysql with foreign key constraints

I have 2 tables as : 'spen_recipe' and 'spen_recipe_type' as shown below
I want to insert the values into spen_recipe and spen_recipe_type simultaneously based on the pk and fk constraints.
Please suggest me the query.
This is what i have tried:
insert into spen_recipe
(`user_id`,`recipe_name`,`recipe_title`,`recipe_type`,`cooking_time`,`preparation_time`,`serving_to`,`recipe_desc`,`recipe_photo`,`created_at`,`modified_at`,`published_at`)
values
('2','recipe2','title2',(select `recipe_type_id` from spen_recipe_type),'20','30','4','desc1','image1','2016-11-05 11:21:43','2016-11-05 11:22:43','2016-11-05 11:21:43');
But need suggestion on how to proceed after select recipe_type_id from spen_recipe_type, cause both the table has null values in the columns, both are empty.
Should spen_recipe_type or spen_recipe be first inserted?

Insert or Update if duplicate based on unique index

Here is what I want to do. Insert if the unique index (code) doesn't exist in the table already. If it exists then simply update the row.
I can't use primary key because it is Auto Increment ID. Here is the code
$sql="INSERT INTO codes (code,registration,country)
VALUES ('$war','$regi','$country') ON DUPLICATE KEY UPDATE code='$war', registration='$regi', country='$country'";
But it doesn't work because I think it is checking for duplicate primary key. So when I try to insert the row in which the value of column code is same as previous row I get Duplicate entry 'xxx' for key 'code' error. So how to make this work for unique index code ?
Ahmar
ON DUPLICATE KEY UPDATE works with UNIQUE indexes as well as PRIMARY KEY values. Try setting one of the values you are trying to update to be UNIQUE on your database table.
All you have to do is set code to be a unique index. Then, anytime you try to do an insert where code matches it will update instead.
Alter this code as needed
alter table `table` add unique index(`code`);
You are correct, having a primary key on your table will not allow you to insert duplicate key values.
In the past, I have used something like this:
SELECT COUNT(*)
FROM codes
WHERE code = '$war'
Then if the count is > 0, you know there's a duplicate and you do:
UPDATE codes
SET registration = '$regi', country = '$country'
WHERE code = '$war'
Otherwise you do:
INSERT INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
However, if we assume you're using MySQL, you might be able to make use of either INSERT IGNORE or REPLACE.
If you use:
INSERT IGNORE codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
The values will be inserted if the code does not already exist. If the code does exist, no record is inserted and MySQL will silently discard the statement without generating an error.
I think what you probably want is this:
REPLACE INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
REPLACE INTO behaves just like INSERT INTO if the record is new. But if the primary key is duplicated, it will perform an UPDATE instead.
Again, INSERT IGNORE and REPLACE INTO are for MySQL only.
Reference: http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm

insert on duplicate key update with multiple values

When using insert... on duplicate key update, what is the syntax to update multiple columns and not update some columns?
i wrote the following query:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"i want this remain the previous value and not change"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=VALUES(text);
how to not change some values and let them remain it's previous value?
Do it with IF:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text)="ZZZ", text, VALUES(text));
-for multiple values use IN instead of =:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,"YYY")
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text) IN ("ZZZ", "YYY"), text, VALUES(text));

get the primary key after a DUPLICATE KEY error?

If I run an insert query but it fails because of duplicated key error is there any way to get its primary key without doing another select?
Basically:
INSERT INTO tbl (field) VALUES ('myvalue')
This fails because there is already a record with ID:1 and field:myvalue.
Now I Want to know that ID:1 without doing another query:
SELECT id FROM tbl WHERE field = 'myvalue'
is it possibile?
Here is a link that provides four different ways to deal with this:
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
There is a provision with each library to get the id of the row which is inserted.
Like: for simple mysql_query() use mysql_insert_id() after that to retrive the id of the last inserted row
Check this link
EDIT:
Please Check that if you have defined the unique index for field column.
If yes then you cannot insert duplicate in the column field

php mysql insert select multiple with where clause

I have a following
Table1 : userid, who, share, date :: id is auto increment and primary key
I would like to build a query to check if record exist and insert new record if is empty.
How to build this in a single query and insert multiple records using a single query
data to inser ('a1','a2','a3','a4'), ('b1','b2','b3','b4'), ('c1','c2','c3','c4'), .......
Create UNIQUE index on column that you want to be unique
Use INSERT IGNORE to insert unique data and ignore not unique
You could use REPLACE statemement that works just like INSERT only it doesn't do anything if the row already exists:
REPLACE INTO table ...
http://dev.mysql.com/doc/refman/5.0/en/replace.html
You should take careful look at mysql INSERT INTO documentation.
How to insert "on no exists" is simple. Let's say you want combination of user,who,share to be unique and use latest date. Update your table and create UNIQUE KEY on those fields:
ALTER TABLE Table1 ADD UNIQUE KEY (user, who, share);
Normally inserting the same combination would cause error but using INSERT IGNORE (link above) would silently ignore error:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW());
You may also force key to update on insert:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW())
ON DUPLICATE KEY UPDATE date = VALUES(date);
And inserting multiple values at once, again the first link:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Categories