2015-06-22 130 views
0

我想用mysql數據庫製作圖表。我有兩列 - 時間戳和溫度。這是時間戳格式 - 2015-06-11 22:45:59和溫度是整數。林不知道我的時間戳轉換爲JavaScript的時間是正確的,我有或可能我有其他錯誤。這是我的代碼:Highstock with php and mysql

data.php

<? 
define('DBHOST','localhost'); 
define('DBUSER','root'); 
define('DBPASS','...'); 
define('DBNAME','diplomna2'); 

try { 

    //create PDO connection 
    $db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

} catch(PDOException $e) { 
    //show error 
    echo '<p class="bg-danger">'.$e->getMessage().'</p>'; 
    exit; 
} 
$stmt = $db->query('SELECT * FROM temperature'); 

$res=array(); 
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    $row['timestamp'] = strtotime($row['timestamp']); 
    $row['timestamp'] *=1000; 

    echo $res="[".$row['timestamp'] . ',' . $row['temperature'] ."]"; 

} 
?> 

這是輸出:

[1434051959000,25][1434051969000,26][1434051979000,26][1434051990000,28][1434052000000,27][1434052024000,25][1434052034000,24][1434052044000,23] 

HTML文件:

<!DOCTYPE HTML> 
<html> 
<head> 
    <script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script> 
    <script src="http://code.highcharts.com/stock/highstock.js"></script> 
    <script src="http://code.highcharts.com/stock/modules/exporting.js"></script> 


    <script type="text/javascript"> 
     $(function() { 
      $.getJSON('data.php', function(data) { 

       // Create the chart 
       $('#container').highcharts('StockChart', { 


        rangeSelector : { 
         inputEnabled: $('#container').width() > 480, 
         selected : 1 
        }, 

        title : { 
         text : 'Temperature' 
        }, 

        series : [{ 
         name : 'temperature', 
         data : data, 
         type : 'areaspline', 
         threshold : null, 
         tooltip : { 
          valueDecimals : 2 
         }, 
         fillColor : { 
          linearGradient : { 
           x1: 0, 
           y1: 0, 
           x2: 0, 
           y2: 1 
          }, 
          stops : [ 
           [0, Highcharts.getOptions().colors[0]], 
           [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] 
          ] 
         } 
        }] 
       }); 
      }); 
     }); 
    </script> 
</head> 
<body> 

<div id="container" style="height: 400px; min-width: 310px"></div> 
</body> 
</html> 

回答

1

正確的方法,使JavaScript的瞭解你的PHP數組是json_encode()

while附近的代碼塊更改爲

$res = []; 

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    $res[] = [ strtotime($row['timestamp'])*1000, $row['temperature'] ]; 
} 

echo json_encode($res); 
+0

感謝您的快速響應。我改變了代碼,但它不再工作。 – Supreme

+0

您收到了什麼錯誤,請檢查您的瀏覽器控制檯。 – Viral

+0

>遺漏的類型錯誤:無法讀取未定義 >遺漏的類型錯誤的特性「的addEvent」:無法讀取屬性「fireEvent」未定義 > test_temperature.php的:25未捕獲的SyntaxError:意外的標識 – Supreme