从 mysql 数据库中绘制

Plot from mysql database

我正在尝试使用从 MySQL 数据库获得的数据绘制一个简单的 x-y 折线图。代码如下:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
</head>
<body>
    <h3><b>Database</b></h3>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "prueba2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password, email, x, y FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    echo "<table>
             <tr>
                 <th>ID</th>
                 <th>Username</th>
                 <th>Password</th>
                 <th>Email</th>
                 <th>X</th>
                 <th>Y</th>
               </tr>";
     // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
             <tr>
                 <td>" . $row["id"]. "</td>
                 <td>" . $row["username"]. "</td>
                 <td>" . $row["password"]. "</td>
                 <td>" . $row["email"]. "</td>
                 <td>" . $row["x"]. "</td>
                 <td>" . $row["y"]. "</td>
            </tr>";
    }
    echo "</table>";
    $dataset1 = array();
    while ($row = $result->fetch_assoc()) {
        $dataset1[] = array(intval($row["x"]),intval($row["y"]));
    }
} else {
     echo "0 results";
}
$conn->close();
?>
<br>
<h3>Test plot</h2>
<div id="placeholder"></div>
<script type="text/javascript">
        var dataset1 = <?php echo json_encode($dataset1); ?>;
        $(function () {
             $.plot($("#placeholder"), [ dataset1 ]);
        });
</script>
</body>
</html>

我得到的结果是 table 完美设置但是一个空的 Flot Chart 图。这就是说数据已正确加载,但我无法绘制它或将其存储在变量中,或者可能未放置 flot 图表语法 well/well。有什么建议么?谢谢!

问题是对数组的赋值是在第一个 while 之后完成的,它为 html table 生成行,而服务器已经获取了结果。所以第二个循环立即退出而不分配任何东西。

您应该在 echo 语句之后的第一个循环内进行赋值。