数据库中的谷歌图表混淆了

时间:2014-05-02 12:13:51

标签: javascript json charts google-visualization

可能是我要求更多,但是已经从GoogleCharts创建了一个简单的图表。 问题是我必须手动输入我想从数据库中填充的值。我知道有JSON可以做到这一点,但我浪费了4个小时的努力。 守则是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['corechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
          ['x', 'Cats', 'Blanket 1', 'Blanket 2'],
          ['A',   1,       1,           0.5],
          ['B',   2,       0.5,         1],
          ['C',   4,       1,           0.5],
          ['D',   8,       0.5,         1],
          ['E',   7,       1,           0.5],
          ['F',   7,       0.5,         1],
          ['G',   8,       1,           0.5],
          ['H',   4,       0.5,         1],
          ['I',   2,       1,           0.5],
          ['J',   3.5,     0.5,         1],
          ['K',   3,       1,           0.5],
          ['L',   3.5,     0.5,         1],
          ['M',   1,       1,           0.5],
          ['N',   1,       0.5,         1]
        ]);

        // Create and draw the visualization.
        new google.visualization.LineChart(document.getElementById('visualization')).
            draw(data, {curveType: "function",
                        width: 500, height: 400,
                        vAxis: {maxValue: 10}}
                );
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 500px; height: 400px;"></div>
  </body>
</html>
​

现在我想从我的数据库中取出数据而不是手动写入它。为此,我创建了一个PHP文件并从MySQL DB中获取数据。

mysql_connect("localhost","root","");
mysql_select_db("db_graph");

$return_arr = array();
$fetch = mysql_query("SELECT * FROM tbl_graph"); 

感谢任何形式的帮助!

3 个答案:

答案 0 :(得分:1)

请至少使用mysqli(或PDO),而不是因为不推荐使用mysql。 http://us3.php.net/manual/en/mysqli.query.php

您需要为API提供一系列数组&#39; (以数字方式编制索引,尽管在进入JS层之前这无关紧要)。而且,您必须提供列名作为第一行:

<?php
$rows = array(
    array('Column 1', 'Column 2', 'Column 3'),
);

// Add the data
// With mysqli_query, the link argument is first and is required
$result = mysqli_query($conn, 'SELECT a, b, c FROM some_table');
while (($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    // should be array('column a value', 'column b value', 'column c value');
    $rows[] = $row;
}

// You can force the array to be numeric, but this should not be necessary
// because MYSQLI_NUM was used, and [] was used to append which means use
// numeric indices
// This is just more extra defensive coding if preferred
//foreach ($rows as $k => $v) {
//    $rows[$k] = array_values($v);
//}
//$rows = array_values($rows);

// Give the data to the front-end, with correct content type (assuming JSON here)
header('Content-Type: application/json');
print(json_encode($rows));

现在您需要获取该数据。我建议使用像jQuery这样的AjAX库。在drawVisualization()函数中:

$.getJSON('/some-endpoint/', function (data) {
    // Since this is the success callback, the data argument is your data from the server
    // Since $.getJSON() is used, there is no need to parse JSON here
    new google.visualization.LineChart(document.getElementById('visualization')).
        draw(data, {curveType: "function",
                        width: 500,
                        height: 400,
                        vAxis: {maxValue: 10}});
}).fail(function () { /* do something */ });

如果在每种情况下都无法使数组成为数字,那么您将获得一个带有对象的JSON流(例如:{'0': [1]}而不是[[1]]),并且可视化将无法生成。

答案 1 :(得分:1)

首先,不要使用mysql_ *函数,因为它们不安全并且已弃用。请改用PDO或mysqli。这是一个PDO示例:

<?php
// $databaseName is the database to access
// $username is the user name to log in with
// $password is the user name's password for logging in
$databaseName = 'db_graph';
$username = 'root';
$password = '';
try {
    $db = new PDO("mysql:dbname=$databaseName", $username, $password);
}
catch (PDOException $e) {
    echo $e->getMessage();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// use bound parameters in the query to avoid SQL injection
$queryStr = "SELECT foo, bar, baz FROM myTable WHERE cad = :cadValue";
$params['cadValue'] = $_GET['cad'];

$query = $db->prepare($queryStr);
$query->execute($params);
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$table = array(
    'cols' => array(
        // each element in this array is 1 column in the DataTable
        // you must specify a type for each column, the label is optional
        array('label' => 'foo', 'type' => 'string'),
        array('label' => 'bar', 'type' => 'number'),
        array('label' => 'baz', 'type' => 'number')
    ),
    'rows' => array()
);

foreach ($results as $row) {
    $table['rows'][] = array('c' => array(
        array('v' => $row['foo']),
        array('v' => $row['bar']),
        array('v' => $row['baz'])
    ));
}

// gracefully exit the database
$results = null;
$query = null;
$db = null;

$json = json_encode($table, JSON_NUMERIC_CHECK);

// you can output $json directly to javascript, or set this up as a data source and use AJAX to query it

答案 2 :(得分:0)

数据库中出现的数据不会采用JSON格式,因此您需要做一些JSON编码工作,然后在google API中使用它。所以做一个文档写或其他什么,这样你就可以看到从SQL查询返回的内容,然后将它与你当前在javascript中使用的JSON进行比较。您基本上需要对数组进行json_encode,请参阅:JSON encode MySQL results