kumail kumail - 7 days ago 5
MySQL Question

How to print MySQL data into a bar chart using PHP

I am creating a report in which I want to show my data using a bar chart I went through some blogs, tutorials and a way to print; but, now my need is I want to show my data in percentages and print it, can anyone help me out?

Here is my code:

<style>
.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(images/bargraph.gif);
background-position:right center;
background-repeat:repeat-x;
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>

</head>

<body>

<div id="container">

<?php
require("includes/dbconnect.php");

$getcen = mysql_query("SELECT count(*) AS totcen, center FROM `makhtab` WHERE center != '' GROUP BY center ORDER BY center") or die(mysql_error());

while ($mcent = mysql_fetch_array($getcen)) {
echo '<div class="rating"><div class="graphcont"><div class="graph"><strong class="bar" style="width:'.$mcent["totcen"].'%;">'.$mcent["totcen"].'</strong></div></div></div>
<div class="clear"></div>';
}
?>
</div>


The above code works fine but I want to set my div in which the bar is shown to a fixed width and I want to manipulate the bar width according to percentage created by the query. Thanks in-advance.

Answer

In order to correctly display the bar, you would need to calculate the value of the percentage that the 'totmakh' value represents.

First, you would need to know the maximum allowed value, which represents 100%, let's assume it's called MAX. Once you have defined this value, calculating the percentage is easy:

$percentage = $mcent["totmakh"] * 100 / MAX;

You can then use that value to set the percentage width of the div.

Comments