PHP: Tagging your content

February 20th, 2008 by jason

 

tagcode.jpg

Most readers will be familiar with the concept of tagging. A tag is a relevant keyword or term associated with or assigned to a piece of information (a picture, a geographic map, a blog entry, a video clip etc.), thus describing the item and enabling keyword-based classification and search of information.

This tutorial talks you through this concept of adding tags to content, both the coding and database aspects.

First lets look at the databases. Firstly we will presume you have an element table, the element is in fact the thing that we will be tagging and could be anything from news item to pictures. In a relational database this element should have an ID and the table would look something like this element[‘element_id’, ‘name’ …]

Next we need a tag table. This will be a simple table with just 3 fields: tag_id, tag_name, element_id. Tag[‘tag_id’, ‘tag_name’, ‘element_id’]. The element_id is the relation to the element table.

Next we need a simple form for users to tag the element. The user will enter each keyword speperated by a comma

<input name=”prodtags” id=”prodmodel” value=”<?php echo $prodtags ; ?>” size=”35″ maxlength=”255″ type=”text” class=”textInput” />

We will POST the contents of this file into a $prodtags variable by doing $prodtags = $_POST[‘prodtags’];

Next we will make use of PHPs explode function to extract the keywords from the string, $prodtagssan = explode(”, “,$prodtags); Simply what happens here is that it breaks the string into different phrases based on where the comma and space are and puts it into an array $prodtagssan.

Finaly we will put the tags into the tag table. We will need to get the element_id, this will be totally independent on your code and you may have to make use of some type of global variable.

foreach ($prodtagssan as $value)

{

$prodtagdata = $prodtagssan[$i];

$sql=”INSERT INTO tag (tag_id, tag_name, element_id) values (’0′,’$prodtagdata’, ‘$element’)”;

mysql_query($sql)or die(mysql_error());

$i = $i + 1;

}

The loop, loops through the variable and inserts each tag into the table as a separate entity.

With tagging in place we can out put this into a tag cloud, or even make some type of graphical representation of the inputted tags using the GD function.

del.icio.us Digg Technorati StumbleUpon

Posted in PHP Code

3 Comments

  1. Matthew Vorster

    Great post!

    Just a bit confused about $sql=”INSERT INTO tag (tag_id, tag_name, product_id)

    is product_id the same as element_id?

  2. jason

    Thanks Mat, I corrected that.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.