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?!
Answer
Solution:
UNIQUE
constraint on thename
column.Use
INSERT IGNORE
so that inserting a column wherename
already exists simply skips that row. 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.Answer
Solution:
Like Jay suggested, normalise the data, then make the column
UNIQUE
, 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
.