HighlyStructured.com is a blog website run by Mike D'Agostino about search engine positioning, online marketing, php/MySQL, tae kwon do, and various other topics.

Creating Bar Graphs Using PHP

February 12, 2006

PHP makes it easy to store and retrieve data to a MySQL database. Statistics analysis is a pretty common application for PHP and MySQL. This involves storing some kind of data, retrieving that data, performing some kind of mathematical operation, and then displaying the results.

This is a common function for something like Microsoft Excel as well. Numbers are stored in a spreadsheet, and using Excel's built-in data analysis functions, it will automatically perform mathematical operations and present the data in the form of a graphical display. Excel even goes a step further and let's you select what kind of graphical display you would like the data presented in.

So how can you use PHP to present numbers and stats in a graphical display?

My solution is quite easy actually. It basically only involves one tiny image...a solid colored gif, 1 pixel by 1 pixel. The beauty about gif images, ones that are a solid color anyway, is that they can be set at any height and width when called to with HTML and will not visually degrade. However a gif image with multiple colors will seriously degrade when given different dimensions than it was originally saved with.

Hopefully it is obvious where I'm going with this. Basically you retrieve your data, perform whatever operations need to be performed, and get your final number. Once the number is produced, a certain height or width can be assigned to the the gif image in HTML. It's that easy!

Specific Example

One great use for graphical images using PHP and MySQL is for polls. I think everyone knows the premise...numbers are produced and a bar graph displays the percentage results. Let's say a particular result is 37 percent. "37" then becomes the height (for a vertical bar graph) of the 1 x 1 pixel gif image. I like to set my widths (again for a vertical bar graph) to 10 or 15, and then let the height take care of itself. Once the height is found, it can then be saved as a variable, and in the HTML code to call the image, the variable can be assigned to the image height.

The result is an easy way to present data graphically using PHP. It's even possible to create multiple heights. I don't mean multiple as in more than one, but as in 1x or 2x or 3.7x. This becomes useful when you don't want 7%, for example, to equal 7 pixels. That size may be too small so you may want to multiple the number by 2, let's say, to make the height 14 pixels. And it won't matter because the solid color gif image can be stretched to any size!

Technorati Tags:         

Recent Articles



Other Blogs of Interest