PHP: prevent duplicated tags in Mysql

914

I have MySql Table For Tags Like This:

| id |   name    |
| 1  |   Linux   |
| 2  |  Windows  |
| 3  |   Unix    |
| 4  |    Dos    |
| 5  |  FreeBSD

In News Page User add New Tags Like This:

|Linux,OpenBSD,Test 

Now,Linux Previously added, So I need To addONLY OpenBSD and Test Into Tags Table. My Mean Is: how toINSERT tags if User tags is New?!

289

Answer

Solution:

  1. Put aUNIQUE constraint on thename column.
  2. UseINSERT IGNORE so that inserting a column wherename already exists simply skips that row. eg:

    INSERT IGNORE INTO tags (name) VALUES ('Linux'), ('OpenBSD'), ('Test');
    
  3. Because you have different casings in your data [eg:linux vsLinux] you either need to make sure that you are using a case-insensitive coallation in your database likeutf8_latin1_ci [ci stands for case-insensitive] or be sure to usestrtolower() on your data prior to inserting it.
401

Answer

Solution:

Like Jay suggested, normalise the data, then make the columnUNIQUE, and use something likeINSERT IGNORE INTO yourTags(name) VALUES(?),(?),(?) (and send in the three values as parameters). I'm also assuming that the ID column isAUTO INCREMENT.

People are also looking for solutions to the problem: php - SimpleXML get all child nodes from Line NUMBER=*

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.