Home >Backend Development >PHP Tutorial >How to Create a Google Chart from MySQL Data Using PHP?

How to Create a Google Chart from MySQL Data Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 10:00:13232browse

How to Create a Google Chart from MySQL Data Using PHP?

PHP MySQL Google Chart JSON - Complete Example

This question pertains to generating Google Charts using a combination of PHP and MySQL. The use of Ajax is not covered in this particular example.

Usage

Requirements

  • PHP
  • Apache
  • MySQL

Installation

  1. Create a database named "chart" using phpMyAdmin.
  2. Create a table named "googlechart" with two columns: "weekly_task" and "percentage."
  3. Insert sample data into the table, ensuring that the "percentage" column contains only numbers.

Code Examples

PHP-MySQL-JSON-Google Chart Example

<?php
// Database connection
$con = mysql_connect("localhost", "Username", "Password");
mysql_select_db("Database Name", $con);

// Query
$sth = mysql_query("SELECT * FROM chart");

// Data preparation
$table['cols'] = array(
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')
);

$rows = array();
while ($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    $temp[] = array('v' => (string)$r['Weekly_task']);
    $temp[] = array('v' => (int)$r['percentage']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

// HTML
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {'packages':['corechart']});
      google.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
        var options = {
            title: 'My Weekly Plan',
            is3D: 'true',
            width: 800,
            height: 600
        };
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div>

PHP-PDO-JSON-MySQL-Google Chart Example

<?php
// Database connection
$dbname = 'chart';
$username = 'root';
$password = '123456';

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Query
$result = $conn->query('SELECT * FROM googlechart');

// Data preparation
$rows = array();
$table['cols'] = array(
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')
);

foreach ($result as $r) {
    $temp = array();
    $temp[] = array('v' => (string)$r['weekly_task']);
    $temp[] = array('v' => (int)$r['percentage']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

// HTML
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {'packages':['corechart']});
      google.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
        var options = {
            title: 'My Weekly Plan',
            is3D: 'true',
            width: 800,
            height: 600
        };
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div>

PHP-MySQLi-JSON-Google Chart Example

<?php
// Database connection
$DB_NAME = 'chart';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '123456';

$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Query
$result = $mysqli->query('SELECT * FROM googlechart');

// Data preparation
$rows = array();
$table['cols'] = array(
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')
);

foreach ($result as $r) {
    $temp = array();
    $temp[] = array('v' => (string)$r['weekly_task']);
    $temp[] = array('v' => (int)$r['percentage']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

// HTML
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {'packages':['corechart']});
      google.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
        var options = {
            title: 'My Weekly Plan',
            is3D: 'true',
            width: 800,
            height: 600
        };
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div>

Troubleshooting

If you encounter the following error:

syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);

This indicates that your environment does not support short tags. To resolve this issue, use this code instead:

<?php echo $jsonTable; ?>

The above is the detailed content of How to Create a Google Chart from MySQL Data Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn