我想通过发布请求从ESP8266向运行php的服务器发送一些日期。 目的是通过ESP8266和DHT22捕获数据,并通过php将其存储在mariaDB上。 我知道PDO可能更安全,但是我想先尝试这种方式。 问题在于,数据似乎已发送,但未写入数据库。
在ESP8266上运行的草图:
if (client.connect(server, 80)) {
Serial.println("connected!!");
WiFi.printDiag(Serial);
String data = "temp="
+ (String) sensorTemp
+ "&humi="
+(String) sensorHum;
client.println("POST /connect2.php HTTP/1.1");
client.print("Host: xxx.xxx.xx.xxxx\n");
client.println("User-Agent: ESP8266/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(data.length());
client.print("\n\n");
client.println (data);
client.stop();
Serial.println("\n");
Serial.println("My data string im POSTing looks like this: ");
Serial.println(data);
Serial.println("And it is this many bytes: ");
Serial.println(data.length());
delay(2000);
client.stop();
}
服务器端php:
<?php
$servername = "xxx.xxx.xx.xxx";
$username = "username";
$password = "password";
$dbname = "dbname";
$temp = $_REQUEST['temp'];
$humi = $_REQUEST['humi'];
//date_default_timezone_set('America/Toronto');
//$date=date('m-d-Y H:i:s') ;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO dbname (temp, humi)
VALUES ('$humi', '$temp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>