mysqli - How can I insert a new row, but if the combination of 2 values already exist update the row? -


my table looks this

create table sample  (  id int auto_increment primary key,   w_id varchar(20),   tc_id varchar(20),   foo varchar(20),   bar varchar(20) ); 

i want insert new row table, if combination of w_id , tc_id exists, want update row new values of 'foo' , 'bar'

i know there lot of similar questions on here, can't figure out....

made sample in sqlfiddle.com

i using 5.6.11-mysql - apache/2.2.22 (win32) php/5.3.25

you can create unique key of combination of w_id , tc_id perform upsert on follows:

create table sample      (      id int auto_increment primary key,       w_id varchar(20),       tc_id varchar(20),       foo varchar(20),       bar varchar(20)     );  alter table sample add constraint unique (w_id, tc_id);  insert sample  (w_id, tc_id,foo,bar) values ('1', '2','123','123'); insert sample  (w_id, tc_id,foo,bar) values ('2', '2','123','123'); insert sample  (w_id, tc_id,foo,bar) values ('3', '2','123','123'); insert sample  (w_id, tc_id,foo,bar) values ('1', '4','123','123'); insert sample  (w_id, tc_id,foo,bar) values ('2', '3','123','123');  insert sample  (w_id, tc_id,foo,bar) values ('1', '2','123','123') on duplicate key update `foo` = 'newfoo'; 

your results like:

id  w_id    tc_id    foo    bar 1   1   2            newfoo 123 2   2   2            123    123 3   3   2            123    123 4   1   4            123    123 5   2   3            123    123 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -