2013-07-11 65 views
0

我想爲我的數據庫表創建一個餅圖字符。使用PHP和谷歌圖表從MySQL數據庫創建餅圖字符

temp -> with columns(id, sent, pcount, ncount) 

pcountncount是INT數。我想爲這兩個值創建一個餅圖。

我想加載這個文件。

<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/jquery.min.js"></script> 
<script type="text/javascript"> 
google.load("visualization", "1", {packages:["corechart"]}); 
google.setOnLoadCallback(drawChart); 

function drawChart() 
{ 
    var jsonData = $.ajax({ 
     url: "graphData.php", 
     dataType:"json", 
     async: false 
}).responseText; 

// Create our data table out of JSON data loaded from server. 
var data = new google.visualization.DataTable(jsonData); 

var options = {'title':'Ticket Sales', 
'width':500,  
'height':400}; 

// Instantiate and draw our chart, passing in some options. 
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); 
chart.draw(data,options); 
} 
</script> 
</head> 

<body> 
    <!--Div that will hold the pie chart--> 
    <div id="chart_div"></div> 
</body> 


</html> 

graphData.php內容如下。

<?php 

$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test'); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: ".mysqli_connect_error(); 
} 

$sql = "SELECT pcount,count(*) AS count from temp"; 

if ($result=mysqli_query($con,$sql)) 
{ 
    $rownum=mysqli_num_rows($result); 
    printf("Result set has %d rows.\n",$rownum); 
    mysqli_free_result($result); 
} 

//start the json data in the format Google Chart js/API expects to receieve it 
$data = array('cols' => array(array('label' => 'pcount', 'type' => 'int'), 
           array('label' => 'mcount', 'type' => 'int')), 
       'rows' => array()); 

while($row = mysqli_fetch_row($result)) { 
    $data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1]))); 
}  

echo json_encode($data); 
?> 

我已將這段代碼從網頁中取出並根據需要進行了修改。當我加載我的第一個PHP頁面時,它什麼都沒顯示。我究竟做錯了什麼?

+1

爲什麼你使用ajax?直接發送值到餅圖函數拋出php。 – Zia

+0

@Zia:你能告訴我我需要做些什麼改變嗎?我真的很抱歉不知道在這裏刪除阿賈克斯! – user123

回答

2

這是從PHP的我的sql表創建PIE圖表(只需更改其他圖表的函數名稱)的代碼。

要記住重要的一點是

array('label' => 'ind_type', 'type' => 'string'), 
    array('label' => 'sum', 'type' => 'number') 

ind_type和金額都在我的表中的列,第一VAR應該是串在這裏。

<?php 
/* 
Script : PHP-JSON-MySQLi-GoogleChart 
Author : Enam Hossain 
version : 1.0 

*/ 

/* 
-------------------------------------------------------------------- 
Usage: 
-------------------------------------------------------------------- 

Requirements: PHP, Apache and MySQL 

Installation: 

    --- Create a database by using phpMyAdmin and name it "chart" 
    --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that 
    --- Specify column names as follows: "weekly_task" and "percentage" 
    --- Insert some data into the table 
    --- For the percentage column only use a number 

     --------------------------------- 
     example data: Table (googlechart) 
     --------------------------------- 

     weekly_task  percentage 
     -----------  ---------- 

     Sleep   30 
     Watching Movie 10 
     job    40 
     Exercise  20  


*/ 

    /* Establish the database connection */ 
// $mysqli = new mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test'); 

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

    $mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test'); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: ".mysqli_connect_error(); 
} 

    /* select all the weekly tasks from the table googlechart */ 
    $result = $mysqli->query('SELECT * FROM new_temp'); 

    /* 
     --------------------------- 
     example data: Table (googlechart) 
     -------------------------- 
     Weekly_Task  percentage 
     Sleep   30 
     Watching Movie 10 
     job    40 
     Exercise  20  
    */ 



    $rows = array(); 
    $table = array(); 
    $table['cols'] = array(

    // Labels for your chart, these represent the column titles. 
    /* 
     note that one column is in "string" format and another one is in "number" format 
     as pie chart only required "numbers" for calculating percentage 
     and string will be used for Slice title 
    */ 

    array('label' => 'ind_type', 'type' => 'string'), 
    array('label' => 'sum', 'type' => 'number') 

); 
    /* Extract the information from $result */ 
    foreach($result as $r) { 

     $temp = array(); 

     // The following line will be used to slice the Pie chart 

     $temp[] = array('v' => (string) $r['ind_type']); 

     // Values of the each slice 

     $temp[] = array('v' => (int) $r['sum']); 
     $rows[] = array('c' => $temp); 
    } 

$table['rows'] = $rows; 

// convert data into JSON format 
$jsonTable = json_encode($table); 
//echo $jsonTable; 


?> 


<html> 
    <head> 
    <!--Load the Ajax API--> 
    <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"> 

    // Load the Visualization API and the piechart package. 
    google.load('visualization', '1', {'packages':['corechart']}); 

    // Set a callback to run when the Google Visualization API is loaded. 
    google.setOnLoadCallback(drawChart); 

    function drawChart() { 

     // Create our data table out of JSON data loaded from server. 
     var data = new google.visualization.DataTable(<?=$jsonTable?>); 
     var options = { 
      title: 'Index analysis', 
      is3D: 'true', 
      width: 800, 
      height: 600 
     }; 
     // Instantiate and draw our chart, passing in some options. 
     // Do not forget to check your div ID 
     var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
     chart.draw(data, options); 
    } 
    </script> 
    </head> 

    <body> 
    <!--this is the div that will hold the pie chart--> 
    <div id="chart_div"></div> 
    </body> 
</html> 
2

我已將這段代碼從網頁中刪除,並根據我的需要進行了修改。當我加載我的第一個PHP頁面時,它什麼都沒顯示。我究竟做錯了什麼?

您顯然已經錯誤地修改了腳本而不是您的需要。否則,你不會問你做錯了什麼。

詢問「我做錯了什麼?」意味着你不理解代碼。您的修改,您需要做的第一件事是退回到代碼的最後一個工作版本。

因此現在提交您的更改,然後將您的腳本比較爲最後一個工作提交。這會向您顯示您的更改,並且更容易找到引入錯誤的部分。

+0

我同意你的觀點,但之前的代碼是使用json文件做的東西,我沒有json文件,我也不熟悉它! – user123

+0

@Karimkhan:如果您選擇的示例修改太複雜了,請使用其他示例,而不是您可以理解的示例。修改我不理解的代碼通常效果不佳。我要麼開始理解它,要麼我慘敗。我想這與其他人也很相似。 – hakre

+0

感謝哥們,我做到了! – user123