ESP32 MySQL Database: Save Sensor Data with PHP and HTTP POST
Send ESP32 sensor data to a MySQL database with PHP: XAMPP setup, table structure, HTTPClient POST, API key, listing records and fixing -1, 404 and 500 errors.
An ESP32 MySQL database setup is the most robust way to store sensor data and look back at it days later. The ESP32 measures temperature, humidity or water level and sends it over Wi-Fi to a PHP script with an HTTP POST request; PHP then writes the data into a MySQL table. The records live on your computer or on a web host, where you can export them to Excel, draw charts or list them as a table in the browser.
This guide starts from scratch: you'll set up a local server on your computer with XAMPP, create the table, write an insert script protected by an API key, make the ESP32 send a POST request with HTTPClient, and list the records on a web page. At the end you'll also find what the common -1, 404 and 500 error codes mean and how to fix them.

Why doesn't the ESP32 connect to MySQL directly?
There are libraries online that connect the ESP32 straight to MySQL on port 3306, but that approach bakes the database username and password into the board and requires the database port to be open on the network. Anyone who gets the board or into your network can reach the whole database. Putting a PHP script in between is both safer and simpler: the ESP32 only speaks HTTP, the same language web browsers use, the password stays on the server, PHP checks the incoming data, and almost every web host offers PHP and MySQL out of the box.
| Layer | Job | In this guide |
|---|---|---|
| ESP32 | Reads the sensor, sends the data with HTTP POST | DHT22 + HTTPClient |
| Web server | Receives the request and runs PHP | Apache inside XAMPP |
| PHP script | Checks the API key and the data, writes to the table | insert.php |
| Database | Stores the records and lets you query them | MySQL / MariaDB |
| Display | Shows the records as a table | list.php and phpMyAdmin |
Step 1: set up a local server with XAMPP
- Install XAMPP (Windows, macOS or Linux version) and open the XAMPP Control Panel.
- Press Start on the Apache and MySQL rows; both should turn green. The MySQL in XAMPP is actually MariaDB, a compatible fork, which makes no difference to the code.
- Open http://localhost/phpmyadmin in your browser; we'll create the database here from the SQL tab.
- Create a folder called esp32-data inside XAMPP's htdocs folder (C:\xampp\htdocs on Windows); the PHP files go here.
- Find your computer's local IP address: on Windows type ipconfig in the command prompt and look at the IPv4 address, on macOS and Linux check the network settings (e.g. 192.168.1.50).
- From a phone on the same Wi-Fi, open http://192.168.1.50/esp32-data/; if the page loads, the ESP32 can reach the server too.
Step 2: database and table structure
1-- Veritabanı ve tablo / database and table
2CREATE DATABASE IF NOT EXISTS esp32_db
3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
4USE esp32_db;
5
6CREATE TABLE IF NOT EXISTS sensor_readings (
7 id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
8 device VARCHAR(32) NOT NULL, -- hangi ESP32 / which ESP32
9 temperature DECIMAL(5,2) NOT NULL, -- °C, ör. / e.g. 23.45
10 humidity DECIMAL(5,2) NOT NULL, -- % bağıl nem / relative humidity
11 created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
12 INDEX idx_device_time (device, created_at)
13);
14
15-- Yalnız ekleme ve okuma yetkili kullanıcı / user that can only insert and read
16CREATE USER IF NOT EXISTS 'esp32'@'localhost' IDENTIFIED BY 'Cambia-Esta-Clave-91';
17GRANT INSERT, SELECT ON esp32_db.* TO 'esp32'@'localhost';| Column | Type | Why? |
|---|---|---|
| id | INT UNSIGNED, AUTO_INCREMENT | Gives each record a unique, auto-incrementing number |
| device | VARCHAR(32) | Tells you which board sent the data when several ESP32s write to the same table |
| temperature, humidity | DECIMAL(5,2) | Values from −999.99 to 999.99 with two decimals; no FLOAT rounding surprises |
| created_at | TIMESTAMP, default CURRENT_TIMESTAMP | The server writes the time, not the ESP32, so the board needs no clock |
| idx_device_time | Index | Keeps queries by device and date fast even with thousands of rows |
Step 3: the PHP scripts (config.php and insert.php)
Keeping the settings in a separate config.php file lets you change the password in one place and makes it easy for the insert and list scripts to share the same connection. Replace the user password from the SQL command and the API key with your own long, hard-to-guess values. We use PHP's PDO class for the connection; setting the error mode to exceptions stops the script from silently carrying on when something goes wrong.
1<?php
2// Ortak ayarlar: htdocs/esp32-data/config.php / shared settings
3const API_KEY = 'k7Qm2ZpX9vT4'; // ESP32 kodundakiyle aynı / same as in the ESP32 sketch
4const DB_DSN = 'mysql:host=localhost;dbname=esp32_db;charset=utf8mb4';
5const DB_USER = 'esp32';
6const DB_PASS = 'Cambia-Esta-Clave-91';
7
8function db(): PDO {
9 return new PDO(DB_DSN, DB_USER, DB_PASS, [
10 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // hatada istisna fırlat / throw on error
11 ]);
12}1<?php
2// ESP32'den gelen ölçümü kaydeder: htdocs/esp32-data/insert.php / stores one reading from the ESP32
3require __DIR__ . '/config.php';
4header('Content-Type: text/plain; charset=utf-8');
5
6if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
7 http_response_code(405); // yalnız POST / POST only
8 exit('Only POST');
9}
10
11$key = $_POST['api_key'] ?? '';
12if (!is_string($key) || !hash_equals(API_KEY, $key)) {
13 http_response_code(401); // anahtar yanlış / wrong key
14 exit('Invalid API key');
15}
16
17$device = is_string($_POST['device'] ?? null) ? substr(trim($_POST['device']), 0, 32) : '';
18$temperature = filter_var($_POST['temperature'] ?? null, FILTER_VALIDATE_FLOAT);
19$humidity = filter_var($_POST['humidity'] ?? null, FILTER_VALIDATE_FLOAT);
20
21if ($device === '' || $temperature === false || $humidity === false
22 || $temperature < -40 || $temperature > 125 || $humidity < 0 || $humidity > 100) {
23 http_response_code(400); // eksik ya da mantıksız veri / missing or implausible data
24 exit('Bad data');
25}
26
27try {
28 $stmt = db()->prepare(
29 'INSERT INTO sensor_readings (device, temperature, humidity) VALUES (?, ?, ?)'
30 ); // hazır sorgu: SQL enjeksiyonuna karşı / prepared statement
31 $stmt->execute([$device, $temperature, $humidity]);
32 echo 'OK';
33} catch (PDOException $e) {
34 error_log('esp32-data: ' . $e->getMessage()); // ayrıntı yalnız sunucu günlüğüne / details only in the server log
35 http_response_code(500);
36 exit('DB error');
37}| Case | HTTP code | Reply text |
|---|---|---|
| Record saved | 200 | OK |
| Missing or implausible value (e.g. humidity 140) | 400 | Bad data |
| API key wrong or missing | 401 | Invalid API key |
| Request isn't POST (e.g. opened in a browser) | 405 | Only POST |
| Couldn't connect to the database or query error | 500 | DB error |
Step 4: ESP32 code, a POST request with HTTPClient
In this example the data source is a DHT22: connect VCC to 3V3, GND to GND and DATA to GPIO 4 (if you use a bare sensor, add a 10 kΩ pull-up resistor between DATA and 3V3). Install DHT sensor library and the Adafruit Unified Sensor library it asks for from the Library Manager. WiFi.h and HTTPClient.h come with the ESP32 package. For sensor details, see our DHT11 and DHT22 guide.
1#include <WiFi.h>
2#include <HTTPClient.h>
3#include <DHT.h>
4
5const char* WIFI_SSID = "MiRed"; // Wi-Fi adın / your Wi-Fi name
6const char* WIFI_PASS = "MiClave123"; // Wi-Fi şifren / your Wi-Fi password
7const char* SERVER_URL = "http://192.168.1.50/esp32-data/insert.php"; // bilgisayarının yerel IP'si / your PC's LAN IP
8const char* API_KEY = "k7Qm2ZpX9vT4"; // config.php'dekiyle aynı / same as in config.php
9const char* DEVICE = "esp32-salon"; // cihaz adı / device name
10const unsigned long INTERVAL_MS = 60000; // dakikada bir kayıt / one record per minute
11
12DHT dht(4, DHT22); // DHT22 veri pini GPIO 4 / data pin on GPIO 4
13unsigned long lastSend = 0;
14bool firstRun = true;
15
16void connectWiFi() {
17 if (WiFi.status() == WL_CONNECTED) return;
18 WiFi.begin(WIFI_SSID, WIFI_PASS);
19 Serial.print("WiFi");
20 unsigned long start = millis();
21 while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) { // en fazla 15 sn / at most 15 s
22 delay(500);
23 Serial.print(".");
24 }
25 Serial.println(WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString() : String(" yok / failed"));
26}
27
28int sendReading(float t, float h) {
29 HTTPClient http;
30 http.begin(SERVER_URL);
31 http.setTimeout(5000); // 5 sn cevap bekle / wait 5 s for a reply
32 http.addHeader("Content-Type", "application/x-www-form-urlencoded");
33 String body = String("api_key=") + API_KEY +
34 "&device=" + DEVICE +
35 "&temperature=" + String(t, 2) +
36 "&humidity=" + String(h, 2);
37 int code = http.POST(body); // >0: HTTP kodu, <0: bağlantı hatası / HTTP code or connection error
38 if (code > 0) {
39 Serial.printf("HTTP %d: %s\n", code, http.getString().c_str());
40 } else {
41 Serial.printf("Hata / Error %d: %s\n", code, http.errorToString(code).c_str());
42 }
43 http.end();
44 return code;
45}
46
47void setup() {
48 Serial.begin(115200);
49 dht.begin();
50 WiFi.mode(WIFI_STA);
51 connectWiFi();
52}
53
54void loop() {
55 if (firstRun || millis() - lastSend >= INTERVAL_MS) {
56 firstRun = false;
57 lastSend = millis();
58 float t = dht.readTemperature();
59 float h = dht.readHumidity();
60 if (isnan(t) || isnan(h)) {
61 Serial.println("DHT okunamadi / DHT read failed");
62 return;
63 }
64 connectWiFi();
65 if (WiFi.status() == WL_CONNECTED) sendReading(t, h);
66 }
67}The code reads temperature and humidity once a minute, reconnects if Wi-Fi drops, and sends the data as application/x-www-form-urlencoded, exactly as a web form would; PHP sees these fields directly in the $_POST array. If http.POST() returns a positive number, that's the server's HTTP code (200, 404, 500); a negative number means the request never reached the server, and errorToString() prints the reason. Because the timing uses millis() instead of delay(), you can add buttons, a display or other sensors inside loop(). One record per minute means 1,440 rows a day and about 525,000 a year, which for this table takes roughly 30–40 MB including the index. If you send values with spaces or special characters like &, remember to URL-encode them (e.g. %20 for a space).
Step 5: list the records in a table
1<?php
2// Son 50 kaydı tabloda gösterir: htdocs/esp32-data/list.php / shows the last 50 records
3require __DIR__ . '/config.php';
4$rows = db()->query(
5 'SELECT id, device, temperature, humidity, created_at
6 FROM sensor_readings ORDER BY id DESC LIMIT 50'
7)->fetchAll(PDO::FETCH_ASSOC);
8?>
9<!doctype html>
10<html>
11<head>
12 <meta charset="utf-8">
13 <meta name="viewport" content="width=device-width, initial-scale=1">
14 <meta http-equiv="refresh" content="30"><!-- 30 sn'de bir yenile / reload every 30 s -->
15 <title>ESP32 + MySQL</title>
16 <style>
17 body { font-family: sans-serif; margin: 16px; }
18 table { border-collapse: collapse; width: 100%; max-width: 640px; }
19 th, td { border: 1px solid #ccc; padding: 6px 8px; text-align: right; }
20 th { background: #f0f0f0; }
21 </style>
22</head>
23<body>
24 <h1>ESP32 + MySQL</h1>
25 <table>
26 <tr><th>ID</th><th>Device</th><th>°C</th><th>% RH</th><th>Time</th></tr>
27 <?php foreach ($rows as $r): ?>
28 <tr>
29 <td><?= (int) $r['id'] ?></td>
30 <td><?= htmlspecialchars($r['device']) ?></td>
31 <td><?= htmlspecialchars($r['temperature']) ?></td>
32 <td><?= htmlspecialchars($r['humidity']) ?></td>
33 <td><?= htmlspecialchars($r['created_at']) ?></td>
34 </tr>
35 <?php endforeach; ?>
36 </table>
37</body>
38</html>When you open this page at http://192.168.1.50/esp32-data/list.php, the last 50 records appear with the newest on top, and the page reloads itself every 30 seconds. Printing every database value through htmlspecialchars() stops any HTML or script code that might have been written into the device field from running on the page. The real power of raw data shows up with SQL queries: the first query below gives the daily average, minimum and maximum temperature for the last seven days, and the second deletes old records so the table doesn't grow forever. You can run both in phpMyAdmin's SQL tab.
1-- Son 7 günün günlük ortalaması / daily average for the last 7 days
2SELECT DATE(created_at) AS day,
3 ROUND(AVG(temperature), 1) AS avg_temp,
4 MIN(temperature) AS min_temp,
5 MAX(temperature) AS max_temp,
6 COUNT(*) AS samples
7FROM sensor_readings
8WHERE device = 'esp32-salon'
9 AND created_at >= NOW() - INTERVAL 7 DAY
10GROUP BY DATE(created_at)
11ORDER BY day DESC;
12
13-- 90 günden eski kayıtları sil / delete records older than 90 days
14DELETE FROM sensor_readings WHERE created_at < NOW() - INTERVAL 90 DAY;Adding a new measurement to the table is easy too. If, for example, you also want to log air pressure with a BME280, run ALTER TABLE sensor_readings ADD COLUMN pressure DECIMAL(6,1) NULL; in phpMyAdmin, read the pressure field with filter_var() in insert.php and add a fourth ? to the INSERT query; on the ESP32 side, just add a new piece starting with "&pressure=" to the body. Making the column accept NULL keeps old records and not-yet-updated boards working without problems. If several ESP32s share the same table, give each board a different DEVICE name; in queries you filter the device you want with WHERE device = '...' and compare rooms or tanks side by side.
Simple security with an API key
- API key: The script only stores requests that send the correct key, so someone who finds the URL can't flood the table with random data. hash_equals() compares in constant time, making it harder to guess the key character by character.
- Prepared statements: Sending data through ? placeholders instead of pasting it into the SQL text prevents SQL injection.
- Restricted user: The esp32 user only has INSERT and SELECT rights; even if the key leaks, the table can't be dropped.
- Data validation: Non-numeric or physically impossible values (below −40 °C, humidity above 100%) are rejected with a 400 code.
- Hidden error details: The database error message only goes to the server log; the outside world just gets "DB error".
- Change the key: Don't use the key and password from the example; generate random values of at least 16 characters.
Moving to a web host: HTTPS
If you want to reach the data from outside your home, upload the same three files to the public_html/esp32-data folder on your host, create the database and user from the control panel, and run the SQL command in phpMyAdmin. On shared hosting, the database and user names usually get your account name as a prefix (e.g. account_esp32_db); edit config.php accordingly. Since hosts redirect HTTP to HTTPS, the ESP32 needs WiFiClientSecure. The setInsecure() line below connects without verifying the certificate; it's handy for testing, but on a permanent device it's safer to give the site's root certificate with setCACert().
1#include <WiFiClientSecure.h>
2
3// sendReading() içinde http.begin(SERVER_URL) yerine / instead of http.begin(SERVER_URL) in sendReading()
4WiFiClientSecure client;
5client.setInsecure(); // sertifikayı doğrulamaz: yalnız deneme için / skips certificate check, testing only
6http.begin(client, "https://tudominio.com/esp32-data/insert.php");Common error codes: -1, 404, 500 and more
| Code | Meaning | Fix |
|---|---|---|
| -1 (connection refused) | The ESP32 never reached the server | Check the IP, that Apache is running, the firewall and that you're on the same network; no localhost in the URL |
| -11 (read timeout) | Connected, but no reply in time | If MySQL is stopped, PHP hangs while trying to connect; start MySQL and raise the setTimeout() value |
| 301 / 302 | The server redirects to another address | The host turns HTTP into HTTPS: use the https URL and WiFiClientSecure |
| 400 | The script rejected the data | Check that field names match on both sides, the Content-Type header is set and the values make sense |
| 401 | The API key doesn't match | Compare the key in the ESP32 code and in config.php character by character |
| 403 | The server refused access | Check folder permissions and the host's bot protection |
| 404 | File not found | Check the folder and file name; on Linux servers Insert.php and insert.php are different |
| 500 | PHP or database error | Check the password, database and table names and the pdo_mysql extension; read the Apache error log |
ESP32 and MySQL project ideas
- Greenhouse logger: Record temperature, humidity and soil moisture every 10 minutes and base watering decisions on past data.
- RFID attendance system: Write the UID and time of every card read with an RC522 to the table, and the in/out list is ready.
- Water tank history: Log the level you measure with a JSN-SR04T and work out daily consumption.
- Current and energy tracking: Measure an appliance's current with an ACS712 and query hourly averages.
- Multi-room home station: Give the ESP32 in each room its own device name and compare them all in one table.
- Cloud alternatives: If you'd like to try without running a server, look at the Google Sheets or Firebase approaches.
Once you've built this setup, the history of every sensor you connect to the ESP32 is at your fingertips: all you need to do is add matching field names in PHP and columns in the table for each new measurement. To see the steps for joining Wi-Fi, fetching data from the internet with HTTPClient and logging temperature, check out the ESP32 Wi-Fi connection, weather API and temperature logger projects in the BlueGrays app, with circuit diagrams and code step by step.
Frequently asked questions
Can the ESP32 connect to MySQL directly?
Technically yes; there are Arduino libraries that speak the MySQL protocol. But then the database password lives on the board and port 3306 has to be open on the network. Using a PHP script in between is safer, works on every web host and lets you validate the data before storing it.
Why does ESP32 HTTP POST return -1?
-1 means the request never reached the server. The usual causes are localhost in the URL, the computer's IP having changed, Apache not running, Windows Firewall blocking port 80, or the ESP32 and the computer being on different networks. First try opening the same address in your phone's browser.
Where can I store ESP32 data without XAMPP?
You can put the same PHP files on any web host that offers PHP and MySQL, or on a Raspberry Pi running Apache, PHP and MariaDB. If you don't want a server, cloud services like Google Sheets or Firebase work well, and with no internet at all you can log to a microSD card as a CSV file.
How do I store the date and time of ESP32 records?
In this guide's table the created_at column is defined with DEFAULT CURRENT_TIMESTAMP, so the server writes the time and the ESP32 needs no clock. The time zone follows the server's setting. If you build a system that sends records late, get the measurement time on the ESP32 via NTP and send it as a separate field.
Does the ESP32 lose data when the internet drops?
With the basic code in this guide, yes: if there's no connection, that minute's reading isn't sent. If you can't afford gaps, buffer the readings with their timestamps in a RAM array, in LittleFS or on a microSD card, and send them in order when the connection returns. On the PHP side, use the incoming time instead of created_at.
How often should the ESP32 send data to MySQL?
For slowly changing values like temperature and humidity, once a minute is more than enough, which means about 525,000 rows a year. Sending every second bloats the database for no reason and can hit request limits on shared hosting. On battery-powered devices, measuring every 10–15 minutes with deep sleep in between greatly extends battery life.
Projects to build after reading this
See all projects
ESP32 DHT22 Temperature and Humidity (with LCD Display)
This project measures ambient temperature and humidity using a DHT22 sensor and displays the data in real time on a 16x2 I2C LCD. Data is read from the sensor using the one-wire protocol via the Adafruit DHT library. This project serves as the foundation for IoT weather stations, smart home automation, or environmental monitoring systems in greenhouses. Communication with the DHT22 is established via the ESP32's GPIO 4 pin.

ESP32 Wi-Fi STA Connection (with LCD Screen)
In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

ESP32 HTTPClient + Weather API (with LCD Screen)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. The JSON response is parsed with ArduinoJson v7, and the city, temperature, humidity, weather and wind are shown on an I2C LCD. wttr.in needs no API key; just type the name of any city.

ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. Unlike the I2C LCD version, it uses an SSD1306 OLED (128×64) display, with large text and vector icons for a richer look. Seven weather icons (sunny, rainy, snowy and more) are drawn on the fly, with no bitmap files.

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

ESP32 Asynchronous Web Server (with IP Display on LCD)
In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)
In this project, two buttons wired to the ESP32 (GPIO 5 counts up, GPIO 4 counts down) change a counter. The value updates instantly both on a 16x2 I2C LCD and, through the WebSocket support of ESPAsyncWebServer, in every connected browser without reloading the page. Instead of HTTP polling a single persistent connection is used, and the ESP32 sends the new value to everyone with ws.textAll().

Real-Time Clock from the Internet via ESP32 NTP
The ESP32 connects to Wi-Fi and fetches the real time from NTP (Network Time Protocol) servers with millisecond precision. configTzTime() applies the Turkey time zone (TRT, UTC+3) automatically, and in countries with daylight saving time the DST switch is handled by a POSIX TZ string. The time is printed both to the Serial Monitor and to an optional I2C LCD.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32 and Pico projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

