ESP32 S3 - MySQL

The ESP32 S3's built-in Wi-Fi makes it an excellent choice for logging sensor data to a MySQL database running on your local PC or a cloud server. This tutorial guides you through the complete setup — from installing a MySQL server and writing PHP scripts to uploading ESP32 S3 code that sends temperature readings into the database over HTTP.

What you'll build:

  1. A MySQL database and table on your PC using the XAMPP stack (MySQL + Apache + PHP)
  2. A PHP script that receives temperature data from an HTTP GET request and inserts it into the database
  3. An ESP32 S3 sketch that connects to Wi-Fi and posts a temperature reading to that PHP endpoint
  4. A fully working end-to-end data pipeline from the ESP32 S3 to a relational database you can query from any SQL client
ESP32 S3 MySQL - save sensor data to a MySQL database through a PHP web server

Hardware Preparation

1×ESP32 S3 WROOM N16R8
1×Alternatively, ESP32 S3 SuperMini Dev Module
1×Alternatively, ESP32 S3 Uno-form Board
1×Alternatively, ESP32 S3 Camera Board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Optionally, DC Power Jack
1×Breadboard
1×Jumper Wires
1×Recommended: Screw Terminal Expansion Board for ESP32 S3
1×Recommended: Breakout Expansion Board for ESP32 S3
1×Recommended: Power Splitter for ESP32 S3

Or you can buy the following kits:

1×DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

ESP32 S3 - MySQL

There are two terms in MySQL that beginners usually get confused: MySQL Database and MySQL server. They are different. However, if you are a beginner, you can assume that they are the same — you will find the differences naturally as you progress in your learning.

ESP32 S3 can interact with a MySQL database in two ways:

  • Directly: ESP32 S3 connects directly to the MySQL server and communicates using the MySQL protocol
  • Indirectly: ESP32 S3 connects to a web server over HTTP/HTTPS, and the web server talks to MySQL on its behalf

Which approach is better for the ESP32 S3? Read on to find out.

ESP32 S3 Interacts Directly with MySQL Server

ESP32 S3 directly to MySQL

Interacting with MySQL directly seems simple but comes with significant drawbacks:

  • You must grant remote access permissions to a MySQL user account, which introduces security risks even with limited privileges.
  • The ESP32 S3 must store and transmit raw MySQL queries, which consumes more memory and CPU than simple HTTP calls.
  • The ESP32 S3 must parse complex MySQL response packets that can be very large, potentially causing out-of-memory crashes.
  • Most MySQL libraries available for the ESP32 S3 do not support SSL/TLS, meaning credentials and data are sent in plain text.

ESP32 S3 Interacts Indirectly with MySQL Server via HTTP/HTTPS

Connecting to MySQL through a PHP script on a web server solves all of the problems listed above.

How It Works

  • Step 1: ESP32 S3 bundles sensor data into an HTTP/HTTPS request and sends it to the web server
  • Step 2: The web server runs a PHP script that handles the incoming request from ESP32 S3
  • Step 3: The PHP script extracts the data from the HTTP request, processes it, and writes to the MySQL database
  • Step 4: The PHP script returns only the essential result to ESP32 S3 via the HTTP response
ESP32 S3 MySQL HTTP

This tutorial installs MySQL, Apache, and PHP on your PC using the XAMPP package. The same setup can be deployed on a dedicated server or a cloud service such as AWS EC2.

The indirect approach solves each problem of the direct approach:

  • Apache and MySQL run on the same machine, so you can restrict the MySQL user to localhost-only access — your credentials are never exposed to the network.
  • The MySQL username and password live only on the server, never on the ESP32 S3.
  • PHP handles data parsing and query construction, keeping the ESP32 S3 code simple and memory-efficient.
  • PHP sends only the data the ESP32 S3 needs, preventing out-of-memory situations.
  • The ESP32 S3 can make HTTPS requests easily, so the entire channel can be encrypted.

