fhem-unwetter/index.php

72 lines
2.6 KiB
PHP
Raw Normal View History

2024-08-13 14:32:02 +02:00
<?php
$servername = "databaseserver";
$username = "wetterquery";
$password = "securepassword";
$dbname = "wetter";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
$jsonres = array("Error"=>$conn->connect_error);
die("Connection failed: " . $conn->connect_error);
}
$conn->query("SET NAMES utf8");
//reported-einträge nach 8h löschen
$sqlx = "DELETE FROM reported WHERE datetime < (NOW() - INTERVAL 8 HOUR)";
$resultx = $conn->query($sqlx);
$sql = "SELECT * FROM warnungen ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$warn = str_replace("\n"," - ", $row["warnung"]);
$warn = preg_replace('/[[:^print:Ä-Üä-ü]]/', "", $warn);
$warn = str_replace("|", "", $warn);
$warn = str_replace(" | "," - ", $warn);
$warn = str_replace("ö","oe", $warn);
$warn = str_replace("ä","ae", $warn);
$warn = str_replace("ü","ue", $warn);
$warns = explode(" - ", $warn);
if (count($warns) == 1) {
$warncombined = $warns[0];
} elseif (count($warns) >= 4) {
$warncombined = $warns[0]." - ".$warns[count($warns)-2]." ".$warns[count($warns)-1];
} else {
$warncombined = $warns[0]." - ".$warns[count($warns)-1];
}
//wenn letzter Eintrag "keine meldungen" ist, gesamte reported-liste löschen damit ein erneutes gewitter innerhalb von 8h gemeldet wird
if ($row["typ"] == "OK"){
$sqly = "DELETE FROM reported";
$resulty = $conn->query($sqly);
}
//prüfung ob diese meldung bereits in reported vorhanden ist
$sql4 = "SELECT * FROM reported WHERE warnung='".$warncombined."'";
$result4 = $conn->query($sql4);
$rowcount = mysqli_num_rows($result4);
//wenn ja, verwerfen und neuesten Eintrag aus reported lesen und ausgeben
if ($rowcount != 0)
{
$sql3 = "SELECT * FROM reported ORDER BY id DESC LIMIT 1";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
while ($row3 = $result3->fetch_assoc()) {
$jsonres = array("warnung"=>$row3["warnung"], "typ"=>$row["typ"], "last_update"=>$row["datetime"]);
}
}
} else {
//wenn nein, aktuelle meldung ausgeben und in reported schreiben
$jsonres = array("warnung"=>$warncombined, "typ"=>$row["typ"], "last_update"=>$row["datetime"]);
$sql2 = "INSERT INTO reported (warnung) VALUES ('".$warncombined."')";
$result2 = $conn->query($sql2);
}
}
} else {
$jsonres = array("Error"=>"No result from database.");
}
$conn->close();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($jsonres, JSON_UNESCAPED_UNICODE);
?>