I’m working on a tags feature and this is my database structure so far:
`tags` Table: `content` Table:
id | tagname id | title | tags
------------ -----------------------
1 | fire 1 | Charizard | 1 3
2 | water 2 | Blastoise | 2
3 | flying 3 | Charmander | 1
What is the best method for using these two tables and outputting the proper tags for each item of content?
If I was to call for my tags in this manner:
$query = mysql_query("SELECT * FROM `content`");
while ($tableData = mysql_fetch_array($query)) {
echo $tableData["tags"];
}
It would obviously output the raw text content 1 3 and 2 and 1 respectively.
I want it to display fire flying and water and fire respectively.
What should I do to grab those tagnames using the information given from the tags column in the content table?
Yes, you should study normalization and change your table to 3NF. First of all this will save you some huge headaches down the line, and second, normalization is really cool. Here’s a very fast summary of what you’d be doing:
Having all your tags in one field is bad practice. It means that everything that will ever query your database has to know exactly how you’re storing them and how to pull them apart. It also means that you won’t be able to use pure SQL to ask questions like “how many pokemon have a fire attribute” or “which tag is the most popular” because SQL doesn’t know what your space-delimited list of tags means. Instead, you’d split
contentinto two tables:monstersandattributes. Monsters looks like this:And attributes looks like this:
To get a monster’s attributes, you find its name in the monsters table, get its ID, and use its ID to find its attributes from the attributes table. This is trivial using JOIN and it gives you a great deal of power to retrieve your information in interesting ways.
To answer your original question, you’d do something like this:
And you’d get a results table that looks like this:
Then you could iterate over the rows that were returned and do something like:
And then finally you’ll have what you wanted, an array where each element is identified by a monster’s name, and the value is an array with all that monster’s tags.
… Seriously, I know this sounds hellishly complicated compared to what you were originally asking, but I believe it’s the simplest way to do it that’s not likely to blow up in your face. Hopefully someone will correct me if I’m badly wrong.
warning – the code here was written off the top of my head. There may be some errors in it, but it should show you how to implement the solution.