Note that authentication between the ESP32 S3 and the web server should be independent of MySQL authentication — use a different username and password for each.

Because of these advantages, this tutorial uses the indirect approach.

ESP32 S3 to MySQL via HTTP/HTTPS

The steps below cover everything you need:

  • Installing XAMPP (MySQL server, Apache web server, and PHP) on your PC
  • Creating a MySQL user account
  • Creating a MySQL database
  • Creating a MySQL table
  • Writing one or more PHP script files
  • Writing ESP32 S3 code

1. Installing MySQL Server, Web Server, and PHP on Your PC

  • Download and install XAMPP from this link. After installation, verify that the folder C:\xampp\htdocs exists on your PC — this is where you will place your PHP files.
  • Open the XAMPP Control Panel
  • Click the Start buttons next to MySQL and Apache to start both services (as shown in the image below)
ESP32 S3 XAMPP

2. Creating a MySQL User Account

A MySQL account restricted to localhost means that even if an attacker learns the credentials, they cannot access your database from outside your machine.

This tutorial creates a MySQL user account with username ESP32 and password newbiely.com:

  • Open the Command Prompt on your PC and keep it open for the rest of the tutorial.
  • Type the following command on the Command Prompt:
cd C:\xampp\mysql\bin
Command Prompt
C:\Users\YOUR_USER>cd C:\xampp\mysql\bin C:\xampp\mysql\bin>
  • By default, the MySQL root account has no password. It is strongly recommended to set one (e.g. YOUR_ROOT_PASSWORD) for security. Type the command below on the Command Prompt:
mysqladmin -u root password YOUR_ROOT_PASSWORD
Command Prompt
C:\xampp\mysql\bin>mysqladmin -u root password YOUR_ROOT_PASSWORD C:\xampp\mysql\bin>
  • Log in to the MySQL server with the command below:
mysql.exe -u root -p
  • Type YOUR_ROOT_PASSWORD and press Enter
Command Prompt
C:\xampp\mysql\bin>mysql.exe -u root -p Enter password: ****************** Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 9 Server version: 10.4.6-MariaDB mariadb.org binary distribution Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]>
  • Create the MySQL user account by copying and pasting the commands below into the Command Prompt:
CREATE USER 'ESP32'@'localhost' IDENTIFIED BY 'newbiely.com'; GRANT ALL PRIVILEGES ON *.* TO 'ESP32'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES;
Command Prompt
MariaDB [(none)]> CREATE USER 'ESP32'@'localhost' IDENTIFIED BY 'newbiely.com'; Query OK, 0 rows affected (0.005 sec) MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'ESP32'@'localhost' WITH GRANT OPTION; Query OK, 0 rows affected (0.005 sec) MariaDB [(none)]> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.001 sec) MariaDB [(none)]>

You have successfully created a MySQL user account. Note down the username and password — you will need them in the PHP script.

3. Creating a MySQL Database

Create a database called db_esp32 by running the following command on the Command Prompt:

CREATE DATABASE db_esp32 CHARACTER SET = 'utf8' COLLATE = 'utf8_general_ci';
Command Prompt
MariaDB [(none)]> CREATE DATABASE db_esp32 CHARACTER SET = 'utf8' COLLATE = 'utf8_general_ci'; Query OK, 1 row affected (0.003 sec) MariaDB [(none)]>

4. Creating a MySQL Table

Create a table called tbl_temp by copying and pasting the commands below into the Command Prompt:

USE db_esp32; CREATE TABLE tbl_temp ( temp_id INT UNSIGNED NOT NULL AUTO_INCREMENT, temp_value FLOAT DEFAULT 0.00, PRIMARY KEY (temp_id) );
Command Prompt
MariaDB [(none)]> USE db_esp32; Database changed MariaDB [db_esp32]> MariaDB [db_esp32]> CREATE TABLE tbl_temp ( -> temp_id INT UNSIGNED NOT NULL AUTO_INCREMENT, -> temp_value FLOAT DEFAULT 0.00, -> PRIMARY KEY (temp_id) -> ); Query OK, 0 rows affected (0.044 sec) MariaDB [db_esp32]>

