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

Updated on 26 March 2023

You’ll also have a web page that displays the sensor readings, timestamps, 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 ESP32 or ESP8266 board. You can modify the code provided to send readings from a different sensor or use multiple boards.

In order to create and 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

Table of Contents

The project is divided into the following main sections:

  1. Hosting Your PHP Application and MySQL Database
  2. Preparing Your MySQL Database
  3. PHP Script HTTP POST – Insert Data in MySQL Database
  4. PHP Script – Display Database Content
  5. Setting up the ESP32 or ESP8266

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 to your domain name (https://example-domain.com) and see the sensor readings from the ESP32 or ESP8266.

If you like our projects, you might consider signing up for 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:

https://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 on 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:

https://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. Setting up the 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. The sketch is slightly different for each board.

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

Installing Libraries

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:

ESP32 Code

Follow this section if you’re using an ESP32. For an ESP8266 click here.

After installing the necessary board add-ons and libraries, 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.

*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.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 = "https://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){
    WiFiClientSecure *client = new WiFiClientSecure;
    client->setInsecure(); //don't use SSL certificate
    HTTPClient https;
    
    // Your Domain name with URL path or IP address with path
    https.begin(*client, serverName);
    
    // Specify content-type header
    https.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 = https.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //https.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = https.POST("Hello, World!");
    
    // If you need an HTTP request with a content type: application/json, use the following:
    //https.addHeader("Content-Type", "application/json");
    //int httpResponseCode = https.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
    https.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 = "https://example-domain.com/post-esp-data.php";

Now, you can upload the code to your board.

Note: Most servers require you to make HTTPS requests. The code above makes HTTPS requests to be compliant with the requirements of most cloud servers nowadays.

Your server doesn’t support HTTPS? Use this code instead.

If you want to learn how the code works read the following 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;
  • 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;
  • Initialize a secure WiFi client.

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(client, 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";

Learn more about HTTPS Requests with the ESP32: ESP32 HTTPS Requests (Arduino IDE).

ESP8266 Code

Follow this section if you’re using an ESP8266. For an ESP32 check the section above.

After installing the necessary board add-ons and libraries, 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.

*/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.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 = "https://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){

    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);

    // Ignore SSL certificate validation
    client->setInsecure();
    
    //create an HTTPClient instance
    HTTPClient https;
    
    // Your Domain name with URL path or IP address with path
    https.begin(*client, serverName);
    
    // Specify content-type header
    https.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 = https.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //http.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = https.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 = https.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
    https.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 = "https://example-domain.com/post-esp-data.php";

Now, you can upload the code to your board.

Note: Most servers require you to make HTTPS requests. The code above makes HTTPS requests to be compliant with the requirements of most cloud servers nowadays.

Your server doesn’t support HTTPS? Use this code instead.

Learn more about HTTPS Requests with the ESP8266: ESP8266 NodeMCU HTTPS Requests (Arduino IDE).

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:

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

You should see 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:

Learn more about the ESP32 with our resources:

Thank you for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

356 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

      Reply
      • 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’

        Reply
      • Hello Rui Everything is working well. However, from the php page post-esp-data.php I got the message “No data posted with HTTP POST.” whereas the connection is working well. I do not see where is the issue down through the if conditions…. it should write “New record created successfully”
        data are correctly inputed in the data base… so i do not see at all where is the problem.
        thanks for your tutorial and hope u ll get some time to answer. thanks

        Reply
  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

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

    Reply
  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

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

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

    Reply
  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

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

      Reply
  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

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

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

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

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

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

    Reply
  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 😇

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

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

        Reply
        • 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’

          Reply
  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

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

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

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

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

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

      Reply
  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

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

      Reply
  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

    Reply
  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

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

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

    Reply
  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!

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

        Reply
  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

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

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

        Reply
  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

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

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

          Reply
  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

    Reply
  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

    Reply
  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

    Reply
  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

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

        Reply
  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 🙂

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

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

      Reply
      • 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!

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

    Reply
  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

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

    Reply
  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

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

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

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

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

    Reply
    • 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”;

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

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

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

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

        Reply
        • Did you ever fix this? I am having the same issue and the hosting company can not figure out how to disable forced HTTPS.

          Reply
          • Hi.
            We’ll update the tutorial soon to be compatible with HTTPS.
            In the next few days, we’ll have this tutorial updated.
            Stay tuned.
            Regards,
            Sara

          • FINALLY got to the bottom of my problem, turns out the host provider wasn’t keeping there PHP up-to date. Woke up do a database that had been logging all night and is still going.

            Also had an email saying they re-zeroed’ everything and updated the PHP and had a side note basically saying that is all they would do and that i should contact a software developer because there was probably an issue with the code………this is after multiple times telling them the code was working fine until in the middle night it stopped. Needless to say i am not happy with hostmonster right now

  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

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

      Reply
  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: http://projects.xief.net/?p=638
    Best,
    Thomas

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

      Reply
  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,
    Jan.

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

      Reply
  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

    Reply
  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

    Reply
  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 example.com to Your website’s address!):

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

    Reply
  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…

    Reply
  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 syntax..it must be connection based.

    Reply
  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
    🙂

    Reply
  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

    Reply
  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

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

    Reply
  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

    Reply
  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

    Reply
    • 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!

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

    Thanks!

    Reply
  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

    Reply
  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.
    Regards,
    Joel

    Reply
      • In case someone wants to try this tutorial on free hosting I found out that 000webhost.com 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?

        Reply
  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 ??
    Hugs
    Manel

    Reply
  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 000webhost.com hosting which, I think, is suitable.

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

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

          • I tried infinityfreeapp free webhosting and it doesn’t send any data. I get HTTP response code:200 so it means it’s okay. What could be the possible problems here?

          • Hi.
            Some free webhosting services don’t work with this project.
            Maybe that’s one of them.
            Regards,
            Sara

  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

    Reply
  54. I have the http://example.com/esp-data.php 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 ?

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

    Reply
    • 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”)

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

    Thanks,
    I await your reply!

    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.

      Regards,
      Rui

      Reply
  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

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

    Reply
  59. Hi, Thank you four the very good tuto..
    I just have a question/Problem
    I become this message : httpRequestData: api_key=tPmAT5Ab3j7F9&sensorId=12621789&latitude=null&longitude=null&altitude=null&PM10=5.10&PM25=3.40&temperature=null&humidity=null
    HTTP Response code: 200
    but i can’t see the data in my database or in my “http://example-domain.com/esp-data.php” .. I’m not sure but i think the cause can be “the missed DB User and the password” in my arduino code .. I don’t know how to add and also I’m not sure if it’s really the reason why i still can’t see the data in my database even when i have 200 als http response code

    Reply
  60. Amazing Tutorial…
    Can you please guide me how can we take user input from esp-data webpage and send it to esp32 to change the data frequency time like in this case we have 30 seconds? I am new to all this so don’t know how to take user input and send to esp32….

    Reply
  61. Hi – Thank you for a great tutorial.

    I have this project running successfully and tracking a system. Is it possible to add a password protection to the php file which displays the data? Can anyone suggest some suitable code?

    Kind regards

    Paul

    Reply
  62. Hi Rui and Sara (Do you speak Portuguese)?

    I’m trying using your code as the base for my project, but an update in a library ’cause some issues for this line:

    http.begin(serverName);
    “call to ‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)”

    Do you have an idea how to fix it?
    Greetings from Brazil

    Reply
  63. Hi Rui and Sara,
    great project, congratulations. It works great with ESP32. I tried to load it on a NodeMCU 1.0 (ESP-12E Module) but upon compilation I also receive the error message: http.begin (serverName);
    “Call to ‘HTTPClient :: begin’ declared with attribute error: obsolete API, use :: begin (WiFiClient, url)”.
    Help, I’ve been fighting for days but I can’t solve it, thanks.
    Greetings

    Reply
    • Hi.
      There were some updates to the library.
      Change the code as explained below:

      old:

      HTTPClient http;
      http.begin(“http://www…….”);

      new:

      WiFiClient client;
      HTTPClient http;
      http.begin(client, “http://www…….”);

      We’ll update the code as soon as possible.
      Regards,
      sara

      Reply
  64. per chi fosse interessato, ho risolto cambiando la versione della board. in gestione scheda cercare 8266 e cambiare da 3.0.0 a 2.0.74

    “for those interested, I solved it by changing the version of the board. in card management look for 8266 and change from 3.0.0 to 2.0.7”

    Reply
  65. I am getting http error code 400.
    httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=Pulse Sensor&location=Office&value1=1861&value2=1869&value3=1870
    HTTP Response code: 400
    httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=Pulse Sensor&location=Office&value1=1888&value2=1889&value3=1885
    HTTP Response code: 400

    Reply
  66. Bom dia. Excelente tópico, porém em meu caso está retornando o Code -1. Estou usando esp8266, já tentei alterar as versões do php, mas nada mudou….

    Reply
  67. Hello Sir!
    In your tutorial, I tried to replace the BME280 sensor with as DS18B20 Temperature sensor. I completed all steps which show on your website. When I upload the code for ESP8266, in the screen monitor of Arduino IDE, it displays HTTP response code 200 and the value of the temperature sensor. But, it didn’t display any information in URL http://abcxyz.com/esp-data.php. The URL which I just illustrate. Also, it didn’t have any information database in MySQL too.
    Please tell me what should I do next?
    Give me advice. Thank you, Sir.

    Reply
  68. Hi, thanks you for taking the time to write such a useful post! I followed it and everything is working as expected. It’s brilliant!!

    I would like to take things a little further but I’m not sure how and I was wondering if you could point me in the right direction.

    Rather than send data every 10seconds to my server, is it possible to take a sample of data every 10seconds and either store it on an SD card or maybe in a buffer, then after 1 min send 6 rows of data to the server?

    I imagine it is possible but I’m just struggling to find a staring point. Any help or guidance would be greatly appreciated.

    Thanks you,

    Gary

    Reply
      • Hi Sara,

        Thanks for replying so quickly!

        I’m comfortable storing data on the SD card, what I can’t quite figure out is how to send a batch of sample data in one go.

        For example, every 10 seconds my accelerometer stores XYZ data somewhere (buffer or SD card), then after 1 minute the esp32 sends all 6 samples (6x10sec in 1 min) to the database as per the above SQL database tutorial.

        Thank you

        Gary

        Reply
        • You would have to read the first 6 lines of samples stored on the microSD card, and then send 6 requests. One for each line of saved data.
          It may be a bit tricky to select each line from the microSD card file, but it is possible.
          Check for tutorials that read data from SD card line by line.
          I hope this helps.
          Regards,
          Sara

          Reply
          • Hi Sara,

            Further the comments above I have managed to store the data to in an array (instead of using Strings) and that is writing to the database table without issue.

            Do you have any guidance on how I would write multiple rows of data to the table in on go? My code uses an RTC sync’d with the NTP server, the function the stores the data in an array every 10s, then on the 51st second uses your method in the above tutorial to write the data to the table. The issue I’m having is it’s only writing the first row of data every 51st second, not 6 rows as I would like.

            I attempt to post the data using the following:-

            http.POST(httpRequestData_00s);

            http.POST(httpRequestData_10s);

            http.POST(httpRequestData_20s);

            http.POST(httpRequestData_30s);

            http.POST(httpRequestData_40s);

            http.POST(httpRequestData_50s);

            However only httpRequestData_00s appears in the table.

            I have also tried to concatenate the above httpRequestData_00s thu to httpRequestData_50s but that didn’t work either.

            I think the issue must be server side but I don’t know PHP or SQL all that well so I have no idea how to post all 6 rows.

            Any help would be appreciated.

            Thank you

            Gary

  69. Good morning, I have a little bug, I signed the bluehost website and put all the code above, but when I add information to the database it doesn’t update on the web page, only when I change the name of the file it updates, I found very strange, could you help me?

    Reply
    • Hello,
      What happens if you press in your web browser page the keys Ctrl+F5. It looks like your web page is currently cached and it saves the last state.

      If refreshing the web page works with Ctrl+F5, then contact bluehost and ask them to disable cache in your server.

      Thanks for your patience.

      Reply
  70. good morning gentlemen,
    I have used this code successfully in a remote database.
    But when I go to connect to a local database then it does not connect.
    my string is: const char * serverName = “https: //localhost/esp_conn/post-esp-data1.php”;
    and : const char * serverName = “http: //localhost/esp_conn/post-esp-data1.php”;
    please tell me what I am doing wrong.
    sinserely
    Stratis Chatzirallis

    Reply
    • Hello Stratis, you must use your local IP address, you can’t type localhost.

      const char * serverName = “http://192.X/esp_conn/post-esp-data1.php”;

      I hope that helps.
      Regards,
      Rui

      Reply
      • dear sir!
        I can’t use http.begin(“http://…post-esp-data.php”) syntax. they always give error “begin(WiFiClient, url)”, I don’t understand this syntax yet.
        when i declare “WiFiClient client;” add using http.begin(client, serverName); it compiles but doesn’t working.

        Reply
  71. Hi. I used http.GET() with my local LAMP server, and it worked. Now after the syntax changed to http.begin(client,serverName); -form, it does not work any more. I tried to move to this http.POST(“xxx”) , but I don’t get it working either, but get error code: -1. Is this really correct and enough with a local server?
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

    Reply
  72. hi all!
    I have some problems as follows:
    – I can’t use the following syntax, “http.begin(http://192.168.1.10:8081/espdemo/post-esp-data.php); they always give me an error “error: call to ‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)”
    i don’t understand what is “wificlient” parameter?
    – when i use:
    HTTPClient http;
    WiFiClient client;
    http.begin(http://192.168.1.10:8081/espdemo/post-esp-data.php)
    then the compiler can compile but they don’t working.
    – Has anyone had success with the program above?.
    Thank for all!

    Reply
    • Hi.
      The correct syntax is http.begin(client, “http://XXXXXXX”);
      You’re not passing the “client” parameter to the begin() method.
      Try the following:
      http.begin(client, “http://192.168.1.10:8081/espdemo/post-esp-data.php”);

      Regards,
      Sara

      Reply
  73. Hi, I have everything working great. One issue I have is if a value is 100 then it puts it as Min value instead of Max. Any ideas?

    Reply
  74. Hello. I really have enjoyed and been challenged by this project! I have a number of ESP32 devices running continuously to measure data every 6 hours. I have found some level of instability and that continuous operations are not possible. I introduced a WatchDog Timer which made a lot of sense to me. But this doesn’t seem to solve the problem. In fact the WDT is resetting in the loop as it should, but at some point the WiFi has disconnected so no readings are made. Perhaps a 6 hour delay is not a good idea for this device. Would it make sense to move the entire WiFi code into the loop and re-establish it only for a measurement, and then close it until the next loop. If the WiFi cannot be re-established, the device should reboot.

    Reply
    • Hi Robert,
      I have ESP32’s that runs for month, and I have ESP8266’s that have run for years, both controlling horticultural projects. My devices control irrigation and propagation systems. They use MQTT and WiFi to communicate with my Home Assistant based data recording and display system. I monitor numerous sensors and send data every 15 minutes.
      When using MQTT the system checks the MQTT connection every few seconds and to do so it also checks the WiFi is connected. I have not experienced the problems you describe.
      In my opinion if you want a fully effective watchdog you need an external device like a 7555 (555) monostable timer which runs continuously, if the ESP32 doesn’t reset it because it is hung in a loop, the 7555 timer times out and outputs a reset pulse to the ESP32 and causes a full reset. There are rare times, when using MQTT, that the ESP gets into an endless loop trying to reconnect to the mqtt broker but not triggering the internal WDT. The external WDT overcomes that issue.
      I don’t know if your system is similar but I can assure you that provided the power supply is good ESP devices will run for very long periods of time without issue.
      If possible, for the long delay (6 hrs) could you use NPT time with, perhaps, the EZtime library and trigger the sensor reading / send at predefined hours?
      I don’t know how you do your timing but as an alternative to the above suggestion I would create a second counter with a built in timer, then a minute counter, then an hour counter, do my processing of sensor etc. then reset all counters to zero. You could check your WiFi connection every few seconds in the main loop and if not connected call a re-connect function. Hope this helps.

      Reply
  75. Bob. Thaks so much for this detailed response. I must admit that I am not familiar with much of what you have said, but I do like a learning challenge. My initial Google searches have shed some further light on MQTT, the 7555, Home Assistant, EZtime and NTP. I will start some detailed learning in order to appreciate how these elements can help with my project. This is valuable information and an interesting direction to pursue. Still, I do remain interested in how the code in this tutorial can be tweaked to address stability if in fact this is a sensible question. Perhaps there are other issues at play and your detailed response outlines the best technical path forward. The incredible path of learning just keeps interconnecting with new paths to explore – exciting. Thanks again.

    Reply
    • Hello again,
      Ideally all project should be modular so that you can get them working stage by stage. The project, books etc. that Ruis and Sara publish are very good and typically can be incorporated in or used as the basis of wider projects. The particular project module on which you posted is designed to store and retrieve data. so, an inital design consideration of your own project is do you need to store / retrieve / view your data just locally or from anywhere in the world? There are many options for either scenario.
      In the instance you posted about I would say something is failing on the ESP32 / 8266 rather than the server or database. I would suggest you build a simple project just to emit some data every 6 hours to a serial terminal, initally you can try it at 5 minutes, then 15 minutes and gradually increase it to 6 hours. Coolterm is a very good terminal software (free) to monitor serial out from the ESP. I am happy to help if you have specific questions.

      Reply
      • Hello. I like your suggestion and have commenced reading up on Coolterm and serial monitoring – again new to me. It may be helpful to ask a couple of questions – Is there private messaging on this site?

        Reply
        • Hello Robert,

          I don’t know about private messaging on this site Ruis or Sara would need to answer that question. If they are agreeable I am happy for them to share my email address with you.

          Reply
  76. Hello Sir! Good day does this work in soil moisture sensor too? because now im using a soil moisture sensor to send its data to the database. btw im using a xampp.

    Reply
  77. Hi, Sara and Rui. Very nice tutorial you worked on here.
    I am using Xampp server and followed all instructions in this tutorial.
    The http post is returning -1 and not posting anything in localhost. Ive checked my ip address but its still not working. I’d really appreciate your help

    Reply
  78. Ola, gostaria de saber como fazer o caminho inverso, ou seja, ler os valores do banco de dados no esp32. Pois eu daria comandos para gravar no banco de dados da página html e no esp32 iria atualizando a leitura.

    grato

    Reply
  79. Hi.
    i have a problem. sata is using esp8266 and I have followed all the steps according to the instructions and the serial monitor is showing HTTP Response code: 200. but for some reason, in my database the data does not enter. Please help

    Reply
  80. Hi All,

    Building a MySQL database for a ESP32 from a Bluehost domain.
    Step 1.
    https://mydomainname.com/post-esp-data.php
    No data posted with HTTP POST.
    This is O.K.

    Step 2.
    This step failed
    https://mydomainname.com/esp-data.php
    Results in the browser:
    Connection failed: Access denied for user ‘tritonS4_esp_hvd’@’localhost’ (using password: YES)

    Standard format did not show up in browser.

    Any ideas. Is there a way to look at settings and username and other?

    Phil

    Reply
  81. Hi All,

    I just got past the errors in last comment. now, I am getting HTTP error 400 with htpp:// and 302 code any ideas.

    My Host Provider is Blue Host. Domain name should allow access not unless there are check boxes somewhere to allow external logger to reach the //public.html file manager folder.

    Reply
  82. Hello,

    I got the code working on my ESP32 and the serial monitor says that the values are succesfully uploaded (HTTP code 200). The log files on my server tell me the same, but for some reason the values are not added to the SQL database. I entered all the passwords correctly and I didn’t change the API key or anything else. The only thing that is changed to the ESP32’s code is that I’m using set values. Does someone here have any suggestions what to try next?

    Reply
  83. String httpRequestData = “api_key=” + apiKeyValue + “&sensor=” + sensorName + “&location=” + sensorLocation + “&value1=” + String(mpu.temperature());

    I tried use the code above, but I change the BME with MPU6050, but the code cant compile. I get “expression cannot be used as a function” error. Can anyone help me

    Reply
  84. Many thanks for this project.
    Quick question. I have an ESP32 which will always be connected to a Raspberry Pi through a serial cable. The Raspberry Pi will be powered by an Ethernet cable through POE which inturn powers the ESP32. If I want to disable the ESP32 wifi and only use the serial communication this part of the code above should be commented, right?

    /*
    const char* ssid = “REPLACE_WITH_YOUR_SSID”;
    const char* password = “REPLACE_WITH_YOUR_PASSWORD”;
    */

    Reply
  85. i have a funny problem .. my code is working but i can only write 2 lines into my database and then i get a “Error code: -1”
    after a reset of the esp it writes 2 lines and then “Error code: -1”

    9:37:25.198 -> Connected to WiFi network with IP Address: 192.168.36.127
    09:37:25.198 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=HC-SR04&location=Home&value1=tPmAT5Ab3j7F9&value2=HC-SR04&value3=Home
    09:37:25.384 -> HTTP Response code: 200
    09:37:35.360 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=HC-SR04&location=Home&value1=tPmAT5Ab3j7F9&value2=HC-SR04&value3=Home
    09:37:35.499 -> HTTP Response code: 200
    09:37:45.471 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=HC-SR04&location=Home&value1=tPmAT5Ab3j7F9&value2=HC-SR04&value3=Home
    09:37:50.712 -> Error code: -1
    09:38:00.697 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=HC-SR04&location=Home&value1=tPmAT5Ab3j7F9&value2=HC-SR04&value3=Home
    09:38:05.902 -> Error code: -1

    so something is rotten in the kingdom of Denmark … but where?

    Reply
      • 😮 this is embarrassing my problem is apparently in my own firewall, when i use local ip of my sql it works perfect…

        i am using a synology as web host with a MariaDB5 SQL everything on a static IP

        i have to look deeper into my router/firewall log.

        thanks for quick response
        Michael

        Reply
  86. welcome members
    i am using Esp32 which connects to Wifi router and also connects to esp32-now.Esp32 connects well to router (I get good data from mysql). so does Esp-now (all connect well) .
    But my problem is that when I use the HTTPClient the connection between Esp-now is broken, but the data on the router is running fine.
    I’ve been looking for a solution for two weeks now but I really haven’t found one yet.
    appreciate

    Reply
  87. Welcome members
    i am using Esp32 which connects to Wifi router and also connects to esp32-now.Esp32 connects well to router (I get good data from mysql). so does Esp-now (all connect well) .
    But my problem is that when I use the HTTPClient the connection between Esp-now is broken, but the data on the router is running fine.
    I’ve been looking for a solution for two weeks now but I really haven’t found one yet.
    appreciate

    Reply
    • Here is the code: note that it works fine but this is the one I wrote about above.
      I posted a comment on the problematic HttpClient.

      #include <HTTPClient.h>
      #include <WebServer.h>
      #include <esp_now.h>
      #include <WiFi.h>
      #include <Wire.h>
      #include <esp_wifi.h>
      //HTTPClient http;
      #define ssid “My ssid” // WiFi SSID
      #define password “My WiFi password” // WiFi password

      //const char* serverName = “http://localhost”;
      String str_mac;
      String mtrame = “”;
      WebServer server(80);
      int btn_avant = 16;
      //—————–FIN WEB FOTSINY

      // REPLACE WITH YOUR ESP RECEIVER’S MAC ADDRESS

      //uint8_t broadcastAddress1[] = {0xF4, 0xCF, 0xA2, 0x5B, 0xAE, 0x44}; //Vide

      //uint8_t broadcastAddress2[] = {0xEC, 0xFA, 0xBC, 0x63, 0x2A, 0xF1}; //EC:FA:26:63:C3:F1 = Camion

      uint8_t broadcastAddress1[6];
      typedef struct test_struct {
      int x;
      int y;
      } test_struct;

      test_struct test;

      /*
      typedef struct test_struct2 {
      int x2;
      int y2;
      } test_struct2;

      test_struct2 test2;
      */

      // callback when data is sent
      void OnDataSent(const uint8_t mac_addr, esp_now_send_status_t status) {
      char macStr[18];
      Serial.print(“Packet to: “);
      // Copies the sender mac address to a string
      /

      snprintf(macStr, sizeof(macStr), “%024:%00A:%0C4:%0FA:%01F:%080”,
      mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);

      */

      snprintf(macStr, sizeof(macStr), “%02x:%02x:%02x:%02x:%02x:%02x”,
      mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);

      Serial.print(macStr);
      Serial.print(” send status:\t”);
      Serial.println(status == ESP_NOW_SEND_SUCCESS ? “Delivery Success” : “Delivery Fail”);
      }

      void setup() {
      pinMode(btn_avant,INPUT);//Bouton Avant arriere
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      /*
      WiFi.printDiag(Serial); // Uncomment to verify channel number before
      esp_wifi_set_promiscuous(true);
      esp_wifi_set_channel(CHAN_AP, WIFI_SECOND_CHAN_NONE);
      esp_wifi_set_promiscuous(false);
      WiFi.printDiag(Serial); // Uncomment to verify channel change after
      */

      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());

      /*
      if(WiFi.status()== WL_CONNECTED){

      Serial.print(“Channel oe:”);
      Serial.println(WiFi.channel());

      //WiFiClient client;

      // Your Domain name with URL path or IP address with path
      //http.begin(client, serverName);
      http.begin(serverName); /////Ici le problème dès qu'on l'active la transmission ESP NOW //devient faild!

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

      // Prepare your HTTP POST request data

      String httpRequestData = "man_num=10";

      Serial.print("httpRequestData: ");
      Serial.println(httpRequestData);

      // Send HTTP POST request
      int httpResponseCode = http.POST(httpRequestData);

      if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      str_mac = http.getString();
      Serial.print("str_mac: ");
      Serial.println(str_mac);
      }
      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

      */

      server.on ( “/”, handleRoot );
      server.begin();

      delay(1000);
      /*
      uint8_t primaryChan = WiFi.channel();
      wifi_second_chan_t secondChan = WIFI_SECOND_CHAN_NONE;
      esp_wifi_set_channel(primaryChan, secondChan);
      ESP_ERROR_CHECK(esp_wifi_set_promiscuous(true));
      */

      //WiFi.reset();
      Serial.print(“str_mac farany: “);
      Serial.println(str_mac);
      //str_mac =”C2:32:A2:B5:AE:44”;

      char str[str_mac.length() + 1];
      str_mac.toCharArray(str, str_mac.length() + 1);

      //char str[] = “C2:32:A2:B5:AE:44”;

      char* ptr;
      broadcastAddress1[0] = strtol(str, &ptr, HEX );
      for( uint8_t i = 1; i < 6; i++ ) {
      broadcastAddress1[i] = strtol(ptr+1, &ptr, HEX );
      Serial.println(broadcastAddress1[i]);
      }

      // WiFi.mode(WIFI_STA);

      if (esp_now_init() != ESP_OK) {
      Serial.println(“Error initializing ESP-NOW”);
      return;
      }
      Serial.println(“WiFi chanel ndray:”);
      Serial.println(WiFi.channel());
      esp_now_register_send_cb(OnDataSent);

      // register peer
      esp_now_peer_info_t peerInfo;
      //peerInfo.channel = WiFi.channel();
      //peerInfo.ifidx=WIFI_IF_AP;
      peerInfo.channel = 1;
      peerInfo.encrypt = false;
      // register first peer
      memcpy(peerInfo.peer_addr, broadcastAddress1, 6);
      if (esp_now_add_peer(&peerInfo) != ESP_OK){
      Serial.println(“Failed to add peer”);
      return;
      }

      /*
      // register second peer
      memcpy(peerInfo.peer_addr, broadcastAddress2, 6);
      if (esp_now_add_peer(&peerInfo) != ESP_OK){
      Serial.println(“Failed to add peer”);
      return;
      }

      /// register third peer
      memcpy(peerInfo.peer_addr, broadcastAddress3, 6);
      if (esp_now_add_peer(&peerInfo) != ESP_OK){
      Serial.println(“Failed to add peer”);
      return;
      }
      */

      }
      void mseries(){

      //——————————-WIFI SERIE—————————————-
      //WiFi.reset();
      Serial.print(“str_mac farany: “);
      Serial.println(str_mac);
      //str_mac = “C2:32:A2:B5:AE:44”;

      char str[str_mac.length() + 1];
      str_mac.toCharArray(str, str_mac.length() + 1);

      //char str[] = “C2:32:A2:B5:AE:44”;

      char* ptr;
      broadcastAddress1[0] = strtol(str, &ptr, HEX );
      for( uint8_t i = 1; i < 6; i++ ) {
      broadcastAddress1[i] = strtol(ptr+1, &ptr, HEX );
      Serial.println(broadcastAddress1[i]);
      }

      // WiFi.mode(WIFI_STA);

      if (esp_now_init() != ESP_OK) {
      Serial.println(“Error initializing ESP-NOW”);
      return;
      }
      Serial.println(“WiFi chanel ndray:”);
      Serial.println(WiFi.channel());
      esp_now_register_send_cb(OnDataSent);

      // register peer
      esp_now_peer_info_t peerInfo;
      //peerInfo.channel = WiFi.channel();
      //peerInfo.ifidx=WIFI_IF_AP;
      peerInfo.channel = 1;
      peerInfo.encrypt = false;
      // register first peer
      memcpy(peerInfo.peer_addr, broadcastAddress1, 6);
      if (esp_now_add_peer(&peerInfo) != ESP_OK){
      Serial.println(“Failed to add peer”);
      return;
      }

      }
      void loop() {
      server.handleClient();
      test.x = random(0,20);
      test.y = random(0,20);

      //esp_err_t result = esp_now_send(0, (uint8_t *) &test, sizeof(test_struct));
      esp_err_t result = esp_now_send(broadcastAddress1, (uint8_t *) &test, sizeof(test_struct));

      /*
      test2.x2 = random(100,200);
      test2.y2 = random(100,200);

      esp_err_t result2 = esp_now_send(broadcastAddress2, (uint8_t *) &test2, sizeof(test_struct2));
      */

      if (result == ESP_OK) {
      Serial.println(“Sent with success”);
      }
      else {
      Serial.println(“Error sending the data”);
      }

      delay(1000);
      }

      void handleRoot(){
      if ( server.hasArg(“DEM”) ) {
      //mtrame = concat(String((int)vA0),”;”,String((int)vA1),”;”,String((int)mArr));
      if (server.arg(“DEM”).toInt()>=10) {
      /*
      svMarche = String((int)vMarche);
      svA0 = String((int)vA0);
      svA1 =String((int)vA1);
      svArr = String((int)mArr);
      svjoy1X =String((int)joy1X);
      mtrame = svA0 + “;” + svA1 + “;” + svArr + “;” + vMarche + “;” + svjoy1X;
      */
      str_mac = “F4:CF:A2:5B:AE:44”;
      Serial.println(“Départ:”);
      Serial.println(str_mac);

      mtrame = "MAHERY";
      //ESP.restart();
      setup();

      delay(5000);
      Serial.println("Arrivé:");
      Serial.println(str_mac);
      /*
      Serial.print("IA0: ");
      Serial.print(svA0);
      Serial.print(" IA1: ");
      Serial.print(svA1);
      Serial.print(" Arr: ");
      Serial.print(svArr);
      Serial.print(" Trame: ");
      Serial.println(mtrame);
      */
      server.send ( 200, "text/plain", mtrame );
      }

      }

      }

      Reply
  88. Hola Rui
    He iniciado a realizar tu proyecto, me dado de alta en bluehost he seguido las pasos wizard para crear un BBDD. El dominio ya lo tenia, es externo a bluehost (cascosta.gal)
    $dbname = “xxxxxxxx_LosaTermica” (nombre mi BBDD)
    $username = “xxxxxxxx_ESP32_board”;
    $password = “xxxxxxxxxxxxx”;

    Introduzco en el naveador la siguiente URL:
    http://LosaTermica-cascosta.gal/post-esp-data.php

    Y no funciona nada, donde esta el error

    GRACIAS

    Jesús

    Reply
  89. i have his error

    [D][HTTPClient.cpp:293] beginInternal(): protocol: http, host: ipmiez.com port: 80 url: /post-esp-data.php
    [D][HTTPClient.cpp:579] sendRequest(): request type: ‘POST’ redirCount: 0

    [D][HTTPClient.cpp:1125] connect(): connected to ipmiez.com:80
    [D][HTTPClient.cpp:1257] handleHeaderResponse(): code: 302
    [D][HTTPClient.cpp:1260] handleHeaderResponse(): size: 223
    [D][HTTPClient.cpp:603] sendRequest(): sendRequest code=302

    [D][HTTPClient.cpp:378] disconnect(): still data in buffer (223), clean up.

    [D][HTTPClient.cpp:385] disconnect(): tcp keep open for reuse

    Reply
  90. Hi, Sara. I’m working on a project in reference to this project of yours. Like a few others in the comment section, I have the error code : -1 for my HTTPresponse. I’m using XAMPP server for my project and I have tried changing the url between “https://…” and “http://”. I have also tried switching between using “localhost” and “127.0.0.1” in my url. Below is the error displayed in the serial monitor.

    httpRequestData: api_key=tPmAT5Ab3j7F9&parking_id=B05&distance=5.70
    Error code: -1

    Hope to get a quick feedback from you.

    Reply
    • Were you able to fix it?
      I have same problem, I have done all suggestions above
      I even created an html form on my laptop and i set the action to the page that will recieve data and it went successfully, but when i try it from the arduino ide i still get the -1 code

      Reply
  91. Hi Sara, – as always your tutorials are brilliant – many thanks.
    My problem is that my server time is 8 hours behind my ‘Europe/London’ time.
    Is it possible to add some code into the ‘esp-data.php’ file to set and format the correct zone and DST and insert that along with the ESP readings.
    Have tried but there are numerous php date/time functions and my knowledge is very limited.
    I’m currently using the arduino ‘time.h’ library and NTP but this takes about 30 seconds on startup and I wish to run the esp8266 in deepsleep mode on a solar/battery project where ‘up time’ is kept to minimum.
    Alternatively, I can create another ‘.php file to echo back the UTC time which is immediate. Can this value be used with the time library without the NTP call.
    Any other options would be appreciated.
    Kind Regards

    Reply
    • Hi.
      There are some lines on the esp-data.php file that show how you can adjust the time. You need to uncomment one of those lines.
      // 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”));
      Regards,
      Ara

      Reply
  92. Any chance someone has added a tipping bucket rain gauge to this script? I’d like to be able to count the bucket tips in the same time delay as the temp, pressure, humidity readings.

    It seems like a straight forward addition but I can’t make heads or tails of how to do it. I have a working version on raspberry pi but want to port to ESP32. Below is code from the raspberrypi weather station project from their site. It logs to a mariadb successfully.

    #!/usr/bin/python3
    import RPi.GPIO as GPIO
    import bme280
    import smbus2
    import time
    import database
    import datetime

    this many inches per bucket tip

    CALIBRATION = 0.01193

    which GPIO pin the gauge is connected to

    PIN = 27

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    variable to keep track of how much rain

    rain = 0

    the call back function for each bucket tip

    def cb(channel):
    global rain
    rain = rain + CALIBRATION

    register the call back for pin interrupts

    GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

    #for the bme280:
    port = 1
    address = 0x77
    bus = smbus2.SMBus(port)

    bme280.load_calibration_params(bus,address)

    db = database.weather_database()

    #display and log results
    while True:
    bme280_data = bme280.sample(bus,address)
    humidity = bme280_data.humidity
    pressure = (bme280_data.pressure *0.02953)
    ambient_temperature = (bme280_data.temperature * 1.8) +32
    x =datetime.datetime.now()

    print(humidity, pressure, ambient_temperature, rain, x)

    file.write(line + “\n”)

    file.flush()

    db.insert(ambient_temperature, 0, 0, pressure, humidity, 0, 0, 0, rain, x)
    rain = 0
    time.sleep(600)

    GPIO.cleanup()

    Reply
    • How do you get a signal from tipping bucket? Is it a reed switch?
      Suggest you don’t use GPIO27. That is ADC2 which may clash with wifi.
      Use pins 16 to 23

      Reply
      • Yes it’s a reed switch and I can swap it to another port. Just wondering how I can do both reed switch AND BME280 on ESP32 similar to the tutorial on this page…

        Reply
        • Before you change the Arduino IDE you will need to do the following:
          * add a column ‘value4’ in the mysql table to store the depth of rain – use same settings as value3
          * include value4 in ‘post-esp-data.php’ file (in 3 places)
          * include value4 in ‘esp-data.php’ file (in 3 places)

          ESP32 changes are straightforward. In order that you don’t miss any bucket tips I’ve used an ‘interrupt’

          //insert before void setup()
          int rainPin=23; //GPIO pin for tipping bucket reed switch – you can change it
          float bucketTip=0; //tip counter
          float depthPerTip=???; //put your factor (eg each tip of mine is 0.19 mm)
          float rainTotal=0; //calculated volume of rain in sampling period

          void IRAM_ATTR detectRain() { //interrupt function
          bucketTip++;
          }

          //insert in void setup() section
          pinMode(rainPin, INPUT);
          attachInterrupt(digitalPinToInterrupt(rainPin), detectRain, FALLING ) ;

          //insert at start of void loop() section
          rainTotal=bucketTip*depthPerTip; // calculate depth of rain
          bucketTip=0; // reset counter

          at the end of the line starting ‘String httpRequestData’ add &value4 details – follow &value3 syntax but with String(rainTotal) – ensure the double quotes are at the end

          Thats it ….I think
          Bob

          Reply
  93. You can try adding a short delay as shown below though it’s considered to be bad practice.
    change:
    void IRAM_ATTR detectRain() { //interrupt function
    bucketTip++;
    }
    to:
    void IRAM_ATTR detectRain() { //interrupt function
    bucketTip++;
    delay(50);
    }

    Better still – do as I did and use a SS443A digital ‘hall effect’ device which doesn’t seem to have any bounce. Really simple – 3 pins: +5v, GND, and data out to your GPIO – no library or change in coding and cheap. Just a 10k resistor between 5v and data pins

    Reply
  94. Well, shoot. I only thought I was done.
    I had this counting button presses but changing to a reed switch it doesn’t detect the magnet passing over.
    I’ve added an LED on one side of the reed so I can see it light when I wave the magnet over but the code doesn’t count it.
    I’ve tried wiring it a few ways, power – reed – pin23, ground – reed – pin23 and now:
    3.3v & pin23 on one side – reed – LED & 1k resistor to the other end.
    Thinking it is probably the wiring? I’ve also tried the 5v power

    Here’s the code:
    /*
    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 = “SSID”;
    const char* password = “password”;

    // REPLACE with your Domain name and URL path or IP address with path
    const char* serverName = “http://ServerIP/weather/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 = “APIKey”;

    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

    //insert before void setup()
    int rainPin=23; //GPIO pin for tipping bucket reed switch – you can change it
    float bucketTip=0; //tip counter
    float depthPerTip = 1; //put your factor (eg each tip of mine is 0.19 mm)
    float rainTotal=0; //calculated volume of rain in sampling period

    void IRAM_ATTR detectRain() { //interrupt function
    bucketTip++;
    //delay(15);
    }

    void setup() {
    Serial.begin(9600);

    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());

    //insert in void setup() section
    pinMode(rainPin, INPUT);
    attachInterrupt(digitalPinToInterrupt(rainPin), detectRain, FALLING);

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

    void loop() {
    //insert at start of void loop() section
    rainTotal=bucketTip*depthPerTip; // calculate depth of rain
    bucketTip=0; // reset counter

    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;

    // Your Domain name with URL path or IP address with path
    http.begin(client, 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() *1.8 +32)
    + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0 *0.02953)
    + "&value4=" + String(rainTotal) + "";
    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 10 minutes
    delay(5000);
    }

    Reply
    • Don’t have reed switch so can’t test.
      Try changing ‘FALLING’ in the interrupt statement to one of the following and see if any works. Also try pulling the pin low with 10k resistor – worth a try. Would recommend the Hall effect device. Mine has worked fine for months.

      LOW Triggers interrupt whenever the pin is LOW
      HIGH Triggers interrupt whenever the pin is HIGH
      CHANGE Triggers interrupt whenever the pin changes value, from HIGH to LOW or LOW to HIGH
      FALLING Triggers interrupt when the pin goes from HIGH to LOW
      RISING Triggers interrupt when the pin goes from LOW to HIGH

      Reply
  95. Getting a Http: 400 error response, I have fixed this error by turning off “Force everyone to use HTTPS” option in bluehost. However, is there an updated version of this designed for https? I know having encrypted data to post on the webserver isn’t important for posting weather data. However, digging into the whole SSL certificates for devices. Buying and entering the cert file seems expensive for every single widget like this. How can you automatically update the fingerprint when your websites fingerprint changes?

    Reply
  96. How can I modify this project so that instead of the ESP32/ESP8266 devices inserting data into MySQL database, I use a GPRS data logger that sends csv data at user programmable intervals.

    In the data logger, I just configure server IP address, port number and data upload interval.

    Regards.

    Reply
  97. Two weeks ago I had never heard of an ESP32, nor anything about creating a cloud-based database.

    Tonight I got one logging to an online database in my domain (I didn’t even know I had one, but learnt it came with my family email addresses).

    What a fantastic discovery and what fantastic intro from this forum.

    Much appreciated!

    Reply
  98. Hello,
    I seem to have quite a unique problem. I get HTTP: 200, but data doesn’t get written into database.
    I get readings from my sensor and I can see them in serial monitor, but they don’t get written into database. How would one fix such an issue?

    Reply
    • It seems I miswrote a part. I get HTTP Response Code: 200 only first time it runs, after that I start getting error:-1.

      Reply
  99. Hi Sara,
    I’m using your POST and GET procedures to save and retrieve weather data and all works fine. Very grateful for your tutorials.
    But now I want to send a daily maintainance instruction from the ESP32 to remove any data older than 12 months.
    Have installed the php instruction on my web hosting site and it will work OK when called from a browser (eg. something like: http://myServer.com/cleanUp.php).
    But how can I run it from an ESP sketch? – it is neither a GET or POST but an instruction.
    Any help would be appreciated

    Below is the relevant part of the cleanUp.php file.

    //php coding extract——————————————
    $conn = new mysqli($servername, $username, $password, $dbname);
    //Check connection
    if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
    }

    $sql = "DELETE FROM my_table WHERE reading_time <= (NOW() - INTERVAL 12 month)";
    if ($conn->query($sql) === TRUE) {
    echo "Old records removed";
    }
    else {
    echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();

    Reply
  100. Hi l am having a problem updating my online MySQL database. I have a online web server. I keep getting http response 301. I can ping the server it seems to connect but no data is uploaded. All steps in tutorial have been copied and pasted.
    All scripts seem to work, l have tried https, still failed to update 301 error. Not sure what to try next.
    Any suggestions would be great.
    Thanks Bruce

    Reply
  101. Hi Sara and Rui,

    I try to send data from a NodeMCU to my webserver running on a RaspberryPi. It works so far, but the server anwers with 401 unauthorized. Thats correct, because my webserver needs username/password.

    http.begin(client, serverName);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    String httpRequestData = “&data=test”;
    int httpResponseCode = http.POST(httpRequestData);
    Serial.print(“HTTP Response code: “);
    Serial.println(httpResponseCode);

    How can I send username/password in this request? I could not find anything to this matter.

    Thanks a lot.
    Regards, Hajo.

    Reply
  102. Your work here is amazing! Knowing zero about PHP, C++, Visual Studio, PlatformIO, hosting Web Sites, (The list goes on and on), I was able to clone/ modify your software to monitor the 3 batteries and capture temperature and humidity on my boat. I’m using an iPhone 8 as a hotspot to keep everything connected to the internet. The UI is great and it works flawlessly. Now I’m in the process of adding the ability to start my generator remotely. I’m leveraging/ modifying this project code and I was running into an issue getting a return code of 200 even though no data is posted to my database. I was able to resolve the issue by changing ($_SERVER[“REQUEST_METHOD”] == “POST”) to ($_SERVER[“REQUEST_METHOD”] != “POST”). So obviously the REQUEST_METHOD is not equal to POST and I would ask, where does a rookie like me learn how REQUEST_METHOD is set in the code from an ESP32. I have studied the code and done multiple internet searches and haven’t found the magic. Any feedback is appreciated. Again, what you have put together is outstanding!

    Reply
  103. I am getting an error message on compiling:
    /Users/normandallura/Documents/Arduino/Kiln_Monitor_to_Database_WiFi/Kiln_Monitor_to_Database_WiFi.ino: In function ‘void POSTPage()’:
    Kiln_Monitor_to_Database_WiFi:151:16: error: no matching function for call to ‘HttpClient::HttpClient()’
    HttpClient http;
    ^~~~
    In file included from /Users/normandallura/Documents/Arduino/Kiln_Monitor_to_Database_WiFi/Kiln_Monitor_to_Database_WiFi.ino:8:0:
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:50:5: note: candidate: HttpClient::HttpClient(arduino::Client&)
    HttpClient(Client& aClient);
    ^~~~~~~~~~
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:50:5: note: candidate expects 1 argument, 0 provided
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:37:7: note: candidate: constexpr HttpClient::HttpClient(const HttpClient&)
    class HttpClient : public Client
    ^~~~~~~~~~
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:37:7: note: candidate expects 1 argument, 0 provided
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:37:7: note: candidate: constexpr HttpClient::HttpClient(HttpClient&&)
    /Users/normandallura/Documents/Arduino/libraries/HttpClient/HttpClient.h:37:7: note: candidate expects 1 argument, 0 provided
    Kiln_Monitor_to_Database_WiFi:154:10: error: ‘class HttpClient’ has no member named ‘begin’
    http.begin(client, serverName);
    ^~~~~
    Kiln_Monitor_to_Database_WiFi:157:10: error: ‘class HttpClient’ has no member named ‘addHeader’; did you mean ‘sendHeader’?
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    ^~~~~~~~~
    sendHeader
    Multiple libraries were found for “HttpClient.h”
    Used: /Users/normandallura/Documents/Arduino/libraries/HttpClient
    Not used: /Applications/Arduino.app/Contents/Java/libraries/Bridge
    exit status 1
    no matching function for call to ‘HttpClient::HttpClient()’

    I have the library installed:
    #include <SPI.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <DHT.h>
    #include <WiFiNINA.h>
    #include <EMailSender.h>
    #include <HttpClient.h>

    and I get the error here on the HttpClient http; line:
    if (WiFi.status() == WL_CONNECTED) {
    WiFiClient client;
    HttpClient http;

    I’m stuck

    Reply
  104. Love the site, guides are very useful!!

    I have a question for anybody here that would like to answer.
    I’m not a programmer by any means, but would like to add a Temperature (°F) column and a pressure column that reads in inHg instead of hPa. Let me further clarify this, I’ve added the columns successfully but not sure were the calculation would go to do the conversion.

    Any help would be appreciated

    Reply
  105. I posted this earlier but i never saw it appear or get answered.

    I don’t need to store the data, but is it possible to create a Fahrenheit column and a inHg column.

    I;m not a programmer unfortunately. Even a link to another page that shows how to do it would be useful.

    Reply
    • you change the &value1= portion of the loop() portion of the code. like so:

      / Prepare your HTTP POST request data
      String httpRequestData = “api_key=” + apiKeyValue + “&sensor=” + sensorName
      + “&location=” + sensorLocation + “&value1=” + String(bme.readTemperature() *1.8 +32)

      Reply
      • Good morning Henk,

        Thank you for the response.

        I’ll try this tonight when I get home, unfortunately I left the ESP home today.

        Mark

        Reply
  106. Hello Sara,

    How can I display to the webpage the latest readings only? Only the Values and Timestamp will change on every refresh if there’s a latest readings. Can it be done?

    Thanks in advance,
    Sophy

    Reply
  107. Hello
    Thanks for the tutorial corresponding to my needs. But…
    I have installed a local server XAMPP and created the corresponding php files.
    I have loaded the ESP32 with the code but when running I have the httpResponseCode = -1 in the arduino console.
    Any ideas?

    Reply
  108. sorry but can you maybe explain the if ($_SERVER[“REQUEST_METHOD”] == “POST”) loop or do you have any in depth guides for this?

    Reply
  109. thank you for your cods .
    i tried them but it doesnt work for me , i get this error at serial monitor :
    17:16:44.635 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=DHT11&location=Office&value1=26.50&value2=18.00
    17:16:47.989 -> HTTP Response code: 302
    17:17:18.020 -> rotubat = 18.00
    17:17:18.020 -> dama = 26.50
    17:17:20.030 -> httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=DHT11&location=Office&value1=26.50&value2=18.00
    17:17:25.520 -> Error code: -11
    i will thanks full if you help me.

    Reply
  110. Good job on the tutorial. It was well written and easy to follow.

    However, I have run into a snag. When I send to post-esp-data.php, the variables get lost.
    I get the “Wrong API Key provided.” error message, and when I try to use the echo command to check the value of api_key, it shows as blank as do all the other variables.

    I tried using PostMan to send the sample test string from the code and got the same result.
    Any clues?

    Reply
    • I found a solution.
      Looking at a variety of other people’s code, I found one that used the construct:

      $value1 = test_input($_REQUEST[‘value1’]);
      rather than
      $value1 = test_input($_POST[‘value1’]);

      Making the change solved the problem

      Reply
  111. Hello, this tutorial is great ! Thank you very much !
    I tried to send data in the json format following the suggestion to comment and uncomment the related lines of the ESP code; in the serial monitor I get a reply code 200, but neither the data are stored in the database nor the webpage shows them. I have moreover added the fields of “api_key” and “sensor” in the json object in this way:
    int httpResponseCode = http.POST(“{\”api_key\”:\”tPmAT5Ab3j7F9\”,\”sensor\”:\”BME280\”,\”value1\”:\”24.25\”,\”value2\”:\”49.54\”,\”value3\”:\”1005.14\”}”);
    with no success.
    Could you help ?
    Thank you in advance !
    Regards

    Reply
  112. I have been using this code successfully for a couple months (late Nov to mid January) and all of a sudden in the middle of the night it stopped logging data into the database.

    I have two separate ESP32’s, each with it’s own BME280.

    Anything to check, I have a hard time believing both 32’s died at the exact same time.

    I have another new in the anti static bag to load the sketch into if I have to.

    Reply
    • Hi.
      Maybe there’s an issue with the database and not with the boards…
      Have you checked if anything changed with the database?
      Regards,
      Sara

      Reply
      • I’m not sure, I have thought about that.
        About a month ago, I went in and manually was able to enter data via the phpmyadmin.

        I don’t have any other web site that enters data for me. I’ve sent a ticket over to the hosting support group to ask if anything has changed on their side since January.

        Mark

        Reply
        • What message did you get sent back to the Serial monitor from PHP file?
          It should say: ‘New record created successfully’.

          If it doesn’t then suggest you check all field names match exactly in both PHP and MYSQL.

          Bob

          Reply
          • Hi Bob,

            Thank you for the suggestion/idea. I don’t know.

            I programmed them and put them standalone in a room and that is were they have been sitting.

            When i get home tonight I will plug one of them into my laptop and see if I can get any output on the serial monitor.

            Mark

          • Hi Bob,

            I did what you suggested last night.

            Initially serial monitor was reporting back:
            “HTTP: Response code 301”

            I looked up on the net what might be causing it and changed the web site address it was going to from http to https. the 301 code went away but then started giving the same output but with a 400 code.

            Looked that up, but couldn’t make heads or tails what to look at in the code to fix it…..any ideas?

          • Suggest you stick with http. Good news is that the message is reaching the Php file.
            Looks like a mismatch of field names from Php to MySQL. Check spelling carefully in the Php file the column names of the table and you are not trying to send column data which isn’t in the table. Remember it’s all case sensitive.
            You might want to serial.print the message being sent to Php file and carefully check the names with the Php file. If you want to strip out your personal data from the Php and PM rest to me I can cast an eye if you want.

          • Hi Bob,

            It all looks good to me, but i might still be missing something since I’ve been looking at it a bunch these last couple nights.

            I have both PHP files and the Ardunio code that I can send to you. How do you PM here? Or is there a better way? (ie email) to have you take a quick peak?

            Thank you for your assistance also!!

            Mark

  113. Let me check tonight what you have suggested.
    I don’t think anything has changed but i could be wrong. I am at times LOL.

    It is just strange that it was working fine when i went to bed and woke up to it having stopped in the middle of the night.

    I will be in touch with the results later.

    Mark

    Reply
  114. Hola buenos dias
    Primero gracias por el tremendo esfuerzo y las horas de trabajo que significa este subir este articulo. Muy bueno, muy bien explicado y sencillamente util.
    Personalmente siempre he huido de Arduino, entiendo que es muy útil dado que simplifica los trabajos pero limita las posibilidades y deja poco espacio para el desarrollo de la tecnología electrónica, que es lo que me gusta a mi. Prefiero cacharrear con un microcontrolador y un diseño que comprarme un par de placas y bajarme un .iso de copia y pega
    Pero gracias por el esfuerzo me ha ayudado mucho y si claro, te invito a café y croissant.
    Por eso para cuando un articulo de envió de datos por GPRS a una IP/base de datos?
    Saludos y gracias por todo
    Antonio

    Reply
  115. I have been using bluehost to host my database and files for 2 years. I have logged over 5 million temperature readings. I have somehow managed to break my code. It does not seem to be establishing the connection to post to the database. I have had bluehost try to help me several times including rebuilding my files from a backup. The people at bluehost tell me that they only support wordpress, and can’t help me. I am willing to pay someone for freelance work to go over the software with me, can you recommend someone?

    Reply
      • Have them update your php software. I had the same problem with hostmonster (they are owned by the same company btw).

        Tech support was absolutly useless and after i raised enough of a stink, they did the upgrade and it has been working again for me.

        Reply
  116. very good tutorial.thank you so much!
    as many users , im facing a -1 error after say 40 uploads to the database.
    after a while the esp32 reset itself and start uploading again and get stuck after same uploads amount.again and again.
    im using a free database 000webhost, but think that the issue is local to the esp itself (not sure).
    wich tools can be used locally and then allow serial print to facilitate the debbuging ?
    otherwise , as proposed wich is the best way to affect the job to a different core of the esp32.
    summarizing this , can be a great improvement to all of the fellows here.
    Thank you in advance , and congratulations for such a great site.

    Reply
  117. very nice… I need to try it…
    I’ve found this project when I’ve googled for an idea how to enter data from a BarCode reader into Alexa’s shopping list. So the product data should be found in the net based on the BarCode… any idea how the interface to alexa could look like. I would also use a ESP32 to read the sensor data and lookup the product information….
    Thanks

    Reply
  118. After reading all the comments to see if there was already a solution to my problem, I’m going to give it a shot here by asking:

    I followed your tutorial, except the part where we do the php script to post the database contents to a website. This is because I am not interested in this step for the moment, since all I want to do is to scan something and store the scanned data in a databse.

    I am using an ESP32. I also downloaded XAMPP which comes with an Apache Server and a phpMyAdmin. Over there I used the SQL query you provided to create the table within the database. In the Arduino code provided, I removed the libraries for the sensor you provided and I only used the line of code that you provided as an example, since I don’t have the sensor and I only want to see if this works for me so I can modify the code to scan the parameters I need.

    However, I am getting this error code:

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

    As server name I have used:

    localhost
    localhost:80
    My PC’s IP address
    127.0.0.1
    localhost with the path for the php script to post
    And many more

    Unfortunately, the table in my database stays empty. What could be causing the error? I could post the code I have if necessary.

    Thank you beforehand.

    Reply
      • The server is my own computer. I am using Apache Web Server, this is the one that comes with XAMPP. I looked into the configuration files and the serverName is listed as “localhost:80”. If I type “localhost:80” in my browser I get redirected to a website named “Welcome to XAMPP”.

        Any ideas?

        Thank you for your time.

        Reply
  119. You need the php file. That is the link between Arduino and mysql.
    OR
    You could save direct to ‘Thingspeak’ from Arduino but its not mysql
    Bob

    Reply
  120. I greet all. I am from Slovakia. This is an amazing project and thanks for sharing this project with other people. I would like to ask if this project can be used locally. I have a synology server and I have hosting and a mysql database running on it. I can’t run docker on my NAS. I thought this could be the solution. Will this project work locally with my server? Thank you very much for your reply and I wish you all the best. I apologize for my poor English.

    Reply
    • Hi.
      Yes. I think so. As long as you have MySQL and PHP installed on your server.
      Then, you just need to use the IP address of your server instead of the server URL.
      Regards,
      Sara

      Reply
  121. Hi everyone, I have a problem similar Mr Eduardo J.I above, hope someone could help me.
    I too getting httpResponseCode = -1, what does this error mean?
    I used ngrok to host the website on my laptop,
    if I type “https://mature-renewing-crane.ngrok-free.app/Example/trash_record.php?binID=1&fill_level=23”, I still get the to my phpmyadmin server.
    I assume that there is some problem in the connecting part.

    If I try the part:
    https.addHeader(“Content-Type”, “text/plain”);
    int httpResponseCode = https.POST(“Hello, World!”);
    It still error -1

    Reply
  122. To everyone having the Error -1, this is what happened to me and how I solved it. It might help you too.

    According to the source code of the HTTPClient.h package, the -1 error is a connection refused by the server. I then checked the access requests on my server (which I run locally), and could see that it was resulting in a bad request (error 400). After a lot of digging, I found the culprit in my case: the WiFiClientSecure package.

    I could make the code work by commenting the follwing lines:
    //WiFiClientSecure *client = new WiFiClientSecure;
    //client->setInsecure(); //don’t use SSL certificate

    and removing the *client from the https.post:
    int httpResponseCode = https.POST(httpRequestData);

    WARNING: this might make your code less secure, do it at your own risk.

    Reply
  123. Thank you so much for amazing tutorials.

    For those getting “-1” error, may I suggest that to ensure,
    int httpResponseCode = https.POST or https.GET,
    to be placed after http.begin.

    Reply
  124. Another solution, if you have this error is to place the client definition before the setup function. Like this:

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

    WiFiClientSecure *client = new WiFiClientSecure;

    void setup() {

    Reply
    • I too have the Error return code of -1

      I included this additional code to track the heap at the end of loop ()
      …….
      } else {
      Serial.println(” > WiFi Disconnected”);
      }
      Serial.printf(” Memory: Stack:%d, Heap:%lu\n”, uxTaskGetStackHighWaterMark(NULL), (unsigned long)ESP.getFreeHeap());
      ……

      I have been trying to trace the serror for days and have even created an account on 000webhosting to see if was a server problem. It isn’t.

      Today, for the first time, I could see one extremely useful error message. Here is the output from the serial monitor showing the moment the error occurs:

      15:43:27.655 -> api_key=tPmAT5Ab3j7F9&sensor=ESP32-C Test Data&location=24AA&value1=91.17&value2=39.62&value3=83.60&value4=84.93&value5=16.62&value6=14.05
      15:43:29.594 -> > HTTP Response code: 200 OK
      15:43:29.594 ->
      15:43:29.594 -> Stack:4736,Heap:56148
      15:44:29.598 ->
      15:44:29.598 -> HTTPS: POST DATA REQUEST
      15:44:29.598 -> httpRequestData:
      15:44:29.598 ->
      15:44:29.598 -> api_key=tPmAT5Ab3j7F9&sensor=ESP32-C Test Data&location=24AA&value1=19.79&value2=38.00&value3=66.90&value4=95.82&value5=15.98&value6=20.10
      15:44:30.005 -> E (4603325) esp-sha: Failed to allocate buf memory
      15:44:30.005 -> > HTTP Error code: -1

      I have tried moving the line “WiFiClientSecure *client = new WiFiClientSecure;” before but with other surrounding code, without success, but never the single line of code.

      I shall try this next to see if the issue is resolved. It needs fixing otherwise the project becomes unusable.
      Cheers,
      Ric

      Reply
      • I can confirm this fix is successful for me on two different web servers and on two different esp32 boards. Although the heap value changes over time it often returns to it’s starting value – and does so over a 24 hour period. there is no evidence of a memory leak.

        Perhaps Rui might review the proposed code change and edit the tutorial?
        Ric

        Reply
        • Hi Ric, I am experiencing the same issue.
          On one instance the serial monitor provided a hint:
          “E (1887635) esp-sha: Failed to allocate buf memory”
          I added the snippet of code you provided that monitors Memory and Heap.
          The Heap started at 277112 and gradually declines with each post.
          When it gets to 48280 it then starts to generate a Error code: -1 and
          E (522970) esp-sha: Failed to allocate buf memory

          I’m not clear on what the fix was you referred to above.

          Reply
  125. Hi Sara,
    Great tutorial !
    What would you recommend on how to transfer the data stored in the database to a web page
    displaying a chart of the data? I am unfamiliar with scripting or css coding. Can you point me
    to a tutorial on how to do this, or do you already have an example I could follow?

    Thanks for all you do!
    Joel

    Reply
  126. Hello Random Nerds,
    I have a very basic question as I like to change and debug for my purpose you post-esp-data.php
    There are several echo statements used in this script (eg echo “Wrong API Key provided.”;). Where do can you see such Message. I mean are they written in the log files or on the serial output.
    Sorry to bother you with such basic question but I can not find the answer.

    Reply
    • Hi.
      In our example, we use a sample API key, in case our readers want to set up an API key.
      In the example, we’re using the tPmAT5Ab3j7F9 API key throughout the example.
      If you’re using a different one, made up by you, make sure you use the same in all codes.
      Regards,
      Sara

      Reply
    • I suspect you are asking where the echo messages appear.
      The answer is they are sent back to the ESP32 so you can print them to the Serial Monitor.

      Reply
  127. Hi there,

    Hi Rui – these are the best tutorials and everything I have is here. I’ve build a self carwash with Arduino AtMEGA2560 and my dad did the hydro part and pumps.

    On this 2nd variant i want to use ESP32 to send certain data to the database and read them in my php. I’ve built the pages and this part is left. Sending data from ESP32 to the database.

    Althogh, I’m trying to debug my code and can’t find why I am receiveing error code -5.

    Any suggestions what to check?

    Reply
  128. Hello
    I did all the steps with the profreehost provider and the asp8266 module and changed the HTTPS to HTTP in the URL, but I still get error-1.
    Even I changed all the HTTPS in code like (https.begin, https.addHeader, …) to HTTP, but still get error -1.
    Can you help?

    Reply
  129. Good morning Rui and Sara I’m using esp32 with bme280 which also gives me altitude, but when I go to write the altitude field the value corresponds to this:

    Data: b”\xf0\xaa\xfc?\xac:\xfc?’\xe3\xc8\xa5\x807\xfc?|<\xfc?\x847\xfc?\x01″

    Could you kindly help me decode the altitude field correctly so that I can insert it correctly into the MYSQL db.
    Thanks for existing
    Best regards

    Reply
  130. After 63 accepted connections, 63 successful submissions, it declines all the others. Almost always 63 connections accepted and data sent and the next ones are always refused. Regardless of the time between connections.
    I tested it on two servers. The second is a VPS. I hired a VPS (Virtual Private Server) server for a short period of time to do more tests with Esp32, being able to change some configuration values in msql.
    Even modifying some parameters in the mysql of the VPS, maximum limits for example. The result was the same: after 63 posts error returns (-1), only by restart the post again, 63 succeeded. That is, he refused to connect after 63. Always between 63 most of the time and once in a while 62. So fixed values, not random. And it doesn’t matter how long it takes between posts/sends, 3 seconds, ten seconds, 30 seconds, or 60 seconds loop. And it doesn’t matter if the program I made or the demo program. The result is always: it accepts 63 connections, from there to the rejection and the looks like -1

    Reply
    • Hi! Can I use WiFiClientSecure client instead of WiFiClientSecure *client = new WiFiClientSecure ? Could there be a problem?
      for example:
      // WiFiClientSecure *client = new WiFiClientSecure;
      WiFiClientSecure client;
      // *client->setInsecure(); //don’t use SSL certificate
      client.setInsecure(); //don’t use SSL certificate
      HTTPClient https;
      Apparently it works fine.

      Reply

Leave a Reply to Glück Gábor Cancel reply

Download Our Free eBooks and Resources

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