Home > Database > Mysql Tutorial > How Can I Generate a Google Chart from MySQL Data Using PHP and JSON?

How Can I Generate a Google Chart from MySQL Data Using PHP and JSON?

Barbara Streisand
Release: 2024-12-05 01:20:11
Original
785 people have browsed it

How Can I Generate a Google Chart from MySQL Data Using PHP and JSON?

PHP-MySQL Google Chart JSON: A Complete Guide

Problem:

Generating a Google Chart using MySQL table data as the data source can be challenging, especially when working with PHP.

Solution:

Here's a comprehensive example that demonstrates how to use PHP, MySQL, and JSON to create a pie chart from data stored in a MySQL table.

Usage:

  • Requirements: PHP, Apache, and MySQL
  • Install:

    • Create a "chart" database in phpMyAdmin.
    • Create a "googlechart" table with two columns: "weekly_task" and "percentage".
    • Insert data into the table with numerical values for percentage.

PHP-MySQL-JSON-Google Chart Example:

<?php
// Connect to MySQL
$con = mysql_connect("localhost", "Username", "Password") or die("Failed to connect!");
mysql_select_db("Database Name", $con);

// Query the "googlechart" table
$sth = mysql_query("SELECT * FROM googlechart");

// Create a JSON table for Google Chart
$table = array(
    'cols' => array(
        array('label' => 'Weekly Task', 'type' => 'string'),
        array('label' => 'Percentage', 'type' => 'number')
    ),
    'rows' => array()
);

// Populate the JSON table with data
while ($r = mysql_fetch_assoc($sth)) {
    $rows[] = array('c' => array(
        array('v' => (string) $r['Weekly_task']),
        array('v' => (int) $r['percentage'])
    ));
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);

// Include necessary scripts and draw the chart
?>

<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>
Copy after login

Note: For other types of charts (e.g., bar charts), minor modifications to the code may be necessary.

PHP-PDO-JSON-MySQL-Google Chart Example (Alternative):

Utilizes the PHP Data Objects (PDO) extension for improved exception handling and flexibility.

PHP-MySQLi-JSON-Google Chart Example (Alternative):

Leverages the MySQLi extension for additional functionality, such as prepared statements.

Short Tag Syntax Error:

If you encounter a syntax error related to short tags (e.g., "".

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template