将MySQL数据读入highstocks

时间:2017-09-20 01:56:29

标签: javascript php jquery highcharts

所以这是我第一次真正使用高级图表我有一些数据从我的MySQL数据库读入高图表,但下一步是尝试设置一个高库存图表。每当我尝试使用与高图表相同的方法时,图表不起作用?这就是我想要的目标 - StockChartDemo

PHP代码:

$conn = new mysqli($servername, $username, $password, $dbName);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
            FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);

if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){      
  echo '['.$row["time"].',' .$row["humidity"].']';
  $count++;
   if ($count<"20"){
   echo ',';
   }      
 }
 echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>

html&amp; jQuery的:

    

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="highstock.js"></script>

</head>
<script type="text/javascript">

$(document).ready(function() {
Highcharts.setOptions({
global: {
        useUTC: false
        }
});
var options = {    
    chart: {
        renderTo: 'tempcontainer',
        alignTicks: false,
          height:320,

    },

    rangeSelector: {
        selected: 1
    },

    title: {
        text: 'Relative humidity'
    },

    series: [{
        type: 'column',
        name: 'Humidity',
        data: json,
        dataGrouping: {
            units: [[
                'month', // unit name
                [1] // allowed multiples
            ], [
                'week',
                [1, 2, 3, 4, 6]
            ]]
        }
    }]


}

$.getJSON("stockdata.php", function(json) {    /*Get the array data in data.php using jquery getJSON function*/
    options.series[0].data = json;        /*assign the array variable to chart data object*/
    chart = new Highcharts.stockChart(options); /*create a new chart*/
});

function refreshChart(){                 /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
    setInterval(function(){
        $.getJSON("stockdata.php", function(json) {
            options.series[0].data = json;
            chart = new Highcharts.stockChart(options);
        });
    },60000);
}
});

</script>
   <div id="tempcontainer"></div>

1 个答案:

答案 0 :(得分:0)

假设您的查询返回了您想要的正确数据。 (我不想嘲笑它来测试你的查询)

您应该切换出以下代码以及介于两者之间的所有代码。

if ($result->num_rows>0){
 //snip
}

改为使用json_encode()

$series = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {  
        $series[] = [
            $row["time"],
            $row["humidity"]
        ];
    }
}

header('Content-Type: application/json');
exit(json_encode($series));