DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Flat-tag Updater
Pass new tags followed by a table name and database handle and this function updates the table so that each tag becomes properly associated/its record created, eg:
table state:
tagname | relatedtags
-----------------------
blog | rss;personal
rss | blog
personal | blog
call (table is named tags):
updateTags("blog personal friends","tags",$db);
table state:
tagname | relatedtags
-----------------------
blog | rss;personal;friends
rss | blog
personal | blog;friends
friends | blog;personal
function updateTags($tags,$table,$db) {//category handling stuff
include("recordExists.php");//see http://bigbold.com/snippets/posts/show/464
$cats = explode(";",$tags);//parse tags into array cats
foreach($cats as $cat) {//loop through cats
$tmp = array($cat);//dummy array with cat in it
$tmp = array_diff($cats,$tmp);//get everything in cats that is not cat
if(!recordExists("tagname",$cat,$table,$db)) {//if there is no category by this name yet
$tmp = implode(";",$tmp);//make tmp into semicolon-separated string
$result = mysql_query("INSERT INTO ".$table." (tagname,relatedtags) VALUES ('$cat','$tmp')", $db) or die(mysql_error());//insert category into database
} else {
$result = mysql_query("SELECT relatedtags FROM ".$table." WHERE tagname='$cat'", $db) or die(mysql_error());//select already related tags
$result = mysql_fetch_array($result);//get the result row as an array
$result = explode(";",$result['relatedtags']);//parse relatedtags into result
$result = array_merge($tmp,$result);//merge the cats in this $tags (without cat, hence tmp) with the ones that were in there already
$result = array_unique($result);//strip duplicates
$result = implode(";",$result);//make result into semicolon-separated string
$result = mysql_query("UPDATE ".$table." SET relatedtags='$result' WHERE tagname='$cat'", $db) or die(mysql_error());//update category
}//end if-else !recordExists
}//end foreach cats
}//end function updateTags





