Yarana Iot Guru
Published © MIT

πŸ”— ESP32 With MySQL Database Management

Log sensor data from ESP32 to a MySQL database using PHP (XAMPP or remote server). Full step-by-step guide for reliable IoT data storage

BeginnerShowcase (no instructions)8 hours31
πŸ”— ESP32 With MySQL Database Management

Things used in this project

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

ESP32 Code β€” Send Data to Server (Arduino IDE)

C/C++
/*
 ESP32 -> MySQL via PHP (HTTP GET)
 Author: YaranaIoT Guru
*/

#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"

// --- Edit these ---
const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";
const char* serverURL = "http://YOUR_SERVER_IP_OR_DOMAIN/esp32/insert.php"; // change

#define DHTPIN 4        // sensor pin
#define DHTTYPE DHT22   // or DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected. IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    delay(5000);
    return;
  }

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = String(serverURL) + "?temperature=" + String(temperature, 2) + "&humidity=" + String(humidity, 2);
    Serial.print("Request URL: ");
    Serial.println(url);

    http.begin(url);
    int httpCode = http.GET();

    if (httpCode > 0) {
      String payload = http.getString();
      Serial.print("Response: ");
      Serial.println(payload);
    } else {
      Serial.print("HTTP request failed, error: ");
      Serial.println(httpCode);
    }
    http.end();
  } else {
    Serial.println("WiFi disconnected");
  }

  delay(60000); // send every 60 seconds
}

PHP Endpoint β€” insert.php (secure basic version

C/C++
<?php
// Simple insert.php - ESP32 to MySQL (basic, add security in production)
$servername = "localhost";
$username = "root";
$password = ""; // XAMPP default
$dbname = "esp32_data";

// Get data (supports GET and POST)
$temp = isset($_REQUEST['temperature']) ? $_REQUEST['temperature'] : null;
$hum  = isset($_REQUEST['humidity']) ? $_REQUEST['humidity'] : null;

// Basic validation
if ($temp === null || $hum === null) {
    http_response_code(400);
    echo "Missing parameters";
    exit;
}

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    http_response_code(500);
    die("Connection failed: " . $conn->connect_error);
}

// Prepare statement to avoid SQL injection
$stmt = $conn->prepare("INSERT INTO sensor_data (temperature, humidity) VALUES (?, ?)");
$stmt->bind_param("dd", $temp, $hum);

if ($stmt->execute()) {
    echo "OK";
} else {
    http_response_code(500);
    echo "DB Error";
}

$stmt->close();
$conn->close();
?>

πŸ“Š Optional: Web Interface to View Data (index.php

C/C++
<?php
$mysqli = new mysqli("localhost","root","","esp32_data");
if ($mysqli->connect_error) { die("DB error"); }
$res = $mysqli->query("SELECT * FROM sensor_data ORDER BY id DESC LIMIT 50");
?>
<!doctype html>
<html>
<head><title>ESP32 Data</title></head>
<body>
<h1>Recent Sensor Data</h1>
<table border=1>
<tr><th>ID</th><th>Temperature</th><th>Humidity</th><th>Time</th></tr>
<?php while($row = $res->fetch_assoc()): ?>
<tr>
  <td><?= $row['id'] ?></td>
  <td><?= $row['temperature'] ?></td>
  <td><?= $row['humidity'] ?></td>
  <td><?= $row['created_at'] ?></td>
</tr>
<?php endwhile; ?>
</table>
</body>
</html>

Credits

Yarana Iot Guru
30 projects β€’ 0 followers
Yarana Iot Guru Yarana IoT Guru: Arduino, ESP32, GSM, NodeMCU & more. Projects, Tutorials & App Development. Innovate with us!
Thanks to YaranaIoT Guru.

Comments