從MySql 資料庫中擷取資料 ,利用chart.js 繪制柱形圖。
檔案結構:

1.index.php檔案。從資料庫擷取資料。先連接配接資料庫exercisedata,然後從資料庫的users表中查詢學生名字userName和學生的成績score,并給userName和score取别名label和value,以符合chart.js中繪制圖形時需要的資料格式。執行sql語句後,把結果以json格式傳回。代碼如下:
<span style="font-size:18px;"> <?php
//資料庫配置
$dbconf= array(
'host'=>'127.0.0.1',
'user'=>'root',
'password'=>'123456',//因為測試,我就不設定密碼,實際開發中,必須建立新的使用者并設定密碼
'dbName'=>'exercisedata',
'charSet'=>'utf8',
'port'=>'3306' );
function openDb($dbConf){ $conn=mysqli_connect($dbConf['host'],$dbConf['user'],$dbConf['password'],$dbConf['dbName'],$dbConf['port']) or die('打開失敗');
//當然如上面不填寫資料庫也可通過mysqli_select($conn,$dbConf['dbName'])來選擇資料庫
mysqli_set_charset($conn,$dbConf['charSet']);//設定編碼
return $conn;
}
$conn=openDb($dbconf);
//2query方法執行增、查、删、改
$sql='SELECT userName as `label`, score as `value` FROM exercisedata.users';
/*************資料查詢***************************/
$rs=$conn->query($sql);
$data=array();//儲存資料
while($tmp=mysqli_fetch_assoc($rs)){//每次從結果集中取出一行資料
$data[]=$tmp;
}
//對資料進行相應的操作
echo json_encode($data);</span>
資料庫中的users
通路http://localhost/test/php/index.php 得到如下結果:
則說明資料庫連接配接成功。
2.index.html檔案。在<script></script>中引入Chart.js庫、index.js檔案, Chart.js是一個簡單、面向對象、為設計者和開發者準備的圖表繪制工具庫。在body标簽中添加一個canvas标簽,用來顯示可視化柱形圖。代碼如下:
<!DOCTYPE html>
<html >
<head>
<meta http-equiv="Content-Type" charset="UTF-8" />
<title>案例顯示</title>
<!-- <link rel="stylesheet" href="../css/ranking.css" target="_blank" rel="external nofollow" /> -->
<style type="text/css">
*
{
margin: 0px;
padding: 0px;
}
body
{
background: #EEE;
text-align:center;
}
#drawCanvas
{
background: white;
border: 1px solid #CCC;
}
</style>
</head>
<body>
<script type="text/javascript" src="../js/Chart.js"></script>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../js/index.js"></script>
<p>A班成績表</p>
<canvas id="myChart" width="600" height="400"></canvas>
</body>
</html>
3.index.js檔案。寫一個用來畫圖的js函數bar,有一個參數Data,然後編寫getdatafromDB 函數用ajax 擷取php檔案中的資料data,并調用bar方法,在window.onload函數中調用getdatafromDB函數。 bar函數分為兩部分:一部分資料設定,一部分為顯示樣式設定。
window.οnlοad=function()
{
getdatafromDB();
}
var getdatafromDB = function(){
$.ajax({
url: "../php/index.php",
type: "POST",
dataType:"json",
error: function(){
alert('Error loading XML document');
},
success:function(data){
console.info(data);
bar(data);
}
});
}
function bar(Data)
{
if(Data.length==null || Data.length == 0)
return;
var barData={};
barData.labels=[];
barData.datasets=[];
var temData={};
temData.data=[];
temData.fillColor= "rgba(151,187,205,0.5)";
temData.strokeColor = "rgba(151,187,205,0.8)";
temData.highlightFill="rgba(151,187,205,0.75)",
temData.highlightStroke= "rgba(151,187,205,1)";
for(var i=0;i<Data.length;i++)
{
barData.labels.push(Data[i].label);
temData.data.push(Data[i].value);
}
barData.datasets.push(temData); //封裝一個規定格式的barData。
console.info(barData);
/ /// 動畫效果
var options = {
scaleOverlay: false,
scaleOverride: false,
scaleSteps: null,
scaleStepWidth: null,
scaleStartValue: null,
scaleLineColor: "rgba(0,0,0,.1)",
scaleLineWidth: 1,
scaleShowLabels: true,
scaleLabel: "<%=value%>",
scaleFontFamily: "'Arial'",
scaleFontSize: 12,
scaleFontStyle: "normal",
scaleFontColor: "#666",
scaleShowGridLines: true,
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleGridLineWidth: 1,
bezierCurve: true,
pointDot: true,
pointDotRadius: 3,
pointDotStrokeWidth: 1,
datasetStroke: true,
datasetStrokeWidth: 2,
datasetFill: true,
animation: true,
animationSteps: 60,
animationEasing: "easeOutQuart",
onAnimationComplete: null
}
var ctx = document.getElementById("myChart").getContext('2d');
myChart = new Chart(ctx).Bar(barData,options, { //重點在這裡
responsive : true
});
}
通路http://localhost/test/html/index.html 測試結果如下: