53 lines
1.7 KiB
PHP
53 lines
1.7 KiB
PHP
<?php
|
|
include_once "db_config.php";
|
|
date_default_timezone_set('Asia/Shanghai');
|
|
header("Content-Type: application/json"); // 返回 JSON 格式的响应
|
|
header("Access-Control-Allow-Origin: *"); // 允许跨域请求
|
|
header("Access-Control-Allow-Methods: POST, OPTIONS"); // 允许的方法
|
|
header("Access-Control-Allow-Headers: Content-Type"); // 允许的请求头
|
|
|
|
|
|
// 处理 OPTIONS 请求
|
|
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
|
http_response_code(204);
|
|
exit();
|
|
}
|
|
|
|
// 获取原始 POST 数据
|
|
$input = json_decode(file_get_contents("php://input"), true); // 将 JSON 转换为 PHP 数组
|
|
|
|
// 检查是否成功解析 JSON
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
echo json_encode(["error" => "无效的 JSON 数据"]);
|
|
exit();
|
|
}
|
|
|
|
$local_temperature = $input["Temperature"] ?? "";
|
|
$local_humidity = $input["Humidity"] ?? "";
|
|
|
|
//$standby = $input["status"]["standby"] ?? 0;
|
|
//$reboot = $input["status"]["reboot"] ?? 0;
|
|
//$humidifier = $input["status"]["humidifier"] ?? 0;
|
|
//$screen = $input["status"]["screen"] ?? 1;
|
|
|
|
|
|
$time = time();
|
|
$date = date("Y-m-d H:i:s", $time);
|
|
|
|
$queryString = "INSERT INTO localdata (time, temperature, humidity) VALUES ('$date', '$local_temperature', '$local_humidity')";
|
|
|
|
mysqli_query($conn, $queryString);
|
|
if(mysqli_error($conn)){
|
|
echo json_encode(["error" => "数据库错误"]);
|
|
}
|
|
|
|
$queryString = "select * FROM status";
|
|
$result = mysqli_query($conn, $queryString);
|
|
if(mysqli_num_rows($result) > 0){
|
|
$data = []; // 初始化为空数组
|
|
while ($row = mysqli_fetch_object($result)) { // 获取查询结果作为对象
|
|
$data[] = $row; // 将对象追加到数组中
|
|
echo substr(json_encode($data),1, 58); // 返回 JSON 格式的响应
|
|
}
|
|
}
|