gpt4 book ai didi

php - 从mysql数据库中绘制

转载 作者:行者123 更新时间:2023-11-28 23:57:46 25 4
gpt4 key购买 nike

我试图用从 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>

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

最佳答案

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

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

关于php - 从mysql数据库中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31088354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com