ESP32/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE

In this project you’ll build an ESP32 or ESP8266 client that makes an HTTP POST request to a PHP script to insert data (sensor readings) into a MySQL database.

ESP32 ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE

You’ll also have a web page that displays the sensor readings, timestamp and other information from the database. You can visualize your data from anywhere in the world by accessing your own server.

As an example, we’ll be using a BME280 sensor connected to an ESP board. You can modify the code provided to send readings from a different sensor or use multiple boards.

In order to create build this project, you’ll use these technologies:

  • ESP32 or ESP8266 programmed with Arduino IDE
  • Hosting server and domain name
  • PHP script to insert data into MySQL and display it on a web page
  • MySQL database to store readings

1. Hosting Your PHP Application and MySQL Database

The goal of this project is to have your own domain name and hosting account that allows you to store sensor readings from the ESP32 or ESP8266. You can visualize the readings from anywhere in the world by accessing your own server domain. Here’s a high level overview:

Hosting PHP Application and MySQL Database to post ESP32 or ESP8266 Sensor Readings

I recommend using one of the following hosting services that can handle all the project requirements:

  • Bluehost (user-friendly with cPanel): free domain name when you sign up for the 3-year plan. I recommend choosing the unlimited websites option;
  • Digital Ocean: Linux server that you manage through a command line. I only recommended this option for advanced users.

Those two services are the ones that I use and personally recommend, but you can use any other hosting service. Any hosting service that offers PHP and MySQL will work with this tutorial. If you don’t have a hosting account, I recommend signing up for Bluehost.

Get Hosting and Domain Name with Bluehost »

