How to Generate Charts from a MySQL Database Using PHP

If you have been into programming for some time now, then there is good chance that PHP and MySQL are part of your technology stack. No matter how many new and shiny languages come and go, this combination (PHP and MySQL) will be there for at least some more time. And that’s the reason I decided to use both the technologies today to make some beautiful charts.

And that’s the reason I decided to use both the technologies today to make some beautiful charts.

In this post, we will cover the process of fetching data from a MySQL database through PHP and then render interactive charts using that data. For charting component, we are going to use FusionCharts as it offers a good collection of charts and maps, is compatible with every browser, and is user-friendly. It also has a dedicated PHP charts plugin that will make our job little bit easier.

One note: FusionCharts is free for personal and non-commercial use. You will have to buy a license if you’d like to use it in commercial applications.

In this step, we are first checking if the result is valid. If it is valid, then we create an associative array which contains both chart configuration options and the data we fetched from database. And then we encode this array into JSON using json_encode function.

chart object under $arrData contains chart configuration options like caption, background color, data plot color, and display formats for numbers etc. To learn about customizing a chart’s look and feel, you can visit this documentation page for 2D doughnut chart.

Step 5: Create a Chart Container

We are going to use HTML <div> element to render our chart:

&amp;lt;div id=&amp;quot;doughnut-chart&amp;quot;&amp;gt;A beautiful donut chart is on its way!&amp;lt;/div&amp;gt;

Another option might be to use a JavaScript charting library for stylish, interactive charts but use a PHP wrapper to customize the charts using PHP. These wrappers exist for several major libraries. Here is one example of such a wrapper: https://github.com/zingchart/ZingChart-PHP