Last updated on January 10th, 2022 at 01:38 pm

Create tag cloud using PHP and Mysql

Simple and effective script to build a PHP MySQL tag cloud using Ajax for your website. Here we use PHP, Ajax and MYSQL. Tagging is now becoming an unavoidable area in website building and if you have a built in code like the one you are about to see, then it will be easy for a developer to integrate it or even customize it according to the requirement.

First and foremost we need to have MYSQL set along with the page with an html input field, the ajax part and some css for styling.
The mysql part looks like this, we are setting column name id as AUTO INCREMENT and as a PRIMARY KEY.

CREATE TABLE IF NOT EXISTS `tags` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `tags` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
<html>
<body>
<style>
#data_up {
  font-family:arial;
  font-size: 10.9pt;
  color: #0066FF;
  background-color: #000;
  width: 300px;
  padding:25px 50px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    border: 1px solid;
}
#my_form {
  font-family:"Times New Roman",Georgia,Serif;
  font-size: 10.9pt;
  color: #fff;
  background-color: #777;
  width: 700px;
  padding:25px 50px;
    -moz-border-radius: 30px;
behavior:url(border-radius.htc);
    border-radius: 30px;
    border: 2px solid;
}
#space_me
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  alert("None Give")
  document.getElementById("data_up").innerHTML="No Tags Were Entered By You :-)";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("data_up").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","add_tag.php?add_me="+str,true);
xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
xmlhttp.send();
}
</script>
<center>
<div id="my_form">
Enter Some Tag Name And Click The Botton <input type="text" id="add_me" name="add_me">
<input type="submit" name="submit" value="Add This Tag" onclick="showUser(document.getElementById('add_me').value)"><p>
<div id="data_up" class="clearfix">
<?php include('add_tag.php')?>
</div>
</div>
</center>
</body>
</html>

In the above html code we can see that there is a add_tag.php file. This is the file from which we establish database connectivity and Display / Add tags.

The add_tag.php file for PHP version 5 and older looks like this.


<style>
#data_up1
{
width:300px;
background-color:#000;
color:#fff;
}
#space_me
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style><div id="data_up1"> <PRE id="space_me"><?php
$host='localhost';
$username='root';
$password='*******';
//Donot Edit Anything Below
$objConnect = mysql_connect($host,$username,$password) or die("Error Connecting to Database, <hr>Known issues:Database may be down or need to contact Admin [[email protected]]");
$objDB = mysql_select_db("test1");
$query = mysql_query("SELECT * FROM `tags`");
$get_tags = mysql_real_escape_string($_GET['add_me']);
$disp_default= mysql_real_escape_string($_GET['display']);
$get_tags = strtolower($get_tags);
if($disp_default)
{
$result_dis = mysql_query("SELECT tags,COUNT(tags) as my FROM tags group by tags") or die(mysql_error());
$result_count = mysql_num_rows($result_dis);
if($result_count == 0)
{
echo "Please Add Some Tags Now!!!<br>";
}
else {
    while($row_dis = mysql_fetch_array($result_dis))
  {
   
  $tag = $row_dis['tags'];
  echo " ".$tag."<font color='yellow'>(". $row_dis['my']. ")</font>" ;
  }
exit;
}
}
$symbol= array("!","@","#","$","%","^","&","*","(",")","+","="."{","}","\\","/",":",";",".","`","~",">","<",".",",");
$result = count($symbol);
for($i==0;$i<=$result;$i++)
{
$check_contains_extra = strstr($get_tags, $symbol[$i]);
if($check_contains_extra == true)
{
echo "Please dont add any extra charecters, Only Alphabets and Numbers are allowed";
exit;
}
}
$tag_array = array("php","ajax","mysql","javascript","flash","photoshop","perl","unix","linux","java");
$contains = in_array($get_tags,$tag_array);
if($contains != "1")
{
  echo "Please Add Only The Tags Displayed Above";
exit;
}
if($get_tags)
{
$results = mysql_fetch_array($query);
$strSQL = "INSERT INTO tags ";
    $strSQL .="(tags) ";
    $strSQL .="VALUES ";
    $strSQL .="('".$get_tags."') ";
    $objQuery = mysql_query($strSQL);
    }
    else
    {
    }
    $result = mysql_query("SELECT tags,COUNT(tags) as my FROM tags group by tags") or die(mysql_error());
    while($row = mysql_fetch_array($result))
  {
  if($get_tags==$row['tags'])
  {
  $tag = "<font size=6 color='blue'>".$row['tags']."</font>";
  }
  else
  {
  $tag = $row['tags'];
  }
  echo " ".$tag."<font color='yellow'>(". $row['my']. ")</font>" ;
  }
