I’m looking to set up a tag system using this normalised table structure:
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Tag_Name
Table: ItemTag
Columns: ItemID, TagID
Where the Item table is my general info table, what i want to do is have an additional single text field in my form, and ask users to insert their tags, seperated by a comma. Nothing out of the ordinary and seen all over the web.
What i need help with is the query which takes those comma seperated inputs and:
- Checks they don’t already exist in the Tag table
- Adds them if they don’t exist (where tag_id is a self-incremental field anyway)
- Links inputted tag id’s (whether new or existing) with the ItemID from my general info table.
Can someone help me with the loop for each comma-separated value please?
Thanks
Dan
Split the tag list on
/\s*,\s*/before touching the database, that gives you an array of tag names. Then normalize your tags: force them to upper case, lower case, title case, or whichever case suits your fancy.Now you have some tags that are ready to go into the database. Don’t bother checking if they already exist; instead, add a unique index to
Tag.Tag_Nameand go ahead and INSERT all the tags from your tag list and trap and ignore the unique violation errors.Now you have all your tags in the database and you can use
INSERT ... SELECTto populateItemTag, for each tag you want to do this:where
$item_idis the ID of the item in question and$tagis specific tag that you’re attaching to the item.