Creating PHP Dynamic Graphs with CSS

Posted on 22 Feb 2012 in Tips and Tricks | 0 comments

Hey everyone, its Grant. Today I am going to show you how to create a dynamic bar graph from a floating point integer exported from a MySQL database or the like.

The number we want to calculate is .4323959623

View the Demo

First we create our CSS to get the right look and feel for the graph once it is displayed…
<style type=”text/css”>

.clear{
clear:both;
}

.graphcont {
padding-top:10px;
color:#000;
font-weight:700;
float:left
}

.graph {
float:left;
margin-top:10px;
background-color:#cecece;
position:relative;
width:280px;
padding:0
}

.graph .bar {
display:block;
position:relative;
background-image:url(bar.jpg);
background-position:right center;
background-repeat:repeat;
border-right:#538e02 1px solid;
text-align:center;
color:#fff;
height:25px;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
line-height:1.9em
}
.graph .bar span {
position:absolute;
left:1em
}
</style>

Moving along we get into the HTML placement of the DIV tags in which the Graph will be displayed:

 

<div class=”rating”>

<div class=”graphcont”>

<div class=”graph”>

<strong class=”bar”></strong>

</div>

</div>

</div>

<div class=”clear”></div>

 

 

And now for the fun part. The conversion of the floating point integer into a percent!

 

<?php

$initialValue = .4323959623;
// the initial value of the float

$percent = $initialValue * 100;
// multiple the float by 100 (output: 43.23959623)

$percent = (int)$percent;
// cast the float value to an int value which will remove the trailing place values.  (output: 43)

if($percent > 100){
// if the integer is above 100 percent reduce it back to 100%.

$percent = 100;

}

//$percent should now equal 43

?>

 

Now we just print the variables into the correct spot, adjust the width of the bar class and we’re done!

 

<div class=”rating”>

<div class=”graphcont”>

<div class=”graph”>

<strong class=”bar” style=”width:<?=$percent;?>%;”><?=$percent;?>%</strong>

</div>

</div>

</div>

<div class=”clear”></div>

 

So what we just did was simple. Convert a floating point integer into an double integer. The trick was to display the % as the width for the bar class.

View the Demo