官方示例(静态死数据)
https://echarts.baidu.com/examples/editor.html?c=bar-simple
本人制作(动态)
数据库
数据库代码
<?php
header("pdotent-type:text/json;charset=utf-8");
try
{
$pdo = new PDO("mysql:host=localhost;port=8806;dbname=phphomework;charset=utf8",'root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e)
{
print("Error:".$e->getMessage());
die();
}
//查询学生信息
$sql = "SELECT * FROM guizhou ";
$result = $pdo->query($sql);
//定义变量json存储值
$data="";
$array= array();
class GuiZhou{
public $id;
public $place;
public $num;
}
while ($row = $result->fetch(PDO::FETCH_ASSOC ))
{
/*$result->setFetchMode(PDO::FETCH_ASSOC);//设置结果集的读取方式,这里用的是关联的方式进行读取(mysqli)
$row=$result->fetch();//获取记录
$row = mysql_fetch_array($result,MYSQL_ASSOC)*/
//list($id,$place,$num) = $row;
/*
echo $id.' ';
echo $place.' ';
echo $num;
echo '<br >';
*/
$gz = new GuiZhou();
$gz->id = $row['id'];
$gz->place = $row['place'];
$gz->num = $row['num'];
//数组赋值
$array[] = $gz;
}
$data = json_encode($array);
echo $data;
//echo $array;
//echo 0;
//{"id":"1","place":"\u8d35\u9633\u5e02","num":"5"}
?>
展示部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="echarts.min.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
var places=[], nums=[];
function TestAjax(){
$.ajax({
type: "post",
async: false,
url: "sql.php",
data: {},
dataType: "json",
success: function(result) {
if (result) {
for (var i = 0; i < result.length; i++) {
places.push(result[i].place);
nums.push(result[i].num);
console.log(result[i].place);
console.log(result[i].num);
}
}
}
})
return places, nums;
}
TestAjax();
var option = {
title: {
text: 'ECharts+Ajax+MySQL+PHP'
},
tooltip: {
show : true
},
legend: {
data:['num']
},
xAxis: [{
type : 'category',
data : places
}],
yAxis: [{
type : 'value'
}],
series: [{
name : "num",
type : "bar",
data : nums
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>