Generating Tag cloud with PHP and MySQL

The basic idea this time is to present a way to form a tag cloud from user input text and text entered in the past. A tag cloud is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. for this we will create an HTML form that will accept user text & also allow user to see tag cloud generated from mysql database which contains the text entered in the past.
<?php echo '<form method="post" action="tag_cloud_gen.php" name="gen_tag_db">'; echo '<p>Input your text here:<textarea name="tag_input" rows="20" cols="80"></textarea></p>'; echo '<input type="submit" name="submit">'; echo '</form>'; ?> <h3>OR</h3> <p>see the current tag cloud here</p> <?php echo '<form name="show_tag_cloud" method="post" action="show_tag_cloud.php">'; echo '<input type="submit" value="show current tag cloud" >'; echo '</form>'; ?>
Code language: PHP (php)
The entered text will be tokenized into single words with php function strtok(), each of which will have its frequency counted and the pair will go into an array. This array will then be stored into a mysql database, we can optionally keep a coloumn in the mysql database table to store links if any for future expansion of this project. 1) tag_id —- int,primary key,auto increament 2) keyword — varchar(20),unique 3) weight — int 4) link — varchar(256). Next make a php file and name it tag_cloud_gen.php . The php code written in following lines just make an array ‘$words’ which has keyword in lower case & its frequency association from input text. The pairs from the array are then feed into the mysql database ‘tagcloud_db’ which has a table callet ‘tags’ whose columns are listed above. On encountering error the mysql _errrno() returns error number. While feeding the word array to the tags table duplication may occour, because of the previous entries, so we check whether this is the case by comparing the number returned to ‘1062’ which indicates duplicate field present in the table (the keyword coloumn of table has unique constraint). On encountering this we simply update the mysql database to include the count of this input word/tag too.
<?php /////////////////////////////////////////////////////////////////////////////////////////////////////// /** * this function will update the mysql database table to reflect the new count of the keyword * i.e. the sum of current count in the mysql database &amp;amp;amp;amp; current count in the input. */ function update_database_entry($connection,$table,$keyword,$weight){ $string=$_POST['tag_input']; $connection = mysql_connect("localhost", "root", ""); /** * now comes the main part of generating the tag cloud * we would use a css styling for deciding the size of the tag according to its weight, * both of which would be fetched from mysql database. */ $query="select * from `tagcloud_db`.`tags` where keyword like '%$keyword%'"; $resultset=mysql_query($query,$connection); if(!$resultset){ die('Invalid query: ' . mysql_error()); } else { while($row=mysql_fetch_array($resultset)){ $query="UPDATE `tagcloud_db`.`tags` SET weight=".($row[2]+$weight)." where tag_id=".$row[0].";"; mysql_query($query,$connection); } } } ?> <?php /* * get the input string from the post and then tokenize it to get each word, save the words in an array * in case the word is repeated add '1' to the existing words counter */ $count=0; $tok = strtok($string, " \t,;.\'\"!&-`\n\r");//considering line-return,line-feed,white space,comma,ampersand,tab,etc... as word separator if(strlen($tok)>0) $tok=strtolower($tok); $words=array(); $words[$tok]=1; while ($tok !== false) { echo "Word=$tok"; $tok = strtok(" \t,;.\'\"!&-`\n\r"); if(strlen($tok)>0) { $tok=strtolower($tok); if($words[$tok]>=1){ $words[$tok]=$words[$tok] + 1; } else { $words[$tok]=1; } } } print_r($words); echo ''; /** * now enter the above array of word and corresponding count values into the database table * in case the keyword already exist in the table then update the database table using the function 'update_database_entry(...)' */ $table="tagcloud_db"; mysql_select_db($table,$connection); foreach($words as $keyword=>$weight){ $query="INSERT INTO `tagcloud_db`.`tags` (keyword,weight,link) values ('".$keyword."',".$weight.",'NA')"; if(!mysql_query($query,$connection)){ if(mysql_errno($connection)==1062){ update_database_entry($connection,$table,$keyword,$weight); } } } mysql_close($connection); ?>
Code language: PHP (php)
Make anether file and name it style.css . Put the following code in it.
HTML, BODY { padding: 0; border: 0px none; font-family: Verdana; font-weight: none; } .tags_div { padding: 3px; border: 1px solid #A8A8C3; background-color: white; width: 500px; -moz-border-radius: 5px; } H1 { font-size: 16px; font-weight: none; } A:link { color: #676F9D; text-decoration: none; } A:hover { text-decoration: none; background-color: #4F5AA1; color: white; }
Code language: HTML, XML (xml)
This will make our tag cloud look pretty, save it as style.css . again make a new php file and name it show_tag_cloud.php . In the php code that follows we connect to mysql database, fetch back all the tags, its weight and link. Then it calculates the size for each tag using its weight & minimum assumed size for tags, it also associates each tag the link retrieved from the database or with a google link if no link was there i.e. ‘NA’
<?php $connection = mysql_connect("localhost", "root", ""); $table="tagcloud_db"; $words=array(); $words_link=array(); mysql_select_db($table,$connection); $query="SELECT keyword,weight,link FROM `tagcloud_db`.`tags`;"; if($resultset=mysql_query($query,$connection)){ while($row=mysql_fetch_row($resultset)){ $words[$row[0]]=$row[1]; $words_link[$row[0]]=$row[2]; } } // Incresing this number will make the words bigger; Decreasing will do reverse $factor = 0.5; // Smallest font size possible $starting_font_size = 12; // Tag Separator $tag_separator = '     '; $max_count = array_sum($words); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Tag Cloud Generator </TITLE> <META NAME="Keywords" CONTENT="tag, cloud, php, mysql"> <META NAME="Description" CONTENT="A Tag Cloud using php and mysql"> <LINK REL="stylesheet" HREF="style.css" TYPE="text/css"> </HEAD> <BODY> <center><h1>Tag Cloud using php and mysql </h1><div align='center' class='tags_div'> <?php foreach($words as $tag => $weight ) { $x = round(($weight * 100) / $max_count) * $factor; $font_size = $starting_font_size + $x.'px'; if($words_link[$tag]=='NA') echo "<span style='font-size: ".$font_size."; color: #676F9D;'><a href='http://www.google.co.in/search?hl=en&q=".$tag."&meta='>".$tag."</a></span>".$tag_separator; else echo "<span style='font-size: ".$font_size."; color: #676F9D;'><a href='http://".$words_link[$tag]."/'>".$tag."</a></span>".$tag_separator; } ?> </div></center> </BODY> </HTML>
Code language: PHP (php)
now put them all in your webserver’s root directory and watch the results. Each query will give you new results over time as the database grows. a sample output from my tag cloug looks like this: a sample tag cloud on my computer This tag cloud was generated using the following data:                      tag_id;keyword;weight;link “1”;”vimal”;”7″;”www.vimalkumarpatel.blogspot.com” “2”;”scet”;”5″;”NA” “3”;”engg”;”2″;”NA” “4”;”0″;”1″;”NA” “7”;”google”;”5″;”NA” “8”;”cool”;”2″;”NA” “9”;”orkut”;”3″;”NA”
Get our Articles via Email. Enter your email address.

You may also like...

38 Comments

  1. vimal says:

    there is an errata in the second code,
    please note that “<?” will not come at 9th line but between 30 & 31 line…

  2. Hi Vimal,
    Thanks for pointing out the typo in code. I have fixed it.

  3. The deer says:

    Can tou create a version that uses flash to do the same thing?

  4. Kris says:

    Hello,

    Please add your site at http://www.sweebs.com. Sweebs.com is a place where other people can find you among the best sites on the internet!
    Its just started and we are collecting the best found on the net! We will be delighted to have you in the sweebs listings.

    Regards
    Kris

  5. Felix Omo says:

    When is tags puts in quote? eg
    “a href=’thread.php?increment=-1′>></ ““

  6. Vimal Patel says:

    @The Deer
    well a flash enabled tag cloud is quiet a flashy idea for the time being,
    why i think that is because of following two reasons
    1. It makes page heavier, it terms if size and time to load.
    2. It will not provide links to a web crawler from search engines like google, msn or yahoo, as none of these search engines have the capability to search for text inside a flash or image file.

    over that i am not much familiar with flash :(
    but i liked the idea and once enough information about flash is gathered i may try it out :)

  7. prazetyo says:

    I already try this code, but I get error :
    Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in D:\xampp\htdocs\tags\tag_cloud_gen.php on line 59

    Is it problem with the connecttion?

  8. madhuprasad says:

    am getting errors with this code…PLEASE HELP

    Array ( [0] => 1 )

    Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 59

    Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 62

    Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 63

    Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 68

    ALSO, ONE OF THE USER MENTIONED AN ISSUE ON LINE 9 OF SECOND FILE, BUT I DIDN’;T GET ANY ISSUE HERE…PLEASE SUGGETS

  9. Hi Prazetyo / Madhuprasad,
    I think there was some typo error in the code. I have updated the code and removed the error. Please take the latest code from above article and try again. It should work :)

  10. mdver01 says:

    When I submit keywords, this all I get from the \"tag_cloud_gen.php\" page:

    Array ( [0] => 1 )

    And it\’s just inserting a \"0\" into the database for the string.

    Please help.

    thanks,

    MD

  11. Jay says:

    Hi, does anyone know of example code somewhere that does not make use of a database, but merely makes a tag cloud from text entered by the user into a form?

  12. Dan says:

    I\’m having the same problem as Madhur Prasad. Is there any fix for this?

  13. Alex says:

    I\’m getting the same error Array ( [0] => 1 )

  14. Domenico says:

    Where can I download this tutorial?

  15. Abhijith says:

    Hey..
    thanks a ton for the post..
    came in really handing.. n it works without a flaw..
    ive implemented it without understandin the logic entirely..
    time to go thru wat uve written.
    thanks anyway.. \m/

  16. Muzika says:

    Hi, thank you very much …

  17. madseason says:

    Im trying to figure out how to create a cloud tag for an html web site any help would be appreciated. Thanks

  18. Claire says:

    I’m having the same problem:

    “Array ( [0] => 1 )

    Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 59

    Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 62

    Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 63

    Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in c:\wamp\www\final\tag\tag_cloud_gen.php on line 68”

  19. Peter says:

    Shame you aren’t replying to the Array ( [0] => 1 errors above. I have commented and uncommented every line of the script trying to debug. No luck. I have checked database connections and debugged them as well

    I am sure you realize that you reference $table as a database and not a table in the last few lines of your code, but that isn’t the problem either.

    I would love to see this working.

  20. Can someone help me? I am getting this ERROR Array ( [0] => 1 )

  21. Thanks for this , its really helpful!

  22. AdamS says:

    I’m not even a great programmer and figured it out. Wow.
    Added:
    $string=$_POST[‘tag_input’];
    after function in tag_cloud_gen.php
    posted value from for was not being set to $string

  23. AdamS says:

    My only issue now is if the tags exist, its adding them again and not just updating the keyword(s) weight.

  24. cihip says:

    Generating Tag cloud with PHP and MySQL post for code thanx.

  25. Great one.. Just took me 10 minutes to implement this into my website and looks awesome now..

  26. kodemonki says:

    Hmm, my tags aren’t wrapping . . . http://www.kate-maher.com/kiva649/tag_cloud.php, otherwise, great example! thanks!

  27. I just put the followings lines out of the function and the code works!

    $string=$_POST[‘tag_input’];
    $connection = mysql_connect(“localhost”, “root”, “”);

  28. lidaa says:

    great example! thanks!

  29. WMI says:

    Works well. Had a few problems with the MySQL queries, but they were easy to fix.

    I changed the code around to use GET instead of POST, for two reasons.

    1. They can do a new search from the url directly
    2. They are able to refresh the page without getting the submit data popup.

    Then I just record by IP so they don’t record a search within a 10 minute time frame.

    All in all, good code Vimal. Thanks.

  30. phphunger says:

    This is one of the best tutorial i found in the internet. He explained in a very good manner. The layman can understand with this kind of explanation. Real great work viral patel..keep going..

    • fguru says:

      Could you please help, how did u get it working. I’m still getting this error: Array ( [0] => 1 )

  31. phpguru says:

    I’m still getting Array ( [0] => 1 ) in tag_cloud_gen.php. Any help would be appreciated.

    • amit says:

      Array ( [0] => 1 )

      Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in E:\php\xampp\htdocs\ranjan\extra\test\tag_cloud_gen.php on line 69

      Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\php\xampp\htdocs\ranjan\extra\test\tag_cloud_gen.php on line 72

      Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in E:\php\xampp\htdocs\ranjan\extra\test\tag_cloud_gen.php on line 73

      Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in E:\php\xampp\htdocs\ranjan\extra\test\tag_cloud_gen.php on line 78

      I am getting These Error. Any one can hepl me to sort out this problem

  32. جارچی says:

    tanx a lot dear Vimal Patel

  33. Prerna Verma says:

    Sir,Can Give me code for the web chat using php and mysql ……….

  34. paulo says:

    why this code have a more than 100 ERROR :-)
    THIS CODE NOT TESTED AND ONLY FOR THE TUTORIALS !!!!

  35. HImanshu Goel says:

    Hi There !
    Thanks for such an desired codes, I was just waiting to complete this in my admin and now it seems to be completed – all thanks to this post.

    I want to know that is there a way to stop error reporting in WAMP where as the same error is not shown when tried on online server. Also, this error comes only when we try to save more than 1 tags using comma or space or separator targeting a Loop section i.e.

    /*
    * get the input string from the post and then tokenize it to get each word, save the words in an array
    * in case the word is repeated add ‘1’ to the existing words counter
    */
    $tok = strtok($string, ” t,;.'”!&-`nr”);//considering line-return,line-feed,white space,comma,ampersand,tab,etc… as word separator
    if(strlen($tok)>0) $tok=strtolower($tok);
    $words=array();
    $words[$tok]=1;
    while ($tok !== false) {
    echo “Word=$tok”;
    $tok = strtok(” t,;.'”!&-`nr”);
    if(strlen($tok)>0) {
    $tok=strtolower($tok);
    if($words[$tok] >= 1){
    $words[$tok]=$words[$tok] + 1;
    } else {
    $words[$tok]=1;
    }
    }
    }
    print_r($words);
    echo ”;

    The Error begins from the – if($words[$tok] >= 1){

    For reference I have a uploaded a image – http://rhs.r4y.in/images/tag-cloud-error.jpg

    Thanks in Advance…

    Please provide me solution if there is any…

  36. HImanshu Goel says:

    I have used this script recently and it works fine, also, it is working on online server also, but there is a small issue that is when I run this script on localhost everything works fine and all data is stored as desired but there shows an error after execution on browser on localhost whereas same codes same db same all stuff works fine on online server. How to hide those error while creating programs offline on localhost and in testing mode of a project.
    Help appreciable and codes highly appreciated…

Leave a Reply

Your email address will not be published. Required fields are marked *