When buying a hosting account, you’ll also have to purchase a domain name. This is what makes this project interesting: you’ll be able to go your domain name ( and see your ESP readings.

If you like our projects, you might consider signing up to one of the recommended hosting services, because you’ll be supporting our work.

Note: you can also run a LAMP (Linux, Apache, MySQL, PHP) server on a Raspberry Pi to access data in your local network. However, the purpose of this tutorial is to publish readings in your own domain name that you can access from anywhere in the world. This allows you to easily access your ESP readings without relying on a third-party IoT platform.

2. Preparing Your MySQL Database

After signing up for a hosting account and setting up a domain name, you can login to your cPanel or similar dashboard. After that, follow the next steps to create your database, username, password and SQL table.

Creating a database and user

1. Type “database” in the search bar and select “MySQL Database Wizard”.

CPanel select MySQL database wizard to create db

2. Enter your desired Database name. In my case, the database name is esp_data. Then, press the “Next Step” button:

ESP32 ESP8266 CPanel Create MySQL Database

Note: later you’ll have to use the database name with the prefix that your host gives you (my database prefix in the screenshot above is blurred). I’ll refer to it as example_esp_data from now on.

3. Type your Database username and set a password. You must save all those details, because you’ll need them later to establish a database connection with your PHP code.

ESP32 ESP8266 CPanel Create MySQL Database User and Password

That’s it! Your new database and user were created successfully. Now, save all your details because you’ll need them later:

  • Database name: example_esp_data
  • Username: example_esp_board
  • Password: your password

Creating a SQL table

After creating your database and user, go back to cPanel dashboard and search for “phpMyAdmin”.

ESP32 ESP8266 CPanel Open PHPMyAdmin

In the left sidebar, select your database name example_esp_data and open the “SQL” tab.

ESP32 ESP8266 PHPMyAdmin Open Database

Important: make sure you’ve opened the example_esp_data database. Then, click the SQL tab. If you don’t follow these exact steps and run the SQL query, you might create a table in the wrong database.

Copy the SQL query in the following snippet:

    sensor VARCHAR(30) NOT NULL,
    location VARCHAR(30) NOT NULL,
    value1 VARCHAR(10),
    value2 VARCHAR(10),
    value3 VARCHAR(10),

View raw code

Paste it in the SQL query field (highlighted with a red rectangle) and press the “Go” button to create your table:

ESP32 ESP8266 PHPMyAdmin Create SQL Table

After that, you should see your newly created table called SensorData in the example_esp_data database as shown in the figure below:

ESP32 ESP8266 PHPMyAdmin View SQL Database

3. PHP Script HTTP POST – Insert Data in MySQL Database

In this section, we’re going to create a PHP script that is responsible for receiving incoming requests from the ESP32 or ESP8266 and inserting the data into a MySQL database.

If you’re using a hosting provider with cPanel, you can search for “File Manager”:

ESP32 ESP8266 CPanel Open Edit PHP Files

Then, select the public_html option and press the “+ File” button to create a new .php file.

ESP32 ESP8266 CPanel Create New PHP File

Note: if you’re following this tutorial and you’re not familiar with PHP or MySQL, I recommend creating these exact files. Otherwise, you’ll need to modify the ESP sketch provided with different URL paths.

Create a new file in /public_html with this exact name and extension: post-esp-data.php

PHP Create New file post esp data

Edit the newly created file (post-esp-data.php) and copy the following snippet:


  Rui Santos
  Complete project details at
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

$servername = "localhost";

// REPLACE with your Database name
// REPLACE with Database user
// REPLACE with Database user password

// Keep this API Key value to be compatible with the ESP32 code provided in the project page. 
// If you change this value, the ESP32 sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";

$api_key= $sensor = $location = $value1 = $value2 = $value3 = "";

    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $sensor = test_input($_POST["sensor"]);
        $location = test_input($_POST["location"]);
        $value1 = test_input($_POST["value1"]);
        $value2 = test_input($_POST["value2"]);
        $value3 = test_input($_POST["value3"]);
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        $sql = "INSERT INTO SensorData (sensor, location, value1, value2, value3)
        VALUES ('" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value2 . "', '" . $value3 . "')";
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
    else {
        echo "Wrong API Key provided.";

else {
    echo "No data posted with HTTP POST.";

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;

View raw code

Before saving the file, you need to modify the $dbname, $username and $password variables with your unique details:

// Your Database name
$dbname = "example_esp_data";
// Your Database user
$username = "example_esp_board";
// Your Database user password
$password = "YOUR_USER_PASSWORD";

After adding the database name, username and password, save the file and continue with this tutorial. If you try to access your domain name in the next URL path, you’ll see the following:

4. PHP Script – Display Database Content

Create another PHP file in the /public_html directory that will display all the database content in a web page. Name your new file: esp-data.php

PHP Create New file esp data

Edit the newly created file (esp-data.php) and copy the following code:

<!DOCTYPE html>
  Rui Santos
  Complete project details at
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

$servername = "localhost";

// REPLACE with your Database name
// REPLACE with Database user
// REPLACE with Database user password

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

$sql = "SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC";

echo '<table cellspacing="5" cellpadding="5">
        <td>Value 1</td> 
        <td>Value 2</td>
        <td>Value 3</td> 
if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $row_id = $row["id"];
        $row_sensor = $row["sensor"];
        $row_location = $row["location"];
        $row_value1 = $row["value1"];
        $row_value2 = $row["value2"]; 
        $row_value3 = $row["value3"]; 
        $row_reading_time = $row["reading_time"];
        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time - 1 hours"));
        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time + 4 hours"));
        echo '<tr> 
                <td>' . $row_id . '</td> 
                <td>' . $row_sensor . '</td> 
                <td>' . $row_location . '</td> 
                <td>' . $row_value1 . '</td> 
                <td>' . $row_value2 . '</td>
                <td>' . $row_value3 . '</td> 
                <td>' . $row_reading_time . '</td> 


View raw code

After adding the $dbname, $username and $password save the file and continue with this project.

// Your Database name
$dbname = "example_esp_data";
// Your Database user
$username = "example_esp_board";
// Your Database user password
$password = "YOUR_USER_PASSWORD";

If you try to access your domain name in the following URL path, you’ll see the following:
ESP32 ESP8266 Test ESP Data PHP URL

That’s it! If you see that empty table printed in your browser, it means that everything is ready. In the next section, you’ll learn how to insert data from your ESP32 or ESP8266 into the database.

5. Preparing Your ESP32 or ESP8266

This project is compatible with both the ESP32 and ESP8266 boards. You just need to assemble a simple circuit and upload the sketch provided to insert temperature, humidity, pressure and more into your database every 30 seconds.

Parts Required

For this example we’ll get sensor readings from the BME280 sensor. Here’s a list of parts you need to build the circuit for this project:

You can use the preceding links or go directly to to find all the parts for your projects at the best price!


The BME280 sensor module we’re using communicates via I2C communication protocol, so you need to connect it to the ESP32 or ESP8266 I2C pins.

BME280 wiring to ESP32

The ESP32 I2C pins are:

  • GPIO 22: SCL (SCK)
  • GPIO 21: SDA (SDI)

So, assemble your circuit as shown in the next schematic diagram (read complete Guide for ESP32 with BME280).

BME280 wiring to ESP32

Recommended reading: ESP32 Pinout Reference Guide

BME280 wiring to ESP8266

The ESP8266 I2C pins are:

  • GPIO 5 (D1): SCL (SCK)
  • GPIO 4 (D2): SDA (SDI)

Assemble your circuit as in the next schematic diagram if you’re using an ESP8266 board (read complete Guide for ESP8266 with BME280).

BME280 wiring to ESP8266

Recommended reading: ESP8266 Pinout Reference Guide

ESP32/ESP8266 Code

We’ll program the ESP32/ESP8266 using Arduino IDE, so you must have the ESP32/ESP8266 add-on installed in your Arduino IDE. Follow one of the next tutorials depending on the board you’re using:

After installing the necessary board add-ons, copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

  Rui Santos
  Complete project details at
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.


#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "BME280";
String sensorLocation = "Office";

/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme;  // I2C
//Adafruit_BME280 bme(BME_CS);  // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);  // software SPI

void setup() {
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED) { 
  Serial.print("Connected to WiFi network with IP Address: ");

  // (you can also pass in a Wire library object like &Wire2)
  bool status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring or change I2C address!");
    while (1);

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;
    // Your Domain name with URL path or IP address with path
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())
                          + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
    Serial.print("httpRequestData: ");
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
    // If you need an HTTP request with a content type: text/plain
    //http.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = http.POST("Hello, World!");
    // If you need an HTTP request with a content type: application/json, use the following:
    //http.addHeader("Content-Type", "application/json");
    //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
    else {
      Serial.print("Error code: ");
    // Free resources
  else {
    Serial.println("WiFi Disconnected");
  //Send an HTTP POST request every 30 seconds

View raw code

Setting your network credentials

You need to modify the following lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting your serverName

You also need to type your domain name, so the ESP publishes the readings to your own server.

const char* serverName = "";

Now, you can upload the code to your board. It should work straight away both in the ESP32 or ESP8266 board. If you want to learn how the code works, read the next section.

How the code works

This project is already quite long, so we won’t cover in detail how the code works, but here’s a quick summary:

  • Import all the libraries to make it work (it will import either the ESP32 or ESP8266 libraries based on the selected board in your Arduino IDE)
  • Set variables that you might want to change (apiKeyValue, sensorName, sensorLocation)
  • The apiKeyValue is just a random string that you can modify. It’s used for security reasons, so only anyone that knows your API key can publish data to your database
  • Initialize the serial communication for debugging purposes
  • Establish a Wi-Fi connection with your router
  • Initialize the BME280 to get readings

Then, in the loop() is where you actually make the HTTP POST request every 30 seconds with the latest BME280 readings:

// Your Domain name with URL path or IP address with path

// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName                      + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())                      + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";

int httpResponseCode = http.POST(httpRequestData);

You can comment the httpRequestData variable above that concatenates all the BME280 readings and use the httpRequestData variable below for testing purposes:

String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";


After completing all the steps, let your ESP board collect some readings and publish them to your server.

ESP32 BME280 Arduino IDE MySQL

If everything is correct, this is what you should see in your Arduino IDE Serial Monitor:

ESP32 ESP8266 BME280 Readings Arduino IDE Serial Monitor

If you open your domain name in this URL path:

You should see the all the readings stored in your database. Refresh the web page to see the latest readings:

ESP32 ESP8266 View Sensor Readings Webpage PHP

You can also go to phpMyAdmin to manage the data stored in your SensorData table. You can delete it, edit, etc…

ESP32 ESP8266 View Sensor Readings PHPMyAdmin SQL Database

Wrapping Up

In this tutorial you’ve learned how to publish sensor data into a database in your own server domain that you can access from anywhere in the world. This requires that you have your own server and domain name (you can use a Raspberry Pi for local access).

The example provided is as simple as possible so that you can understand how everything works. After understanding this example, you may change the appearance of the table, publish different sensor readings, publish from multiple ESP boards, and much more.

You might also like reading:

I hope you liked this project. If you have any questions, post a comment below and we’ll try to get back to you.

If you like ESP32, you might consider enrolling in our course “Learn ESP32 with Arduino IDE“. You can also access our free ESP32 resources here.

Thank you for reading.

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our weekly newsletter!

174 thoughts on “ESP32/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE”

    • I definitely plant to create a follow up guide on that subject, but basically you just need to install MySQL and PHP on a Raspberry Pi. Then, instead of making an HTTP POST request to a domain name, you make the request to the RPi IP address. The exact same code that I use works on the Raspberry Pi by default.

      • As a matter of fact I am using it on a local raspi database, albeit that I use MariaDB rather than MySQL, but that is largely the same.
        Setting up MySQL isnt really translucent and userfriendly, but MariaDB, tops that. Hint: first log in: ‘sudo mysql’, no user no pw.
        But it is very doable.
        Your php script doesnt care if it is mysql or mariadb nor if it is on a local server or ‘in the cloud’

  1. Hi!

    I made a similiar approach.
    An ESP2866 measures temperture, pressure, humidity (BME280) and brightness (LDR). Every minute/10minutes/hour a website is called with parameters to post the sensor data. A php-script on the webserver at the site of my provider takes this parameters and inserts them via mysql into the specified table.
    On my website ( – please visit!) you can recall the data – visualized with jpgraph – in severeal intervals. Therefore I used woody snippets to integrate a php-script into wordpress.

    My website is in German, but I think the menu item “Konzept und Umsetzung” (concept and implementation) should be understandable due to the pictures.

    Happy planning/”boarding”/welding/&coding.

    Kind regards, Stefan

  2. getting stuck at the end of step #…put in my website address

    Connection failed: Access denied for user ‘mywebsite_esp_board’@’localhost’ to database ‘mywebsite_my_first_db’

    I don’t need to change “localhost” to something else do I?

  3. Awesome Rui,
    Thanks for this example, love it.
    How secure is this type of http posting? Whats your opinion about security on these type of systems using a database across the cloud?. Do you have an example of sending a trigger back on a response from the PHP. Example if you reading is > 100 send led 1 on from a table stored value where the 100 value would be evaluated by its row id some small type of logic so to speak.



    • Hi Chris.
      You can define your server with HTTPS to have all data posted to your server encrypted. Of course, with this example, you are relying on third-party websites, but I’ve been using it for years and haven’t had any problem.
      The URL /esp-data.php is currently open to the public, but you can set up a login system with a php code that would keep that data private to you.
      At the moment, we don’t have any projects about that exact subject.

  4. Wow Rui .. very nice post .. my weekend ‘to-do’ list is now officially occupied 🙂 Thanks for all the great tutorials !

  5. Hi, it’s very usefull this article, thanks a lot. You can write something about transfer video files instead sensor values? Maybe recorded in a SD memory connected to a ESP32 or ESP8266.

    • Hi.
      In this example we’re using a BME280 sensor. It reads temperature, humidity and pressure.
      At the moment, we don’t have any companion video for this project.

  6. Hi,

    Good tutorial …

    You can use WampServer for both Internet and LAN …
    1/3 of all servers are WampServer, I have been using it for years
    for webpages, controlling steam game Servers, and media servers,
    Home Automation using esp8266 and esp32 now


  7. A word of caution if planning to run this on a Raspi Pi. The conventional wisdom widely shared on the net is that MySQL does a lot of writing to the SD card causing it to wear out quickly. I would suggest that it would work better with an SSD.
    Rui a very explanation of the basics of setting up a MySQL system with an ESP device. A follow up article on how to extract specific data / topic would be very welcome.

  8. Rui Santos,
    You did excellent job in this tutorial.
    Your setup procedures working perfect, except that the timestamp is not my local time.

    How to change the SQL query time_reading to show my local time ?

    • Hi.

      We’ve added some extra lines of code to adjust the time to your timezone in the esp-data.php file:

      You can simply uncomment one of the following lines to adjust the time displayed in your webpage:
      // Uncomment to set timezone to – 1 hour (you can change 1 to any number)
      //$row_reading_time = date(“Y-m-d H:i:s”, strtotime(“$row_reading_time – 1 hours”));

      // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
      //$row_reading_time = date(“Y-m-d H:i:s”, strtotime(“$row_reading_time + 4 hours”));

      If the actual time (minute and date) is incorrect when inserting data into the database, I recommend contact your host directly to see what is going on in your server.

      I hope this solves your problem.


      • Sara,

        Thank you very much. I can see my local time now in “reading time”. I have to +16 hours to make it right.

        Ong Kheok Chin

  9. Hello Rui,
    This tutorial is for one ES8266 and one BME sensor. Can we connect three or more ESP8266 with other sensors. further in your tutorial three values are inserted. Can we insert more than three values.

  10. Me again 😉

    Can i use the esp software in a sonoff basic and use gpio 1 og 14 for digital input, I Will only use it becourse the power supply is build in, and I Will not use the relay.

    I Will only connect a photo diode to one of the gpio input an save on and off time in the db

    Thanks in advance 😇

    • Hi again.
      I haven’t tested that. But it should work, because it is an ESP8266.
      If you try it, then let me know if it worked.

      • Hi

        I have try it for many days but i cant get it to work with sonoff basic, well im new i this world.

        My wish is to save data in mysql from my sonoff basic, i have input on gpio14 and if this input change i will like to send on and off to my mysql.

        I have some esp8266 on way from China but i cant se where in the code i can add I/O port some replacement for the sensor, maybe you can help me with that.

        Tanks in advance

        • Niels, I hope you found an answer already, but if not, maybe this will help:
          The ESP program reads the sensor in the http request, e.g. when it does this: “String(bme.readTemperature())”
          I understand that you only want to send a message to your database when the input on pin14 changes. That is not so hard.
          I presume you are working with MQTT, but in case you are not, i’ll just give a general example:
          When you switch pin 14, you have to check if the state has changed, so that the received command was indeed ON-OFF or OFF-ON and not ON-ON,
          Then you put your http request in an IF statement that basically checks:
          IF (previousstate !currentstate) {do http request)
          in your http request you then only have to send the current state, dont forget to end with ‘previousstate=current state’

  11. Sara,

    How is the api_key_value generated ? Do we just pick any random character/n umbers for this api_key ?

    Ong Kheok Chin

    • Yes. That was randomly generated by us. You can set any API Key that you want.
      That way, only who knows the API key can post data to your database.

  12. Thanks for writing this awesome article. The article is very comprehensive as you have highlighted all the key points regarding the article. Furthermore, the process is so simply explained that even a lay man can understand the process. However, when talking of the hosting then I think digitalOcean is the best option but, I don’t think that it is only limited to the advanced users. Even someone with the basic knowledge can go with DO server. Perhaps, you can even go with the managed DigitalOcean web server. Below, is the link to the managed hosting:

  13. Hey, im trying to use sql for a project and need to send data almost constantly. How much delay does uploading data have? And what could be a good alternative if its too slow?

  14. I see that you have stopped recommending Stablehost, it was there earlier on this week; is there a reason for this?

    • No reason, I just had a bunch of people emailing me which one should they choose, so I decided to just 1 option with cPanel to be less confusing. This tutorial works with any hosting provider that offers cPanel.

  15. Thank you for the tutorial. I follow the tutorial and it works great. But If I have a multiple ESP8266 clients, Please can you give example that display the latest readings only of all ESP8266 clients. Like this:
    Sensor Location Value 1 Value 2 Value 3 Timestamp
    ———————————————————————————————————–BME280 Office 21.14 56.91 996.52 2019-06-07 03:57:17
    BME280 Kitchen 22.15 56.33 996.62 2019-06-07 03:57:18
    BME280 Garage 21.77 56.66 996.80 2019-06-07 03:57:19

    Thanks in advance


    • Hi Kim.
      You need to upload the Arduino sketch to all your EPS8266 and modify it accordingly to your needs. For example one ESP publishes the location “kitchen” and the other “room”. Each ESP will publish different data but to the same database.

  16. Hello Sara,

    Regarding location I already done that on my 4 ESP8266, my concern is how can I display it to the webpage with the latest readings only. Only the Values and Timestamp will change on every refresh if there’s a latest readings. Can it be done, do you have any example on it.

    Thanks in advance,

  17. hello thanks for this great tutorial i am stuck on file manager process because there is no file name public_html in my file manager

    • Hi
      I recommend contacting your hosting provider team and asked them how to access your public_html folder or similar.
      Some hosts might have a different name.

  18. In arduino serial monitor i got 200 status code but in server value is not display.. I am struggling that past 2 days.

  19. Hi Rui and Sara,

    Firstly thanks for all the tutorial that you have provided here. They have helped me a lot over the last couple of weeks.

    I created an async webserver on the ESP32. My index.html, stylesheet and js functions are located in the SPIFFS (4mB). All is working, upon typing the local IP in my browser the index.html page shows up nicely.

    However…. I have a toggle “button” on my website:

    The button loads perfectly and looks the way I want it to look. My question is, how on earth can I pass the state of that button to a variable in my .ino program? I followed your async web server tutorial as well as your temp and humidity web server tutorial. And I can get it to work but I do NOT want to refresh the entire page every time a button is clicked NOR do I want to have my html code inside the .ino file.

    Could you point me in the right direction?

    Thanks heaps in advance!

      • Hi Sara,

        Thank you for your reply! I had already used code from suggested project. However, my project is different in a few ways:
        1. I store my index.hml file and a myJqueries.js file in the SPIFFS. The AJAX request and other JS code from the Servo project is called upon from within the html page. I do not want that for various reasons. What code do I need to include in my .js file and how do I call it from within my html file?

        2. The entire html code of the Servo project is generated within the C/C++ code with help of client.println statements. For that reason C/C++ variables can easily be injected in the html document. However, when working with an external index.html document you need to rely on that server.on(“/”, HTTP_GET, [](AsyncWebServerRequest * request) {… and request->send(SPIFFS, “/index.html”, String(), false, processor). I cannot figure out how to retrieve data from that GET request, use it in my C/C++ program and then send something back to my index.html.
        How do I use that “request–> send: correctly to exchange data between my C/C++ code and my index.html?

        Would you be able yo provide sample code?

        Kind regards,


  20. Hello – First off let me tell you how much I appreciate what you folks are doing. I’ve followed several of your projects. bought several on-line courses/books and am playing with a couple projects. Now I’m attempting to post data to a MySQL database from an automated weather station. I’m not using the BME sensor but rather the ESP8266 combined with the Hiletgo DHT11 Temperature and Humidity sensor and the Argent precipitation, wind speed and direction devices. I’ve got the program to the point where data is being delivered to the MySQL database but PHP is giving me an error as follows: ” Undefined index: api_key in /home/u638013961/domains/ on line 32″. I’m not sure what the error message means. By the way, I’m using as my web site host. Thanks for any help. – Gary

    • I’m not sure Gary, but to be honest you should start with a BME280 sensor first, so you use the exact example that I show.
      Later on you could modify my example with a different sensor (just to avoid these problems).

      Basically, it looks like you’ve deleted this variable declared:

      $api_key_value = “tPmAT5Ab3j7F9”;

      I’ve created that sample API Key value, so only you can post to your exact URL.


      • I tried using the BME280 and that worked just fine. Now I’ve switched back to the DHT22, made a couple modifications and, for some reason the data is now being posted – complete with new headings for the web page. So, for now, all is good. Although I do wonder what the purpose of the API_key is and how that is generated? Thanks. – Gary

  21. plz help me out my seriel monitor shows this and data is not posting to server

    httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=10&value2=10&value3=10
    Error code: -1

      • Hi Rui Santos,

        I have the same issue … but isn’t inserting in database, does this have to do with the API key?

        If yes so how can I generate another key? Thanks

        00:44:26.724 -> httpRequestData: api_key=&temperatura=21.30&umidade=71.00
        00:44:26.724 -> Error code: -1
        00:45:26.748 -> httpRequestData: api_key=&temperatura=21.30&umidade=71.00
        00:45:26.748 -> Error code: -1
        00:46:26.755 -> httpRequestData: api_key=&temperatura=21.30&umidade=71.00
        00:46:26.755 -> Error code: -1

        • i had the same problem until i changed the adress of the website from https:// to http:// (delete “s”)

          Apparently <ESP8266HTTPClient.h> dont work with https Protocol

  22. Hi. I’m lately working with the same project as this. is this possible to use Arduino Uno and ESP-01 to send data to my live server? Thank you in advance

  23. thank you very much Rui for your reply yes i check but there is no data in database plz take me out from this problem

  24. Hi, I had a similar problem with the same message. I found that it was because I used https under the server name in the ESP32/ESP8266 Arduino Code – I changed this to http even though my server address is https and it then worked. Hope this works for you as well

  25. sir do you know how to get/retrieve data from firebase then send to PHP then will received by the arduino?

    I already tried “echo” but it was just the PHP to arduino situation

    I need firebase to PHP to arduino

    because I want to change the wifi SSID and password by sending those two information in firebase

      • Hi,
        i am trying to make a project IOT Based Smart Irrigation System. now I have done my website in PHP and Hardware also ready now.. Now i want to connect it with my domain and save all sensors reading into online database(phpMyAdmin).
        second thing is this if i want to turn on/off the water pump manually through my webpage and its effect will work on hardware(ARDUINO UNO/NODEMCU). As a result the water pump will turn on/off even if moisture level is lower then its limit. Then how it is possible ? can you give me a tutorial for this issue..
        Thank you in advance for your positive response.
        Ziyam Aslam
        From Pakistan

  26. thank you so much Alister you are great you solve my problem i will be very happy if i solve any of your problem 🙂

  27. Great explanation. But I have a question.

    I run my own website, just for fun and education.

    My site is “” and is a secure site. So http:// will be redirected to https://

    Browsers can handle this problem.

    Your script returns:

    Connected to WiFi network with IP Address:
    httpRequestData: api_key=tPmAT5Ab3j7F9&yeti=3
    HTTP Response code: 302

    IMHO the redirection is not the problem but the secure connection. Do you have an example with a secure connection?

    That would be great.

    • You can open the Arduino IDE > File > Examples > WiFiClientSecure > WiFiClientSecure.ino example which shows how to make HTTPS requests with an ESP32.

      Then, you can merge that example with my code to make an HTTPS post to your server…

      Note: some severs allow both http and https connections, so with an HTTP request you can still insert data in your database

      • Hi Rui,
        The example is for an ESP32. I was looking for a similar example for the ESP8266, but couldn’t find it. Does it exist or can you give me directions where to find it or how to apply wifi security for an ESP8266? TIA!

  28. I have everything in your example working great using a DHT22! Thank you! I’m having trouble adding in more values so that I can push and display more data to the database. Any advice?

  29. Hi Sara & Rui,
    Great work on this project – brilliant! I have just completed it using Wampserver and hosting on my laptop. Took a little bit of work setting up Apache and MySql but well worth the aggravation.
    I was using a Wemos Lolin Lite board so the pin out to get the BME280 going took some experimenting to find the working I2C pins.
    Keep up the sterling work!

  30. Is there a simple way to modify the esp-data.php file so that the database will display the most recent record on top and the oldest record on the bottom?

  31. Hi Sara, hi Rui,
    first one my congratulations for your job here on Random Nerd!!!
    Let me ask a question: it could be possible to combine this project with an Asinchronus web server?

    Let me know if you have any ideo or suggestion for this


    • Hi.
      Yes, it is possible.
      We’ll be publishing a project to display data from the database in charts in an asynchronous web server, probably in two weeks.

      • Hello Rui and Amanda,

        I’m curious, Amanad, how you get this working with XAMPP?

        For some reason it looks for my ESP that he is not addressing the file post-esd-data.php on my XAMPP-server. The errorcode showing up is -11 (whatever this will say).

        In the ESP-sketch I used this data for serverName:

        // REPLACE with your Domain name and URL path or IP address with path
        //const char* serverName = “”;
        const char* serverName = “http://localhost/post-esp-data.php”;

        I created a database ‘esp-data’ by XAMPP in MySQL and the other php-file from this example (esp-data.php) is working fine. If I run post-esp-data.php on my iMac in the XAMPP-folder this is also working (except for not posting data).

        You have to know that I’m working on iMac with XAMPP.

        What I’m doing wrong in my ESP-sketch?



        • Hi,

          In follow-up of my question before how to address my XAMPP-server, I found solution. I was stupid thinking in using the URL that is valid only on my iMac (http://localhost/….).

          Of course I need here the IP-address that is given to my localserver, as the ESP is not aware of “localhost”.
          Now it is working fine.


  32. Hi Sara & Rui,
    Great work on this project, Thank you for the tutorial.
    if I want to the latest information on the first page. In the esp-data.php modify descending id suggestion me please?

    • Hello,
      You can modify the esp-data.php PHP script in this line:

      $sql = “SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData”;

      It becomes:

      $sql = “SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData order by reading_time desc”;

  33. Hello.

    Thank you for your great tutorials. I have learned much following your work. However on this project all went smooth untill the very end.

    I have a HTTP Response of 301 showing up on my Serial monitor and no sensor data from BME 280 is getting posted to my database in My PHP Admin.

    The post-esp-data.php and esp-data.php show up all ok in my browser but empty.

    I also tried labelling my server as http and https in the arduino code (when my server is https) as advised by one of the comments here but no luck.

    Do you have any idea what the problem may be?

    Thank you.

    • You should only use HTTP (the Arduino sketch provided only supports HTTP requests). Did you keep the same API Key both in the PHP scripts and Arduino code?
      Did you had your exact domain name to the Arduino variable?

    • I had this same problem.

      I figured out that my website had SSL and “force HTTPS” enabled. This meant that my HTTP was forced to redirect to HTTPS and that messed everything up.

      To fix it, I had to turn off force HTTPS on the server side.

      • Hi,
        I have the same probleme, but how can I turn off force HTTPS, i tried turn it off from the domains, but it says that there is no SSl certificate configured.

  34. Hello Sara and Rui,

    I’m running into problems with this project
    The database and php programs are OK, but the ESP8266 is running in to an error.
    The serial monitor repeatedly shows:

    Connected to WiFi network with IP Address:

    Soft WDT reset


    ctx: cont
    sp: 3ffffde0 end: 3fffffc0 offset: 01b0
    3fffff90: 40206ea0 25b2a8c0 feefeffe feefeffe
    3fffffa0: feefeffe 00000000 3ffee628 40204c60
    3fffffb0: feefeffe feefeffe 3ffe8514 40100459

    ets Jan 8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d

    What could be the problem?
    (The esp32-web-server is running Ok)
    Cheers, Gerard

    • Hi again,
      I commented all lines that concern BME280
      and commented the lines with fixed values.
      Now the previous error is solved
      but now the HTTP Response code = -1
      I’m running local LAMP, path, rights end , password are OK
      What could wrong?

  35. Hey,

    Hope I am not too late to the party, thanks for the great tutorial! It was my inspiration for a weather station that is now in operation for some months.
    Took the liberty to use the basic method, but took the time to really make it a working setup including a graph view of the data etc.

    See my post there:

    • Hi Thomas.
      Your project look great!
      I’m always happy when I see our readers implementing our tutorials to make great projects.
      Keep up with the great work.

  36. Hello Sara, Hello Rui,

    I have followed a few of your tutorials, and they are all great!!!
    After reading the tutorial on DS18B20, I adjusted this project to send readings from 4 sensors to my database, and it works perfectly!!!

    However… may I do one suggestion?
    In my opinion, sensor-readings are numerical data, and they should be stored as such in the database. This will save you a lot of trouble when you want to do calculations on your data later on…
    For example:
    – difference between MIN an MAX temperature for a certain day or month
    – AVERAGE MIN or MAX temperature for a certain month
    – etc…

    But once again: great job!
    I’m having a hard time deciding which tutorial I will do next 😉

    Best regards,

    • Hi.
      That is just a random string set by you, to ensure that only you can post data to your database.
      That string should be the same on your sketch and on post-esp-data.php file.

  37. hello please I have a problem with the data channel on the page “post-esp-data.php” the card works and the sensors also, data are displayed on serial monitor but the problem during send data to the “post-esp-data.php” page,
    as long as I hyberge the page

  38. Thank you for sharing the knowledge, collecting the data is what I want!

    I am using the free domain server, then created /post-esp-data.php
    The URL it shows “https://…”.

    At the beginning it occurred “Error code: 1”.
    But after I changed “HTTPS” to “HTTP” of declare “serverName”, its works well now.

    Thanks again

  39. The response -1 I could solve (after testing with SOAP UI) by adding to the header in the ESP32/ESP8266 Code the followings (make sure to change to Your website’s address!):

    http.addHeader(“Accept-Encoding”, “gzip,deflate”);
    http.addHeader(“Content-Length”, “100”);
    http.addHeader(“Host”, “”); //make sure to change to Your website’s address
    http.addHeader(“Connection”, “Keep-Alive”);
    http.addHeader(“User-Agent”, “Apache-HttpClient/4.1.1 (java 1.5)*/”);

  40. I’ve done everything you showed in your tutorial but kept returning ERROR Code : -1 and No data posted with HTTP POST. I’m using ESP8266 and Flow Sensor trying to store the flowrate and volume to a database. What am I missing guys, please HELP…

  41. ERROR Code : -1 and No data posted with HTTP POST

    Not sure why. My intuition tells me it has to do with the headers.. Either way no data is being posted to phpmyadmin or Mysql.. All the data is coming in the serial monitor and all my String httpRequestData are working properly. This tells me there is no issues with the sensor or must be connection based.

  42. Thank’s work fine with a HTTP on webhos*, but on local machine refuse to connect with LAMP.
    I don’t know how to configure apache2 to connect with my local network’s machines

  43. Hi, can i use esp8266 with just wifi router only but without internet access? Can i still view the datas or receive the data in php mysql? Like localhost/network? Thanks a lot

  44. Hello and thanks a lot for this tutorial
    please is there any free way to Hosting server and domain name??
    because is not free anymore

  45. Great tuto, Santos.
    Following your instructions (which are very clear), I set up the data base and the table, and I will do the electronic part with an ESP8266 later. Thanks for sharing.

  46. Nice tutorial.
    What about if we set up a webserver to check real time data, at least when request is sended.

    If loop has a 30s delay, it will take long time to check values. any option?

    Thanks you

  47. Rui, Sara, this is really a great tutorial, thanks for providing it. I used it to a somewhat different project but the concept is same/similar.

    I am using a Mega+Wifi board (it has the ESP8266), a moisture sensor is connected to the board and as a server I am using my Synology NAS.

    By now I programmed the board and in the serial monitor I get good output:
    httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=moist01&location=loc01&value1=149
    HTTP Response code: 200
    httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=moist01&location=loc01&value1=181
    HTTP Response code: 200
    etc etc.

    Setting up the Synology NAS as a webserver, I created the database and the table, also put both PHP files in the right folder.
    When I call in the browser ip-address/test/post-esp-data.php , I get as in the tutorial “No data posted with HTTP POST.”
    When I call in the browser ip-address/test/esp-data.php , I get only the table header as described in the tutorial prior the tutorial gets to the ESP programming.

    The issue I have is that the table is not being fed with entries and I dont get any error messages or what so ever as an orientation, can you guide me on what I might be missing?

    Cheers, Alex

    • Rui, Sara, now I am also seeing my first post. Maybe something with my browser cache…

      I just applied my “deviating” project on webspace and it works great. I guess the issue I have with Synology NAS relate to some writing permissions that I will check on the Synology forum.

      Thanks again for your tutorial, great stuff and I will check out all the other projects and tutorials for more ideas and inspiration! Keep it up!

  48. Hello,
    Trying to repost my comment as the first one seems to have disappeared.

    Thanks for the great tutorials!
    Doing above steps I ran into an issue that I am not able to find a solution on, also it was touched in the comments by people but there is no solution posted or potential direction for a solution posted.

    I try to do pretty much the same as you explain but with the variation of using a Mega+Wifi board (ESP8277), with currently just one sensor and I having my database set up on my Synology NAS.

    I get good results when checking the Serial Monitor but the posting itsels seems not to work.
    Calling: ip-address/test/post-esp-data.php, I just have “No data posted with HTTP POST.” constantly.
    Calling: ip-address/test/esp-data.php, I just see the empty table with the column headers.

    I went by now through the ESP code to check for typos, also went through all kind of trouble shooting related to MariaDB of the Synology but I couldnt find the root cause.

    Appreciate any guidance you can provide or food for thought on the trouble shooting.


  49. Amazing

    I am realy amazed

    Thank you Sara and Rui

    I subscribed to bluehost. Never seen such wonderful customer support.

    This example worked from the first click even with bme 680 with minor change

    the only thing is that the server time is different than my local time. I should search the web to find the right functions

    many thanks

  50. Hi,
    From the Arduino Serial Monitor, I am getting HTTP Response code: 200, but in my database, nothing gets inserted. I am using infinityfree hosting. Also, I can access both post-esp-data.php and esp-data.php
    What could be the issue?
    Thanks for your time.

      • In case someone wants to try this tutorial on free hosting I found out that works.
        The only issue that I am getting is from time to time I get Error code: -11 which isn’t an HTTP error.
        What could be the reason for that error code?

  51. Hello Sara and Rui
    I managed to make a MESH network with 3 ESP32 (DEVKITV1) being one the “server” and the others two as “client”. In both, I can put analog values in some inputs (three) and obtain the reading of the values on the “server”.
    Now I would like to take the next step: send the data to an SQL “database”.
    What I get on the server is:
    logServer: Received from 2884070797 msg = {“Serial”: “COMxx”, “node”: 2884070797, “V_wind”: 3.299194, “V_sun”: 0, “V_bat”: 3.299194}
    logServer: Received from 3294438085 msg = {“serial”: “COMxx”, “node”: 3294438085, “V_wind”: 0, “V_sun”: 1.687866, “V_bat”: 0}
    Where and how should I start to proceed ??

  52. From the Arduino Serial Monitor, I am getting HTTP Response code: 200, but in my database, nothing gets inserted. I am using infinityfree hosting. Also, I can access both post-esp-data.php and esp-data.php
    What could be the issue?

    Note: i am using hosting which, I think, is suitable.

        • It’s hard to tell without testing and trying the server configurations, but if it’s a free hosting platform it will probably not work. They will block all connections from ESP devices to avoid resources usage.

          • Hi.
            I just tried to use another nonfree hosting platform (Education Host) and it still doesn’t send any data. I get HTTP response code:200. Any suggestions, please??

  53. Hi
    First of all, let me thank you for the wast amount of information, posted in here.
    I’ve been using this site as a reference and resource for a lot of my projects.

    I’ve used this guide, as a reference to a sensor project, where i post data from a modded ESP32(POE enabled).
    I wanted to make a dashboard, and used grafana as the tool.
    To make it work, i had to make some changes to the mod-headers, and it might have messed up the communication between the ESP32 and raspberry. Sending the HTTP headers.

    The Error! :
    In my “post-esp-data.php”, that has been working flawlessly for months, i get the error:
    PHP NOTICE: Undefined index: Request Method in /path/post-esp-data.php

    Do you have any idea, whatsoever, how i messed up?
    I think it stopped, when i got grafana working.
    Am i messing up port conf?
    Or might it be the mod-header conf?

    I hope, that you might point me in the right direction.

    I am not able to read the serial output, while the ESP32 are connected, BC of the POE configuration. At some point, i will make a cable for just serial comms, but right now, i’m forced to using the USB port, while disconnected from the system.

    Either way, much appreciation for this website.

    Sincerly Sebastian

  54. I have the Display withy everything listed in my web browser, and I get the HTTP Response code: 200 reply back in the serial terminal.

    I also see the sensor data changing in the serial monitor…

    But the there is no updates of the variables in the browser window.

    could there be something wrong with the database or the post-esp-data.php ?

  55. Thanks very much for this tutorial. I have it running and it does exactly what I needed to be done. I am new to this type of programming and am wondering why VALUES are entered into the INSERT INTO code using concatenation for single and double quotes in the code for file post-esp-data.php? Using ‘” . $sensor . “‘ rather than ‘$sensor’. I understand the entire INSERT INTO code needs to be double quoted. Thanks.

    • Hello Robert,
      The single quote is used to concatenate ‘
      The double quote is used to define the values ”

      In the end, the $sql variable will look like this:
      INSERT INTO SensorData (sensor, location, value1, value2, value3) VALUES (“sensor_value” , “location_value”, “value1_value”, “value2_value”, “value3_value”)

  56. Good afternoon, Rui and Sara!
    First of all, I want to thank you for the excellent projects that you publish here on the site!

    I am trying to hire a host service to put my project in the cloud. You recommended Bluehost for being friendlier.

    Could you tell me if on Amazon WS or Azure you have similar plans? I’m doing a job for college and they have free plans for students.

    Another question, when I tried to hire by bluehost they asked which version of php the project uses. Does version 7.3-7.5 support?

    I await your reply!

    • Hello, it should definitely work with most hosting providers, unfortunately I can only test or setup with a hosting that I already use.
      It should definitely work with AWS, but I don’t have any tutorials for it. However, free hosting providers will not work because they block the ESP connections or limit the amount of connections to avoid resource usaage.

      It should work with any PHP 7 version. I recommend that latest version.


  57. Good afternoon, Rui and Sara!
    I want to thank you for the projects that you publish here.
    But I have a problem.
    I get “HTTP Response code: 500” what does it mean.
    No data is shown on the display.
    Also there is no data in the SQL-Database.
    Serial monitor is showing: httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=23.77&value2=36.11&value3=1003.89
    HTTP Response code: 500
    I’m working with a local NAS with PHPMyAdmin and MySQL installed.

    Regards Matthias

  58. Hello everybody!

    This “No data posted with HTTP POST.” is a serious issue, I see.

    I had problem at Infinity hosting so I tried at my local machine with default Wampserver 3.2.0 and the issue is still there. I don’t think that is because free hosting providers are blocking ESP traffic.

    I am testing without ESP device, just pasting and refreshing this link: post-esp-data.php?api_key=222&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14 and I get “No data posted with HTTP POST.”

    When pasting wrong api key in link, there is the same echo “No data posted with HTTP POST.”. “Wrong API Key provided.” is not triggered. So php script is not executed below “($_SERVER[“REQUEST_METHOD”] == “POST”)”

    Rui Santos, please look deeper into this when you find spare time.

    Best regards and thank you.


Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.