How To Create Dynamic Pie Chart in PHP or JavaScript with MySQL?

Graphical or visual representation of data is usually a requirement for a software, mostly, business apps. Today I’m going to show you the two and free ways to generate dynamic Pie Charts for your web applications.

We say “dynamic” because the data that will be shown in the pie chart were pulled from a database which can be updated frequently.

You can also create other types of charts such as bar charts, line charts, and many other types of charts, but in this post, we will cover pie charts only which can give you a good idea on how to create dynamic charts.

how to create dynamic pie chart in php or javascript

In this post, we will cover the following topics:

1.0 Dummy Database for Dynamic Pie Chart
2.0 Using LibChart to Create Dynamic Charts (PHP)
3.0 Using the Google Chart Tools (JavaScript)

The first way I will give you is generating a chart using PHP, and in the second way, we will use JavaScript.

Dummy Database for Dynamic Pie Chart

This will be our example table and data.

--
-- Table structure for table `programming_languages`
--
 
CREATE TABLE IF NOT EXISTS `programming_languages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `ratings` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
 
--
-- Dumping data for table `programming_languages`
--
 
INSERT INTO `programming_languages` (`id`, `name`, `ratings`) VALUES
(1, 'C', 17),
(2, 'Java', 16),
(3, 'C++', 9),
(4, 'Objective-C', 9),
(5, 'C#', 7),
(6, 'Basic', 6),
(7, 'PHP', 5),
(8, 'Phyton', 3),
(9, 'Pearl', 2),
(10, 'Ruby', 1);

Using LibChart to Create Dynamic Charts (PHP)

We will do the first way using the LibChart, the simple and free PHP chart drawing library.

Here’s a code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pie Chart Demo (LibChart)- https://codeofaninja.com/</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
</head>
<body>
 
<?php
    //include the library
    include "libchart/libchart/classes/libchart.php";
 
    //new pie chart instance
    $chart = new PieChart( 500, 300 );
 
    //data set instance
    $dataSet = new XYDataSet();
    
    //actual data
    //get data from the database
    
    //include database connection
    include 'db_connect.php';
 
    //query all records from the database
    $query = "select * from programming_languages";
 
    //execute the query
    $result = $mysqli->query( $query );
 
    //get number of rows returned
    $num_results = $result->num_rows;
 
    if( $num_results > 0){
    
        while( $row = $result->fetch_assoc() ){
            extract($row);
            $dataSet->addPoint(new Point("{$name} {$ratings})", $ratings));
        }
    
        //finalize dataset
        $chart->setDataSet($dataSet);
 
        //set chart title
        $chart->setTitle("Tiobe Top Programming Languages for June 2012");
        
        //render as an image and store under "generated" folder
        $chart->render("generated/1.png");
    
        //pull the generated chart where it was stored
        echo "<img alt='Pie chart'  src='generated/1.png' style='border: 1px solid gray;'/>";
    
    }else{
        echo "No programming languages found in the database.";
    }
?>
 
</body>
</html>

Some advantage of using the LibChart includes: Free, it will work even offline or if you’re just debugging on your localhost, easy to use and can be used for multiple data sets.

Some disadvantages are: It is limited to Line, Bar and Pie charts only and it works with PHP5 only.

Using the Google Chart Tools (JavaScript)

Google chart tools are powerful, simple to use, and also free.

Our index.php code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Pie Chart Demo (Google VAPI) - https://codeofaninja.com/</title>
    </head>
    
<body style="font-family: Arial;border: 0 none;">
    <!-- where the chart will be rendered -->
    <div id="visualization" style="width: 600px; height: 400px;"></div>
 
    <?php
 
    //include database connection
    include 'db_connect.php';
 
    //query all records from the database
    $query = "select * from programming_languages";
 
    //execute the query
    $result = $mysqli->query( $query );
 
    //get number of rows returned
    $num_results = $result->num_rows;
 
    if( $num_results > 0){
 
    ?>
        <!-- load api -->
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        
        <script type="text/javascript">
            //load package
            google.load('visualization', '1', {packages: ['corechart']});
        </script>
 
        <script type="text/javascript">
            function drawVisualization() {
                // Create and populate the data table.
                var data = google.visualization.arrayToDataTable([
                    ['PL', 'Ratings'],
                    <?php
                    while( $row = $result->fetch_assoc() ){
                        extract($row);
                        echo "['{$name}', {$ratings}],";
                    }
                    ?>
                ]);
 
                // Create and draw the visualization.
                new google.visualization.PieChart(document.getElementById('visualization')).
                draw(data, {title:"Tiobe Top Programming Languages for June 2012"});
            }
 
            google.setOnLoadCallback(drawVisualization);
        </script>
    <?php
 
    }else{
        echo "No programming languages found in the database.";
    }
    ?>
    
</body>
</html>

The advantages of using Google chart tools include: Free, easy to use, multiple data sets, and has wide range of charts types that you can use, looks good and interactive.

I think the only disadvantage will be: you cannot use it when you don’t have internet connection.

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

How about you, do you have any other suggestions or solutions on how to create dynamic pie chart in PHP or JavaScript? Thanks for sharing it in the comments section below!

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

34 comments

  1. It’s not working. i copied the code exactly as is. i tried to put the code on my server, but not working??? i don’t know if i put the folders in the right place. keep getting a blank page. any help would be greatly appreciated.

    1. Hi @mb, would you try to right click your page > click ‘inspect element’ > click ‘console’ tab and let us know what error message you see there?

  2. google.charts.load(“current”, {packages:[“corechart”]});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
    var data = google.visualization.arrayToDataTable([
    data.addColumn(‘string’, ‘login’);
    data.addColumn(‘number’, ‘score’);

    ]);
    whats wrong with this? it showing nothing on the browser

    1. Hello @disqus_wJET4cZNP7 , would you try to right click the page, then click ‘inspect element’, then click the ‘console’ tab. Let us know what error message you see.

  3. Its not working for me… Please Help.

    The code is

    Pie Chart Demo (LibChart)- https://codeofaninja.com/

    0)

    {

    while( $row = mysql_fetch_array($result) )

    {

    extract($row);

    $dataSet->addPoint(new Point(“{$name} {$ratings})”, $ratings));

    }

    //finalize dataset

    $chart->setDataSet($dataSet);

    //set chart title

    $chart->setTitle(“Tiobe Top Programming Languages for June 2012”);

    //render as an image and store under “generated” folder

    $chart->render(“generated/1.png”);

    //pull the generated chart where it was stored

    echo “”;

    }

    else

    {

    echo “No programming languages found in the database.”;

    }

    ?>

  4. It’s helpful and it’s working nicely. i want to use more than one pie chart in a page. what should i do?

    1. Hello @disqus_6oxnJDQSLx , I’m glad you made it work! Multiple pie chart will work on one page please try it and post any error message you see here.. thanks!

  5. Amigo, excelente tutorial. Mas o meu está apresentando uma mensagem de erro na linha 29(Undefined variable: mysqli).

    1. mysqli is connection name….

      some thing like this, this work for me,

      $mysqli=mysqli_connect(‘localhost’,’root’,”,’database_name’);

    1. Hello @john_leno, you’re welcome! I appreciate you for joining our site here in the comments! Te agradece! (Thanks to google translate haha!)

  6. Pretty decent collection you got here. I’ve never handled charts in PHP/JS before, I might find this useful. Bookmarked! Thanks

  7. Hi,

    I am new to PHP.I am using php libchart.

    Getting error in Pie chart program.

    Warning: imagepng(sample/libchart/demo/generated/img.png): failed to open stream: No such file or directory in C:wampwwwsamplelibchartlibchartclassesview plotPlot.php on line 284

    I dont know how to fix it .I googled a lot but no solution. I saw that u also got the same error..

    It would be great if my error is solved..

    Thanks.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top