php - 从 mysql 中检索数据并从 php 中输出 json

标签 php mysql json arduino

我正在从 Arduino MCU 转储 json采用以下格式,

{"live" : [{"location" : "Outdoor" , "temperatureInC" : "33.90" , "temperatureInF" : "93.02" , "dewPoint_in_Fahr" : "21.18" , "dewPoint_in_Cel" : "-6.01" , "heat_index__in_Fahr" : "87.17" , "heat_index_in_Cel" : "30.65" , "humidity":"7.40" , "UVSig":"131.44"} , {"location" : "Drawing Room" , "temperatureInC" : "31.20" , "temperatureInF" : "88.16" , "dewPoint_in_Fahr" : "46.78" , "dewPoint_in_Cel" : "8.21" , "heat_index__in_Fahr" : "85.03" , "heat_index_in_Cel" : "29.46" , "humidity" : "24.00"}] , "pots" : [{"soilMoist" : "118", "avgSoilMoist" :"125" }]}

此数据是实时的,但我的 Arduino 也正在转储到 mysql 服务器。

我想使用 php 检索并在前端显示它

我对 php 知之甚少,写了下面的代码,成功地将数据从 mysql 服务器转储到浏览器中:

<?php
header('Content-type: application/json');

$servername = "localhost";
$username = "username";
$password = "secret";
$dbname = "arduinoData";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT  timeStamp, out_temperature, out_humidity FROM sensorLog ORDER BY timeStamp DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br>Time: ". $row["timeStamp"]. "<br>Temperature: ". $row["out_temperature"]. "<br>Humidity: " . $row["out_humidity"] . "<$
     }
} else {
     echo "0 results";
}

$conn->close();
?>

然而,这只会吐出两个 3 列的表,甚至没有正确的 json,我想使用 php 和转储 json 从 mysql 检索数据,格式与我从 arduino live 获得的格式相同,除了将按钮 live 替换为 database

如果我想在客户端的前端页面上直播或从数据库中检索数据,这将很有用。任何帮助将不胜感激。我是 php 的新手。

最佳答案

要获取所有列,您需要选择 * 而不是查询中的 3 个特定列名。要获得有效的 JSON 对象,您只需使用 PHP json_encode 函数对结果进行编码,如下例所示:

$sql = "SELECT  * FROM sensorLog ORDER BY timeStamp DESC LIMIT 1";
$result  = $conn->query($sql);

$rows = $result->fetch_all(MYSQLI_ASSOC);
header('Content-Type: application/json');
echo json_encode($rows);

NOTE: You can always use json_decode to convert the JSON string back to the original results array.

关于php - 从 mysql 中检索数据并从 php 中输出 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734015/

相关文章:

Java程序动态加载mysql

mysql - 将两列合并为同一表中的单列

json - 几秒钟后快速刷新 JSON 数据

javascript - JSON.解析 : unexpected character at line 1 column 1 of the JSON data in Firefox only

php - 大量数据的 HighChart 不起作用

php - 具有多个参数的 Laravel FindOrNew

php - PHP 中的子域漂亮 URL

php - 如何修复PHP中的“ header 已发送”错误

MySQL 条件求和

c# - Json序列化为空