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

[adinserter block=”34″]

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!
[purchase_link id=”12370″ text=”Download Now” style=”button” color=”green”]

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!


Comments

34 responses to “How To Create Dynamic Pie Chart in PHP or JavaScript with MySQL?”

  1. Anonymous Avatar
    Anonymous

    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.

  2. Thankyou for this great tutorial

  3. Anonymous Avatar
    Anonymous

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

    1. Thanks Anonymous! 😀

  4. RSVV Prasad Avatar
    RSVV Prasad

    Thank you soooooooooooooooooooooooooooo much. You helped me a loooooooooooot.

    1. You’re welcome @35cd13e39492c2a9db19428a709112f1!

  5. Võ Chí Tân Avatar
    Võ Chí Tân

    thanks you, it’s useful for me!

    1. Glad it was useful to you @vchtn!

  6. Anand Mishra Avatar
    Anand Mishra

    Thanks for sharing this excellent tutorials…

    1. ninjazhai Avatar
      ninjazhai

      Hey @disqus_N4Cch6jKTg , glad you found our tutorials helpful!

  7. John Leno Avatar
    John Leno

    Entrei só para agradecer sua ajuda!

    🙂

    Thank´s

    1. ninjazhai Avatar
      ninjazhai

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

  8. L̶e̶a̶n̶d̶r̶o̶ M̶a̶r̶t̶i̶n̶s̶ Avatar
    L̶e̶a̶n̶d̶r̶o̶ M̶a̶r̶t̶i̶n̶s̶

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

    1. ninjazhai Avatar
      ninjazhai

      Hello @l_e_a_n_d_r_o_m_a_r_t_i_n_s, are you sure MySQLi is supported in your server?

    2. Er Ajay Nishad Avatar
      Er Ajay Nishad

      mysqli is connection name….

      some thing like this, this work for me,

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

  9. Nurul Huda Avatar
    Nurul Huda

    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. ninjazhai Avatar
      ninjazhai

      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!

  10. how can i change the pie color??

    1. Prabhakaran GBLS Avatar
      Prabhakaran GBLS

      how to alter this pie chart

      1. Hello @prabhakarangbls, what exactly are you trying to achieve? Pie chart will change based on the data on your database.

  11. Manav Patadia Avatar
    Manav Patadia

    Its not working for me… Please Help.

    The code is

    Pie Chart Demo (LibChart)- http://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.”;

    }

    ?>

  12. Pradeep Swat Avatar
    Pradeep Swat

    Thank you Amigo

    1. You’re welcome Amigo @pradeep_swat! Please share our site to your friends! 🙂

  13. Junio Sousa Avatar
    Junio Sousa

    Hi, do you know how it would be if I’m using Heidisql?

    1. Hello @disqus_apnVvMtYFX, I’m not familiar with HeidiSQL, but should work if you know how to query with that tool.

  14. Praveen Kumar Avatar
    Praveen Kumar

    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.

  15. Arjun P V Avatar
    Arjun P V

    Thanks for the idea for a future lesson. Stay tuned!

    1. You’re welcome @disqus_INULnH3JbA , please share our post to one of your friends if you have time. Thank you!

      Please subscribe as well: https://www.codeofaninja.com/subscribe

  16. ankush. sharma Avatar
    ankush. sharma

    this pie chrt code is not working in my systm

    1. Hi @disqus_FGWOppERt4 would you tell us the error message you encounter?

  17. 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?

  18. Hi @sneha, we used the extract($row); so it was implicitly declared based on the field name.

Leave a Reply

Your email address will not be published. Required fields are marked *