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 (http://example-domain.com) 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:

CREATE TABLE SensorData (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sensor VARCHAR(30) NOT NULL,
    location VARCHAR(30) NOT NULL,
    value1 VARCHAR(10),
    value2 VARCHAR(10),
    value3 VARCHAR(10),
    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

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:

<?php

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  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
$dbname = "REPLACE_WITH_YOUR_DATABASE_NAME";
// REPLACE with Database user
$username = "REPLACE_WITH_YOUR_USERNAME";
// REPLACE with Database user password
$password = "REPLACE_WITH_YOUR_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 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $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;
        }
    
        $conn->close();
    }
    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:

http://example-domain.com/post-esp-data.php
ESP32 ESP8266 Test POST ESP Data PHP URL

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>
<html><body>
<?php
/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  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
$dbname = "REPLACE_WITH_YOUR_DATABASE_NAME";
// REPLACE with Database user
$username = "REPLACE_WITH_YOUR_USERNAME";
// REPLACE with Database user password
$password = "REPLACE_WITH_YOUR_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">
      <tr> 
        <td>ID</td> 
        <td>Sensor</td> 
        <td>Location</td> 
        <td>Value 1</td> 
        <td>Value 2</td>
        <td>Value 3</td> 
        <td>Timestamp</td> 
      </tr>';
 
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> 
              </tr>';
    }
    $result->free();
}

$conn->close();
?> 
</table>
</body>
</html>

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:

http://example-domain.com/esp-data.php
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 MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematics

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 https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  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>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif

#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 = "http://example.com/post-esp-data.php";

// 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() {
  Serial.begin(115200);
  
  WiFi.begin(ssid, 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());

  // (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
    http.begin(serverName);
    
    // 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: ");
    Serial.println(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: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);  
}

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 = "http://example-domain.com/post-esp-data.php";

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
http.begin(serverName);

// 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";

Demonstration

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:

http://example-domain.com/esp-data.php

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.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


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

97 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.
      Regards,
      Rui

      • 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 (wetter.cuprum.de – 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

    • Hi Stefan.
      Thank you so much for sharing your project and congratulations! Your project looks great! People love data visualization in graphics 😀
      Regards,
      Sara

        • Hi.
          Sometimes when that error is printed in the Arduino IDE Serial Monitor, but the data is still inserted into the server.
          If your server is not receiving the data, make sure you have the right files saved in your server (/esp-data.php /post-esp-data.php)
          Regards,
          Sara

  2. getting stuck at the end of step #…put in my website address
    mywebsite.com/esp-data.php

    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.

    Thanks

    Chris

    • 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.
      Regards,
      Sara

  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.
    Thanks

    • 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.
      Regards,
      Sara

  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

    Regards
    derek

  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: https://raw.githubusercontent.com/RuiSantosdotme/ESP32-ESP8266-PHP-MySQL/master/code/esp-data.php

      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.

      Regards,
      Sara

      • Sara,

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

        Regards,
        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.
      Regards,
      Sara

      • 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

        • 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 ?

    Regards,
    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.
      Regards,
      Sara

  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: cloudways.com/en/digital-ocean-cloud-hosting.php.

  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

    Regards,
    Kim

    • 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,
    Kim

  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.
      Regards,
      Sara

  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,

        Tim

  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/shybearnc.net/public_html/post-esp-data.php on line 32″. I’m not sure what the error message means. By the way, I’m using Hostinger.com 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.

      Regards,
      Rui

      • 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

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

    • Sometimes it retrieves an error code, but the data is still being inserted in the database.
      Can you check your tables to see if the data is there?

      Regards,
      Rui

  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.
        Regards
        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 “veldbies.nl” and is a secure site. So http:// will be redirected to https://

    Browsers can handle this problem.

    Your script returns:

    Connecting
    …..
    Connected to WiFi network with IP Address: 192.168.2.15
    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!
    Regards
    Alan

  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?

    • 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

  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

    Attilio

    • 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.
      Regards,
      Sara

      • 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 = “http://example.com/post-esp-data.php”;
        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?

        Regards,

        Jop

        • 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.

          Regards,
          Jop

  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?

  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:

    Connecting
    .
    Connected to WiFi network with IP Address: 192.168.178.37

    Soft WDT reset

    >>>stack>>>

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

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

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

    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?
      Cheers
      Gerard

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.