?></PRE></div>


The php script uses a database with name test1 and the table used is tags
I am using two arrays to find out any extra characters.

$symbol= array("!","@","#","$","%","^","&amp;amp;","*","(",")","+","="."{","}","\\","/",":",";",".","`","~","&amp;gt;","&amp;lt;",".",",");


The advantage above is you are free to add any number of extra symbol/characters above.
You can even filter tags.

$tag_array = array("php","ajax","mysql","javascript","flash","photoshop","perl","unix","linux","java");

The add_tag.php file for PHP version 5 and above looks like this.

<style>
#data_up1
{
width:300px;
background-color:#000;
color:#fff;
}
#space_me
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style><div id="data_up1"> <PRE id="space_me"><?php
$host='localhost';
$username='root';
$password='';
//Donot Edit Anything Below
$objConnect = mysqli_connect($host,$username,$password) or die("Error Connecting to Database, <hr>Known issues:Database may be down or need to contact Admin [[email protected]]");
$objDB = mysqli_select_db($objConnect,"test");
$query = mysqli_query($objConnect,"SELECT * FROM `tags`");
$get_tags = mysqli_real_escape_string($objConnect,$_GET['add_me']);
$disp_default= mysqli_real_escape_string($objConnect,$_GET['display']);
$get_tags = strtolower($get_tags);

if($disp_default)
{
$result_dis = mysqli_query("SELECT tags,COUNT(tags) as my FROM tags group by tags") or die(mysqli_error());
$result_count = mysqli_num_rows($result_dis);
if($result_count == 0)
{
echo "Please Add Some Tags Now!!!<br>";
}
else {
	while($row_dis = mysqli_fetch_array($result_dis))
  {

  $tag = $row_dis['tags'];
  echo " ".$tag."<font color='yellow'>(". $row_dis['my']. ")</font>" ;
  }
exit;
}
}

//$check_contains_extra = strstr($get_tags, ',');
$symbol= array("!","@","#","$","%","^","&","*","(",")","+","="."{","}","\\","/",":",";",".","`","~",">","<",".",",");
$result = count($symbol);
//echo $result;
for($i==0;$i<=$result;$i++)
{
//echo $symbol[$i];
$check_contains_extra = strstr($get_tags, $symbol[$i]);

if($check_contains_extra == true)
{
echo "Please dont add any extra charecters, Only Alphabets and Numbers are allowed";
exit;
}
}
$tag_array = array("php","ajax","mysql","javascript","flash","photoshop","perl","unix","linux","java");
$contains = in_array($get_tags,$tag_array);
if($contains != "1")
{
  echo "Please Add Only The Tags Displayed Above";
exit;
}
if($get_tags)
{
$results = mysqli_fetch_array($query);
$strSQL = "INSERT INTO tags ";
	$strSQL .="(tags) ";
	$strSQL .="VALUES ";
	$strSQL .="('".$get_tags."') ";
	$objQuery = mysqli_query($objConnect,$strSQL);
	//echo "Tag <b>".$get_tags."</b> Has Been Succesfully Added Under<br>";
	}
	else
	{
	}
	$result = mysqli_query($objConnect,"SELECT tags,COUNT(tags) as my FROM tags group by tags") or die(mysqli_error());
	while($row = mysqli_fetch_array($result))
  {
  if($get_tags==$row['tags'])
  {
  $tag = "<font size=6 color='blue'>".$row['tags']."</font>";
  }
  else
  {
  $tag = $row['tags'];
  }
  echo " ".$tag."<font color='yellow'>(". $row['my']. ")</font>" ;
  }

?> </PRE>    </div>


Add the required tag name in this array and only those will be updated to database 🙂 .

If you want to just display the tags then use this URL [ASSUMING THE MAIN WEBPAGE IS INDEX.PHP] http://<YOUR_WEBSITE_NAME>/tags/?display=1 or whatever you need in place of 1, only thing here is the GET tag name DISPLAY in the URL should be SET to some value. I hope you got my point.

DEMO


Leave a Reply

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