How to write in the mysql field unique values? If given:
privet
privet
privet
... others

Need to write (unique by adding a hyphen and numbers)
privet
privet-1
privet-2
....

Tell me how to more effectively implement in php?
What are the options?

Another option: if the table field before insertion is generally empty. (can process everything in an array, and then write it once to the database?)

The assumption to search and select each time SELECT.
but it seems there will be a lot of search operations ... especially on "big data" and this will affect the performance

  • Try searching through REGEXP, and at the end add count records found with regexp. Create a trigger that will be executed before writing a new line. This processing can be done on the PHP side, then the trigger will not be added, but the latter will ensure the uniqueness of the record. - ilyaplot
  • Why do you want to push everything into one field, and not create another one? - uorypm
  • I did not understand about another field. Well, this is one field with data, just like in my example, the same values ​​can occur, and in the field we need unique ones. That is to uniquely need to add hyphens and numbers. - Andrei
  • @ Andrei id field with auto increment. Insert records without any checks, and when reading you make the concatenation of the required field with the id field and with a hyphen between them. What is the reason that the record should be in one field? - uorypm
  • I understand you, then you can add id. We need to think about it. In addition to my "greetings" (privet) there is / may be data in this field. Characteristics of the field: varchar (255), NULL - no. I just saw the method I described (with -1, -2, 3-), but I do not know how it is implemented. I decided to ask. - Andrei

1 answer 1

Here is an example of a function that can help:

 function getUniqueValue($value) { $value = trim($value); $i = 1; do { if (preg_match("/\-\d+$/i", $value)) { $value = preg_replace("/\-\d+$/i", sprintf("-%02d", $i++), $value, 1); } else { $value .= '-01'; } $match = ... ;// здесь возвращается результат запроса с проверкой на наличие в базе такого поля } while ($match); return $value; }