How to organize a condition check when adding a record to the database?

If the database already has a similar name, then instead of adding a new line (duplicate), just update some values ​​first.

Suppose there are 3 columns in the database (id, name, date). I need to check when writing new lines: for example, since there is a line called "bla-bla", then do not create a new "bla-bla" with a new ID, but simply change the date in the first "bla-bla" to new and all.

It was ('100', 'bla-bla', '08.01.2016 10:00')

It became ('100', 'bla-bla', '08.01.2016 10:47')

Reported as a duplicate by Anton Shchyrov , AK , Vadim Ovchinnikov , user194374, Denis on Jan 9 '17 at 6:36 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

2 answers 2

You can use ON DUPLICATE KEY UPDATE :

 INSERT INTO table (id, name, date) VALUES (100, 'bla-bla', '08.01.2016 10:47') ON DUPLICATE KEY UPDATE date = '08.01.2016 10:47'; 

You also need to add a UNIQUE index (or PRIMARY KEY ) for the name field.

  • Thanks for the answer. I did as you advised, but I ran into a problem, I have data transferred through variables in VALUES, and if I write with variables VALUES ('". $ Item"', "'date"' ....) then ON DUPLICATE KEY UPDATE becomes not active. And if you write VALUES ('123', '12122015') then everything is okay. Maybe I’m doing something wrong .. I looked at all the links I was given in the answers, everything seems to be right, but it still doesn’t work and I can’t understand why - Vladimir V.
  • @ VladimirV. Check how your query looks after concatenations in code. In VALUES ('".$item"', "'date"'....) it seems to me very suspicious that the point $item missing, as well as "'date"' instead of '" . $date . "' . But the question itself, in general, is no longer relevant. - Regent
  • In the file I have points. $ Date. $ item. I made a mistake and did not add them when writing the answer to you. - Vladimir V.
  • @ VladimirV. save the query text in a variable, display it on the screen and check for errors. - Regent

It is possible in this way, everything works as it should

 INSERT INTO requests ('user_id','subject','text','time') VALUES (56,'test','test 1234',6516516) ON DUPLICATE KEY UPDATE time = VALUES(time), user_id = VALUES(user_id)