You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP读取MySQL数据直接传入Dygraph渲染IoT图表报错如何解决

问题排查
  • 首要原因是PHP代码未被服务器解析,直接原样返回给浏览器,浏览器将<?php识别为JS语法的非法字符,触发Unexpected token '<'报错,排查点如下:
    1. 确认文件后缀为.php,只有.php后缀的文件才会触发Web服务器的PHP解析逻辑,若使用.html后缀PHP代码不会执行
    2. 确认通过http://localhost/对应文件路径.php访问页面,直接双击打开本地文件走file://协议不会触发PHP解析
    3. 确认Web服务(Nginx/Apache)和PHP服务正常运行,且已正确配置PHP解析规则
  • 代码本身存在的问题:
    1. HTML结构错误,<head>标签内嵌套了<body>标签,会导致浏览器解析异常
    2. 循环输出的Dygraph数据数组末尾多余逗号,部分JS运行环境会触发语法错误
    3. $lastutime、$dcount变量未初始化就使用,PHP警告输出会破坏JS代码结构
    4. 使用$_SESSION前未调用session_start(),会抛出PHP错误
修复后的完整实现代码
<?php
session_start();
// 提前处理数据逻辑,避免报错污染JS代码
$mysql_host = "localhost:3306";
$mysql_db = "mqtt";
$mysql_user = "你的数据库用户名";
$mysql_pw = "你的数据库密码";
$mysql_table = "analog_data";
$chartData = [];
$dcount = 0;

$connection = mysqli_connect($mysql_host, $mysql_user, $mysql_pw, $mysql_db);
if ($connection) {
    $result = $connection->query("SELECT DATE_FORMAT(datum, '%Y/%m/%d %H:%i:%s') AS date, datum, analog0, analog1 FROM ".$mysql_table);
    $lastutime = 0;
    while($row = mysqli_fetch_assoc($result)) {
        $utime = strtotime($row['datum']);
        $diffutime = $utime - $lastutime;
        if ($diffutime > 600) {
            $chartData[] = "[new Date(\"{$row['date']}\"), NaN, NaN]";
        } else {
            $chartData[] = "[new Date(\"{$row['date']}\"), {$row['analog0']}, {$row['analog1']}]";
        }
        $lastutime = $utime;
        $dcount++;
    }
    mysqli_close($connection);
}
$_SESSION["dcount"] = $dcount;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>IoT数据图表</title>
    <script src="dygraph.js"></script>
</head>
<body style="color: #000; background-color: #373737;">
    <div style="text-align: center; color: #fff;">Test<br><br></div>
    <table style="margin: 0 auto;" border="0" width="500">
        <tr>
            <td style="background-color: #fff;">
                <div id="graphdiv2" style="width: 500px; height: 300px;"></div>
            </td>
        </tr>
    </table>
    <div style="text-align: center; color: #fff;">
        <br><?php echo $_SESSION["dcount"]; ?> D
    </div>
    <script>
        const dygraphData = [<?php echo implode(',', $chartData); ?>];
        const g2 = new Dygraph(
            document.getElementById("graphdiv2"),
            dygraphData,
            {
                rightGap: 20,
                connectSeparatedPoints: true,
                labels: ["Datum", "A0", "A1"]
            }
        );
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:24:03