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

时间:2017-03-11 10:23:16

标签: php mysql json arduino

我是按照以下格式从Arduino MCU转储json,

  

{"活" :[{" location" :"户外" ," temperatureInC" :" 33.90" ,   " temperatureInF" :" 93.02" ,"露点_in_Fahr" :" 21.18" ,   " dewPoint_in_Cel" :" -6.01" ," heat_index__in_Fahr" :" 87.17" ,   " heat_index_in_Cel" :" 30.65" ,"湿度":" 7.40" ," UVSig":" 131.44"}   ,{" location" :"绘图室" ," temperatureInC" :" 31.20" ,   " temperatureInF" :" 88.16" ,"露点_in_Fahr" :" 46.78" ,   " dewPoint_in_Cel" :" 8.21" ," heat_index__in_Fahr" :" 85.03" ,   " heat_index_in_Cel" :" 29.46" ,"湿度" :" 24.00"}]," pot" :   [{" 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,我想用mysql从mysql中检索数据并转储{armino live的格式json,只是更换按钮livedatabase

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

1 个答案:

答案 0 :(得分:0)

要获取您需要选择的所有列,而不是查询中的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);
  

注意:   您始终可以使用json_decode将JSON字符串转换回原始结果数组。