5. Writing PHP Script Files

Create a file called insert_temp.php using any text editor (such as Notepad or Notepad++). This script reads the temperature value from the HTTP GET request and inserts it into the database.

<?php if(isset($_GET["temperature"])) { $temperature = $_GET["temperature"]; // get temperature value from HTTP GET $servername = "localhost"; $username = "ESP32"; $password = "newbiely.com"; $database_name = "db_esp32"; // Create MySQL connection from PHP to MySQL server $connection = new mysqli($servername, $username, $password, $database_name); // Check connection if ($connection->connect_error) { die("MySQL connection failed: " . $connection->connect_error); } $sql = "INSERT INTO tbl_temp (temp_value) VALUES ($temperature)"; if ($connection->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . " => " . $connection->error; } $connection->close(); } else { echo "temperature is not set in the HTTP request"; } ?>
  • Place this file inside the C:\xampp\htdocs folder
  • Find your PC's IP address (search online if you are unsure how)
  • Test the PHP script by opening a web browser and navigating to: http://192.168.0.19/insert_temp.php?temperature=26.2. Replace the IP address with your PC's actual address.
  • The web browser should display a success message as shown below:
MySQL Test
  • Verify the data was stored by running the following command on the Command Prompt:
SELECT * from tbl_temp;
Command Prompt
MariaDB [db_esp32]> SELECT * from tbl_temp; +---------+------------+ | temp_id | temp_value | +---------+------------+ | 1 | 26.2 | +---------+------------+ 1 row in set (0.001 sec) MariaDB [db_esp32]>

The temperature value 26.2 is now stored in the database. The next step is to write ESP32 S3 code that makes an HTTP request to this web server.

6. Writing ESP32 S3 Code

The following code configures the ESP32 S3 to connect to your Wi-Fi network and send an HTTP GET request to the PHP endpoint, inserting a temperature reading of 30.5°C into the MySQL database. Update the Wi-Fi credentials and PC IP address before uploading.

/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-mysql */ /* * This ESP32-S3 code is created by esp32io.com * * This ESP32-S3 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-s3-mysql */ #include <WiFi.h> #include <HTTPClient.h> const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // change to your WiFi network name const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // change to your WiFi password String HOST_NAME = "http://192.168.0.19"; // change to your PC's IP address String PATH_NAME = "/insert_temp.php"; String queryString = "?temperature=30.5"; void setup() { Serial.begin(115200); // connect the ESP32-S3 to the WiFi network WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); HTTPClient http; http.begin(HOST_NAME + PATH_NAME + queryString); // HTTP int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // file found at server if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); Serial.println(payload); } else { // HTTP header has been sent and server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); } } else { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); } void loop() { }

Detailed Instructions

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Complete the MySQL, Apache, and PHP setup steps above before uploading the code.
  3. Connect the ESP32 S3 board to your PC using a USB Type-C cable.
  4. Open the Arduino IDE on your PC.
  5. In the Arduino IDE, select the correct board (ESP32S3 Dev Module or equivalent) and COM port under Tools.
How to upload ESP32 S3 code on Arduino IDE
  1. Copy the sketch above and open it in the Arduino IDE.
  2. Update YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD with your network credentials.
  3. Replace the IP address in the code with your PC's actual IP address.
  4. Click the Upload button to compile and flash the sketch to the ESP32 S3.
  5. Once the upload is complete, open the Serial Monitor from the Tools menu or the monitor icon.
How to open serial monitor on Arduino IDE
  1. Set the baud rate to 115200 in the Serial Monitor dropdown.
  2. Pro Tip: If the ESP32 S3 reports a connection failure, double-check that XAMPP's Apache and MySQL services are both running and that your PC's firewall is not blocking port 80.

Serial Monitor Output

When the ESP32 S3 successfully connects to Wi-Fi and inserts a row into the database, the Serial Monitor will display output similar to the following:

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32S3 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32S3 Dev Module' on 'COM15')
New Line
9600 baud
[2026-06-16 09:14:01] Connecting to WiFi... [2026-06-16 09:14:04] WiFi connected. IP: 192.168.1.112 [2026-06-16 09:14:04] Sending HTTP request to server... [2026-06-16 09:14:05] HTTP Response Code: 200 [2026-06-16 09:14:05] Server reply: New record created successfully [2026-06-16 09:14:15] Sending HTTP request to server... [2026-06-16 09:14:16] HTTP Response Code: 200 [2026-06-16 09:14:16] Server reply: New record created successfully
Ln 11, Col 1
ESP32S3 Dev Module on COM15
2
  • Check that the data was stored by running the following command on the Command Prompt:
SELECT * from tbl_temp;
Command Prompt
MariaDB [db_esp32]> SELECT * from tbl_temp; +---------+------------+ | temp_id | temp_value | +---------+------------+ | 1 | 26.2 | | 2 | 30.5 | +---------+------------+ 2 rows in set (0.000 sec) MariaDB [db_esp32]>

The temperature reading of 30.5°C sent by the ESP32 S3 is now stored in the database alongside the earlier test value.

How ESP32 S3 Inserts, Updates, or Reads Data from MySQL

The example above demonstrates inserting data into MySQL. Updating and reading data follow exactly the same pattern — you simply modify the SQL query inside the PHP script. You can learn more about PHP and MySQL at W3Schools.com.

Application and Project Ideas

The ESP32 S3's ability to store data in MySQL opens the door to a wide range of data-driven IoT applications. Here are some directions worth exploring:

  1. Environmental data logger: Collect temperature, humidity, or air-quality readings from sensors every few minutes and insert each measurement into a time-series MySQL table for long-term trend analysis.
  2. Smart irrigation controller: Log soil moisture sensor readings to MySQL and query historical averages to decide when to activate a water pump automatically.
  3. Access control log: Record every RFID or keypad authentication event — including card ID, timestamp, and access result — into a MySQL database for auditing.
  4. Energy monitor: Read current-sensor values with the ESP32 S3, calculate power consumption, and store daily totals in MySQL so you can track energy usage over weeks or months.
  5. Remote inventory tracker: Place ESP32 S3 nodes at different locations; each node reports stock-level or weight-sensor data to a central MySQL database accessible from any browser.
  6. Alert history dashboard: Store every threshold-crossing event (high temperature, gas leak, motion detection) in MySQL and query the table to display an alert history on a web dashboard.

Video Tutorial

Watch the step-by-step video walkthrough for this ESP32 S3 project below.

Challenge Yourself

Once your ESP32 S3 is writing rows to MySQL, there are many ways to extend the project and deepen your understanding. Try the challenges below in order of difficulty:

  1. Beginner: Modify the PHP script to return the auto-incremented row ID in the response and print it on the Serial Monitor to confirm each insert.
  2. Beginner: Change the ESP32 S3 code to read a real sensor (such as a DHT22 or LM35) and log its output to the database instead of the hard-coded 30.5°C value.
  3. Intermediate: Add a second PHP endpoint called get_temp.php that reads the latest ten rows from tbl_temp and returns them as a JSON array; have the ESP32 S3 fetch and print the JSON to the Serial Monitor.
  4. Intermediate: Implement an update_temp.php script that accepts a row ID and a new temperature value via GET parameters and updates the existing record in MySQL.
  5. Advanced: Switch the connection from HTTP to HTTPS by installing a self-signed certificate in XAMPP and using WiFiClientSecure on the ESP32 S3 to verify the certificate before sending data.
  6. Advanced: Build a browser-based dashboard in PHP that queries MySQL and plots the stored temperature readings as a line chart using Chart.js — then watch the chart update live as the ESP32 S3 keeps inserting new rows.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!