Hello everyone,
I am having a problem sending data from an ESP32 board to a MySQL database by inserting it into a table.
Unfortunately, the PHP script does not seem to read the data received from the ESP32 board to insert it into the database table. Here are my codes and the result obtained on the serial monitor in Arduino IDE:
Arduino code:
#include <WiFi.h>
#include <HTTPClient.h>
String URL = "http://192.168.1.**/dht11_project/test_data.php";
const char* ssid = "**************";
const char* password = "******";
int temperature = 50;
int humidity = 50;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
connectWiFi();
}
void loop() {
// put your main code here, to run repeatedly:
if(WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
String postData = "temperature=" + String(temperature) + "&humidity=" + String(humidity);
HTTPClient http;
http.begin(URL);
int httpCode = http.POST(postData);
String payload = http.getString();
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Serial.print("URL : "); Serial.println(URL);
Serial.print("Data : "); Serial.println(postData);
Serial.print("httpCode : "); Serial.println(httpCode);
Serial.print("payload : "); Serial.println(payload);
Serial.println("------------------------------------------------------");
}
void connectWiFi(){
WiFi.mode(WIFI_OFF);
delay(1000);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("connected to : "); Serial.println(ssid);
Serial.print("IP address : "); Serial.println(WiFi.localIP());
}
PHP code :
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "sensor_db";
$conn = mysqli_connect ($hostname, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Database connection is OK<br>";
if(isset($_POST["temperature"]) && isset($_POST["humidity"])) {
$t = $_POST["temperature"];
$h = $_POST["humidity"];
$sql = "INSERT INTO dht11 (temperature, humidity) VALUES (".$t.", ".$h.")";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
Result :
Connecting to WiFi
..connected to : ***********
IP address : 192.168.1.**
URL : http://192.168.1.**/dht11_project/test_data.php
Data : temperature=50&humidity=50
httpCode : 200
payload : Database connection is OK
Any help or suggestions to resolve this issue would be greatly appreciated.
Thanks in advance !