Visualize Your Sensor Readings from Anywhere in the World (ESP32/ESP8266 + MySQL + PHP)

In this project, you’ll create a web page that displays sensor readings in a plot that you can access from anywhere in the world. In summary, you’ll build an ESP32 or ESP8266 client that makes a request to a PHP script to publish sensor readings in a MySQL database.

ESP32 ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE - Visualize Your Sensor Readings from Anywhere in the World

Updated on 26 March 2023

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

To create 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 database and display it on a web page
  • MySQL database to store readings
  • PHP script to plot data from database in charts

You might also find helpful reading these projects:

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 – Visualize Database Content in a Chart
  5. Setting up the ESP32 or ESP8266

Watch the Video Demonstration

To see how the project works, you can watch the following video demonstration:

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 of the project:

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

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

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

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

Get Hosting and Domain Name with Bluehost »

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

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

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

2. Preparing Your MySQL Database

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

Creating a database and user

Open the “Advanced” tab:

Bluehost Advanced tab

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 Sensor (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    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 Sensor Table

After that, you should see your newly created table called Sensor 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 receives incoming requests from the ESP32 or ESP8266 and inserts 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 with File Manager

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

ESP32 ESP8266 CPanel Create New PHP File using File Manager

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-data.php

PHP Create New file post data .php

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

<?php
/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com
  
  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 = $value1 = $value2 = $value3 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $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 Sensor (value1, value2, value3)
        VALUES ('" . $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 message:

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

4. PHP Script – Visualize Database Content in a Chart

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

PHP Create New file esp chart data .php

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

<!--
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com
  
  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.

-->
<?php

$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, value1, value2, value3, reading_time FROM Sensor order by reading_time desc limit 40";

$result = $conn->query($sql);

while ($data = $result->fetch_assoc()){
    $sensor_data[] = $data;
}

$readings_time = array_column($sensor_data, 'reading_time');

// ******* Uncomment to convert readings time array to your timezone ********
/*$i = 0;
foreach ($readings_time as $reading){
    // Uncomment to set timezone to - 1 hour (you can change 1 to any number)
    $readings_time[$i] = date("Y-m-d H:i:s", strtotime("$reading - 1 hours"));
    // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
    //$readings_time[$i] = date("Y-m-d H:i:s", strtotime("$reading + 4 hours"));
    $i += 1;
}*/

$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$value2 = json_encode(array_reverse(array_column($sensor_data, 'value2')), JSON_NUMERIC_CHECK);
$value3 = json_encode(array_reverse(array_column($sensor_data, 'value3')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);

/*echo $value1;
echo $value2;
echo $value3;
echo $reading_time;*/

$result->free();
$conn->close();
?>

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <style>
    body {
      min-width: 310px;
    	max-width: 1280px;
    	height: 500px;
      margin: 0 auto;
    }
    h2 {
      font-family: Arial;
      font-size: 2.5rem;
      text-align: center;
    }
  </style>
  <body>
    <h2>ESP Weather Station</h2>
    <div id="chart-temperature" class="container"></div>
    <div id="chart-humidity" class="container"></div>
    <div id="chart-pressure" class="container"></div>
<script>

var value1 = <?php echo $value1; ?>;
var value2 = <?php echo $value2; ?>;
var value3 = <?php echo $value3; ?>;
var reading_time = <?php echo $reading_time; ?>;

var chartT = new Highcharts.Chart({
  chart:{ renderTo : 'chart-temperature' },
  title: { text: 'BME280 Temperature' },
  series: [{
    showInLegend: false,
    data: value1
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    },
    series: { color: '#059e8a' }
  },
  xAxis: { 
    type: 'datetime',
    categories: reading_time
  },
  yAxis: {
    title: { text: 'Temperature (Celsius)' }
    //title: { text: 'Temperature (Fahrenheit)' }
  },
  credits: { enabled: false }
});

var chartH = new Highcharts.Chart({
  chart:{ renderTo:'chart-humidity' },
  title: { text: 'BME280 Humidity' },
  series: [{
    showInLegend: false,
    data: value2
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    }
  },
  xAxis: {
    type: 'datetime',
    //dateTimeLabelFormats: { second: '%H:%M:%S' },
    categories: reading_time
  },
  yAxis: {
    title: { text: 'Humidity (%)' }
  },
  credits: { enabled: false }
});


var chartP = new Highcharts.Chart({
  chart:{ renderTo:'chart-pressure' },
  title: { text: 'BME280 Pressure' },
  series: [{
    showInLegend: false,
    data: value3
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    },
    series: { color: '#18009c' }
  },
  xAxis: {
    type: 'datetime',
    categories: reading_time
  },
  yAxis: {
    title: { text: 'Pressure (hPa)' }
  },
  credits: { enabled: false }
});

</script>
</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.com/esp-chart.php
ESP32 ESP8266 Test ESP Data PHP URL

That’s it! If you see three empty charts in your browser, it means that everything is ready. In the next section, you’ll learn how to publish your ESP32 or ESP8266 sensor readings.

To build the charts, we’ll use the Highcharts library. We’ll create three charts: temperature, humidity and pressure over time. The charts display a maximum of 40 data points, and a new reading is added every 30 seconds, but you change these values in your code.

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.

ESP32 vs ESP8266 Development Boards

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 I2C wiring to ESP32 - circuit schematic diagram SDA SCL

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 I2C wiring to ESP8266 - circuit schematic diagram SDA SCL

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

/*#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 + "&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.com/post-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.

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);
  • 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(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 + "&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&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-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";

/*#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 + "&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.com/post-data.php";

Now, you can upload the code to your board.

rnt_box type=”3″] 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 Temperature Humidity and Pressure sensor publishing readings using Arduino IDE, MySQL, and PHP

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.com/esp-chart.php

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

ESP32 ESP8266 View BME280 Sensor Readings (Temperature, Humidity, and Pressure) using PHPMyAdmin and SQL Database

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

ESP32 ESP8266 View Sensor Readings PHPMyAdmin SQL Database

Wrapping Up

In this tutorial, you 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 also use a Raspberry Pi for local access).

With this setup, you control your server and can move to a different host if necessary. There are many cloud solutions both free and paid that you can use to publish your readings, but those services can have several disadvantages: restrictions on how many readings you can publish, the number of connected devices, who can see your data, etc. Additionally, the cloud service can be discontinued or change at any time.

The example provided is as simple as possible so that you can understand how everything works. After understanding this example, you may change the web page appearance, 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 »

Enjoyed this project? Stay updated by subscribing our newsletter!

215 thoughts on “Visualize Your Sensor Readings from Anywhere in the World (ESP32/ESP8266 + MySQL + PHP)”

  1. do you have example that use input data from web server save to database, and from data base, we use data to control machine, for exemple if user input 1(led 1 on), input 2 led 2 on) and 3 to turn off led

    Reply
  2. I’m glad to read about the possibility to use Raspberry Pi instead of a server. Do you have additional information to do so?
    Friedhelm

    Reply
    • You can definitely do it. Search for “PHP + MySQL” on Mac OS X and you’ll find plenty of tutorials on that subject.
      Note: with that setup data will be stored locally (not from anywhere in the world).

      Reply
  3. Hi, When i execute from my FileManager the file esp-chart.php visualize the following lines:

    Notice: Undefined variable: sensor_data in /storage/ssd3/152/2515152/public_html/esp-chart.php on line 38

    From Monitor Arduino I view following:

    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14
    HTTP Response code: 200

    But my database ‘sensor’ don’t update and HTTP response is 200.

    When execute post-data.php in my screen view is the following:
    No data posted with HTTP POST.

    When I view the structure the ‘sensor’ database ,I view following:

    # Name Type Collation Attributes Null Default Comments Extra Action
    1 idPrimary int(6) UNSIGNED No None AUTO_INCREMENT Change Change Drop Drop
    More More
    2 value1 varchar(10) utf8_unicode_ci Yes NULL Change Change Drop Drop
    More More
    3 value2 varchar(10) utf8_unicode_ci Yes NULL Change Change Drop Drop
    More More
    4 value3 varchar(10) utf8_unicode_ci Yes NULL Change Change Drop Drop
    More More
    5 reading_time timestamp No current_timestamp() ON UPDATE CURRENT_TIMESTAMP() Change Change Drop Drop
    More More

    What happens with in this case?

    Thanks you

    Reply
      • No, unfortunately only the following appears when I run esp-data.php:
        ID Sensor Location Value 1 Value 2 Value 3 Timestamp

        Please, view the following link:

        qpower.000webhostapp.com/esp-data.php

        Reply
          • Hello Rui:
            From Monitor Arduino I view following:

            httpRequestData: api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14
            HTTP Response code: 200

            But my database ‘sensor’ don’t update and HTTP response is 200.

            Is it possible to have some kind of return from the database if it recorded well or not?
            Thanks for helping

          • I’m honestly not sure why that happens… I can only imagine some small error in the post-data.php script (like wrong credentials) that can’t insert data in your Sensor table…

          • I had a problem posting to the database.

            I solved it by noting the URL of the SQL server as indicated in phpMyAdmin and I changed the $servername value from ‘localhost’.

            Thank you Santos’ for this tutorial.

  4. I’m a fan of you guys. You are doing a wonderful job. This tutorial is but one of your great efforts. I appreciate it.
    Please is it possible to make this same platform used in this tutorial to control appliances from anywhere in the world? Thanks for your reply.

    Reply
    • It’s definitely possible, but it’s a bit tricky. I’ll probably create that tutorial too in a couple of weeks.

      Right now I don’t have any tutorial on that subject.

      Reply
      • Stunningly good example, like all your others 😊
        I just wanted to add in that if things don’t work immediately as was the case with mine, try talking to your isp internet service provider.
        I put this in my existing site and just couldn’t push data from sensor to database. I KEPT GETTING A FAILURE 301 Redirect Status
        It turned out my isp had as Default a redirect in place. They commented that out and data started to appear in the database, but, not on the page.

        More talking and it turned out this was a question of cache.

        With super cache turned off I now get live data… After refresh…

        I now want to find out what I need to do to have an auto-refresh as data arrives.

        As I say, just my experience, but it may help someone.

        Keep up the great work guys. I have been through my course twice now and feel quite empowered.
        😁😁

        Reply
  5. got this when visited *****.com/esp-chart.php “Connection failed: Access denied for user ‘*****_esp_brd’@’localhost’ to database ‘*****_esp_data’ “

    Reply
    • Hello Akash,

      I have the same issue.. ; but the database name, user and password are correct..

      Did you solved the issue ?
      If yes, please tell me how.

      Thanks in advance,
      alin

      Reply
          • Hello, same trouble here !
            The post-data file does work when opened in a browser.
            Only the esp-chart gives a “Connection failed: Access denied for user…”
            Strange because I copied / pasted the password, database Id ….
            I dont understand why 😉
            Thanks a lot,

  6. Ciao, thamks for your fantastic tutorials, i have learned a lot from them.
    In this one i have found a problem. Opening the file esp-chart.php it give me this error and i don’t know how to solve it:

    Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean in /home/mhd-01/www.”myhost”.it/htdocs/ESP/esp-chart.php:34 Stack trace: #0 {main} thrown in /home/mhd-01/www.”myhost”.it/htdocs/ESP/esp-chart.php on line 34

    Obviusly in “myhost” i have my domain name

    Reply
      • Hi Rui,
        I have almost the same error. I’m trying to mimic this data visualisation on my local computer, using XAMPP. I don’t understand your answer to the question of Davide. What do you mean by “leave localhost in the host”?
        This is the error text:
        Fatal error: Uncaught Error: Call to a member function fetch_assoc() on bool in /Applications/XAMPP/xamppfiles/htdocs/websiteSWB/esp-chart.php:34 Stack trace: #0 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/websiteSWB/esp-chart.php on line 34

        Reply
        • After hours of internet searching and trial and error I finally had success in using the XAMPP-environment to receive the ESP-data and plotting the chart in my browser locally. First I changed in the ‘esp-chart.php’ file the $username to “root” and the $password to “” (empty). Then in the Arduino sketch I set the servername to “http://192.168.0.16/websiteSWB/post-data.php”. This means: first the IP-address of my computer, followed by the foldername ‘websiteSWB’ which contains the ‘post-data.php file’. The folder is inside the xammp/htdocs/ folder structure.

          Reply
      • Hi Rui, thanks for this tutorial! Your time is appreciated.

        I have followed your tutorial to the letter and I am also recieving the same error regarding line 34? Very strange. I have only changed the database, username and password as intructed. The servername was left as localhost.

        [06-Feb-2021 11:06:02 UTC] PHP Fatal error: Uncaught Error: Call to a member function fetch_assoc() on bool in /home2/myHost/public_html/esp-chart.php:34
        Stack trace:
        #0 {main}

        thrown in /home2/myHost/public_html/esp-chart.php on line 34

        Do you have any idea what I might have to do to fix this?

        Thank you for your time.

        Reply
  7. Hi,
    Im trying to follow and try the tutorial according to the code and step, I managed to setup the mysql database, create post-data.php, and esp-chart.php, seem to be ok, except that for esp-chart.php I didnt see nothing, it did not show the X-Y chart and the title, it just doesnt show anything, I just copy and paste from ur rawcode, please advise, the php code seem to be able to connect to the sql database, it just doest display the html or chart portions of it.

    Reply
  8. Hi Rui,

    Sent a msg yesterday about my code not working. Actually ended up a problem with the php version stored on my ISP’s server.

    Just a suggestion, adding a sleep mode to the esp’s code, will make this project portable 😉

    Thanks again and keep up with the excellent job!

    Reply
  9. esp-chart.php is returning me this error:
    Connection failed: Access denied for user ‘xxxx_esp_boa’@’localhost’ (using password: YES)

    My database name, user and password are correct, the same as in post-data.php, which is working fine. My user has all privileges. I have a online mysql server, I work with wordpress websites, so it would have to do the job.
    What could be happening?

    Your project is very interesting, I wish I could see it working for me. Thank you and congratulations.

    Fabio.

    Reply
    • To be honest that error only happens if you entered the wrong settings in your PHP script… Can you double-check the database name, username, and password again?

      The user must have all the privileges as you’ve mentioned in order to work

      Reply
    • I have had the same Problem and solved it. My fault was to use the wrong kind of “-Key around the username and password. It was the „username“ instead of “username”.

      Reply
    • Check your database password if you are having access denied problems.
      Invalid characters in my password were causing the similar problems.

      Reply
  10. Forgot to mention the function which solved my php version issue…

    if (! function_exists(‘array_column’)) {
    function array_column(array $input, $columnKey, $indexKey = null) {
    $array = array();
    foreach ($input as $value) {
    if ( !array_key_exists($columnKey, $value)) {
    trigger_error(“Key \”$columnKey\” does not exist in array”);
    return false;
    }
    if (is_null($indexKey)) {
    $array[] = $value[$columnKey];
    }
    else {
    if ( !array_key_exists($indexKey, $value)) {
    trigger_error(“Key \”$indexKey\” does not exist in array”);
    return false;
    }
    if ( ! is_scalar($value[$indexKey])) {
    trigger_error(“Key \”$indexKey\” does not contain scalar value”);
    return false;
    }
    $array[$value[$indexKey]] = $value[$columnKey];
    }
    }
    return $array;
    }
    }

    Reply
  11. Hi, Rui good work Rui, I want a bit modification, can I transfer and plot my sensor data within micro seconds delay rather than 30 seconds? Actually, I want to plot the real time current wave of my induction motor. So, please suggest what I have to change?

    Reply
  12. Hi,
    many thanks for the good tutorial. I like the presented architecture very much.
    I use the Highcharts library for the first time. Unfortunately the scaling on the x-axis is not nice because of the crooked values. I haven’t managed to get a reasonable scaling yet.
    Do you have any idea to get this?

    Reply
    • You can definitely modify the charts look as they are highly customizable (show less points or hide x axis data). Unfortunately I don’t have any examples on that subject…

      Reply
  13. I have entered the Sensor table in phpMyAdmin in me account at ONE.COM.
    But where and how do I enter the PHP files?
    There is no cPanel file manager.
    Sorry if this is a silly question, I am new to all this sql php stuff.

    Reply
    • You should definitely have a file manager of some sort where you’ll find a folder called public_html (you might need to contact your host for specific details on where they have that folder).

      Reply
  14. Hi guys, thanks again for a brilliant tutorial. I have set up an ESP32 and have it logging to my home computer hosting a webserver and SQL database using Wamp64. Your code worked fine after a bit of setting up localhosts on the Wamp server. Also had some errors initially in the chart php code in line 35. The code returned an error until there was some data in the sensor table. The php code is looking for an array which only gets populated when there is some data. After the first posting by the ESP all was fine.
    Keep up these great tutorials………
    Regards
    Alan

    Reply
  15. Hello
    I followed the tutorial to the letter.
    A problem has arisen when I connect the ESP32 to an external power source, the ESP32 if it turns on but does nothing, does not send data to the web. It only works correctly when it is connected via USB to my PC.
    What could be the problem?

    Reply
  16. Hi guys,
    just finished a project where I combined 4 of your previous projects:
    1. Sensor data to SQL database and available anywhere
    2. BME280 temp, humidity and pressure sensor data logging
    3. SD1306 OLED display with DS3231 Real Time clock
    4. ESP32 Dual Core for split processing

    Basically, I wanted to capture and display multiple sensor data together with real time video, real time clock data and display this on a dashboard with selectable update timing.
    I used the 2 ESP32 cores to periodically poll the SQL database for data (5 minute intervals) and also to update a Real Time Clock display every second.
    The results were posted to an IOBroker dashboard using Node Red logic behind the scenes. The outcome was a superb display with historical trends updated every 5 minutes and an IP camera live video.
    I have to thank you guys for the great work done on these individual projects which enabled me to get the final result.
    A big shout out to IOBroker and Node Red in providing the open source tools to integrate and display the data in a professional manner.
    Anybody interested in the details please contact me via RNT Forum as I’m pleased to share RNTs valuable work.

    Reply
  17. Hello and thanks a lot for that tuto. I’m noob on that : just began today
    I followed everything in your tuto.
    The only diff is that i’ve setup a ubuntu server with apache2 MySQL PhpMyadmin etc…
    Created databases etc…
    Finally at the end i loaded the sketch and i only add a auto-refresh in “esp-chart.php”
    I also put a DeepSleep function in the sketch, the chart is working and giving the good values : it’s great

    But on MySQL side i always get that errors :
    Unfortunately iam not a SQL expert so if someone can help me please ?
    Also as a no SQL expert, is it possible to add a button to reset data-base to restart from zero value


    Warning in ./libraries/sql.lib.php#613
    count(): Parameter must be an array or an object that implements Countable

    Backtrace

    ./libraries/sql.lib.php#2128: PMA_isRememberSortingOrder(array)

    Reply
  18. Hi
    Thanks for another interesting project. Works fine.
    I only wonder if I change my domain to ‘SSL’ or https from http,
    do I need to include WiFiClientSecure etc. in the sketch?

    Did one program that sends to Google Sheet and the fingerprint
    (client.verify(fingerprint, host)) does not seem to make any difference.
    Janne

    Reply
  19. Hello again 😉
    I’ve a question please :
    I noticed that the chart is limited for one day display history
    Is it possible to custom that view or get more large than now
    a view for one week or one month
    Is it possible to add an option like that in main esp_*.php page ?
    or at minimum setup a larger view

    Waiting for your feedback
    thanks in advanced

    Reply
  20. Guys, this tutorial is just awesome! Even though I’ve never created a website, a database or even registered a domain before, I was able to complete the whole project and it works perfectly. I managed to change the sensor to others and, with some changes of the script, measure different variables and check them from anywhere in the world! 🙂
    This tutorial is so well explained that it wasn’t as complicated to follow as it may seem at the beginning.

    Thank you very much for posting these projects and helping so many people.
    Best regards,
    Joan

    Reply
    • Hi Joan.
      Thank you so much for your feedback.
      We spend a lot of time making the tutorials as easy to follow as possible even if you don’t have any experience in these fields.
      We’ll try to create more projects on this subject on a near future (like sending email notifications, setting a threshold on a web form, etc…)
      Regards,
      Sara

      Reply
    • Hi Joan, can you please tell me how you were able to upload and display other data? I tried to modify this part:
      String httpRequestData = “api_key=” + apiKeyValue + “&value1=” + String((1.8*(bme.readTemperature())+32))
      + “&value2=” + String(bme.readHumidity()) + “&value3=” + String(bme.readPressure()/100.0F) + “”;

      to this:
      String httpRequestData = “api_key=” + apiKeyValue + “&value1=” + String((1.8*(bme.readTemperature())+32))
      + “&value2=” + String(coach()) + “&value3=” + String(starter()) + “”;

      I added these lines to confirm the data was being received:
      Serial.print(“httpRequestData: “);
      Serial.print(“Coach battery: “);
      Serial.print(String(coach()));
      Serial.println();
      Serial.print(“Starter battery: “);
      Serial.print(String(starter()));
      Serial.println();
      Serial.println(httpRequestData);

      Serial monitor output:
      20:02:44.638 -> httpRequestData: Coach battery: 9.54
      20:02:44.706 -> Starter battery: 12.08
      20:02:44.742 -> api_key=not_the_real_key&value1=80.71&value2=9.54&value3=12.09
      20:02:45.381 -> HTTP Response code: 200

      MySQL database never updates, webpage never updates. I only changed two of the variables.

      If anyone has an ideas please help.

      Thanks

      Reply
  21. Hi Rui, Hi Sara, please let me know how to do to implement Autoconnect on ESP32 (Not ESP8266!)

    I tried to do it but I’m getting compiling errors.

    Thanks

    Reply
  22. Hi Rui –

    Having saved this tutoprial when I first came across it, I called it up to solve a current problem. The approach taken to access HTTP services is much simpler than the one I have been using previously. Unfortunately, however, I cannot get past the #include line! The compiler throws errors. There seem to be countless variants of this library – HttpClient.h, ESP8266HTTPClient.h, ArduinoHttpClient.h and so on. None of these seems to compile! Help – what am I missing here?

    Reply
      • Hi Sara –

        Merry Christmas!

        I am using a NodeMCU ESP-12E board but the confusion arose over exactly which version of the HTTP library I should be using as the version specified above didn’t seem to work with some of the other libraries I was using. However, I finally succeeded with the libraries you recommended having modified the rest of my program to work with these and the updating is now working.

        Thanks for coming back to me – have a Happy New Year!

        Regards

        Phil

        Reply
  23. Hi Rui,
    short feedback from my side.
    Everything worked well. Thanks for all your work – very much appreciated.
    Looking forward to go on with the esp32 GSM one to get rid off the wifi challenges.

    Reply
  24. Hi Rui, Hi Sara
    thank you for your great tutorial,
    I would like to replace the Bme280 to DS18B20 or Dht 22, could you help me please,
    Best,

    Reply
  25. Hi and thanks for your valuable tutorials.
    How I can have a chart with shifting data from right to left.
    I have to press Enter key every time for reading and showing new data.
    Would you please guide me for solving this problem.

    Reply
  26. 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
    • 20:51:20.529 -> httpRequestData: api_key=tPmAT5Ab3j7F9&value1=24.20&value2=24.20&value3=993.83
      20:51:20.576 -> Error code: -1

      Reply
  27. My website doesnt show any readings but in Arduino serial monitor shows:
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.28&value2=84.59&value3=84.59
    HTTP Response code: 200

    I think the problem is in PHP file because there is no data shown in the SensorData table.

    Please help me. Thanks!

    Reply
  28. Dear Sara and Rui Santos,
    Thank you for all your projects. Not only are interesting, they are perfectly configured, with many included possibilities. I did it with another sensor like voltaje and DHT, but I think like you tha BM280 is much better. I used my NAS and my webpage and of course it works perfect due to the project is very clear and the I could find my errors quickly. The only thing that I didn’t find was how to show the part of the table I want to show based on the time or date that I want, but I think I have to study more about sql.
    Thakns again and best regards,
    Lorenzo

    Reply
  29. Sara & Rui,
    Thanks for the great tutorial. This was my first ESP32 / BME280 project and I managed to get everything working. I would like to modify the date format though and I’m not exactly sure how I can do this.

    I’ve been reading php.net’s manual for DateTime::format and tried to modify this line in esp-chart.php:

    $readings_time[$i] = date(“Y-m-d H:i:s”, strtotime(“$reading – 1 hours”));
    to
    $readings_time[$i] = date(“D H:i”, strtotime(“$reading – 1 hours”));

    I was hoping to get the date to display as “Mon 12:30” but this did not seem to work. Any suggestions? I am completely new to all of this so I’m a little puzzled.

    Thanks

    Reply
  30. Hello,

    First of all, congratulations for the excellent work you are doing with all these tutorials you are sharing with us.

    I have a quick question regarding the HTTP POST, is ti possible to show me how to adapt the code in order to send a POST but using HTTPS.

    I’ll really appreciate your help.

    Regards and great job.

    Reply
  31. Made this with a BMP085 sensor so no humidity available, had to changes the .h file with the correct one for the BMP085. and left out the part for the humidity reading.
    Once I get the correct sensor i put this back in.
    I like to read the tutorials and the comments, very useful.
    Thanks

    Reply
  32. if I have data 1000 record to show .this chart can show 40 data . How can I do to show data next 40? I maybe add button to show next data. How can I do that ?
    Thanks for advance

    Reply
  33. Hi! I want to modify the HTML Portion of the esp-chart.php files (text and colors) . But when i edit and save it, nothing changes. Thanks for your effort Rui

    Reply
  34. Hi together,

    points in my series here, are not always equidistant in time along the charts x-axis, but appear as that in the chart unfortunately.
    I have invested so much efforts already but have still not been able to find out,
    how Highcharts needs to be configured, so that the timestamp values appears at correct positions which reflect their proportional distance in time.
    Was anyone perhaps already been able to solve this appropriate?
    Thanks so much for sharing in that case !

    Kind Regards to you all and to Sara and Rui over there in Porto

    Reply
  35. most of the problems above have to do with the browser not updating.
    if you want to check this is your issue, just put an ‘ ? ‘ char behind your url and load webpage again. i d’ont know yow to fix this in the html code but someone over here probable does.
    thanks and welcome

    Reply
  36. 17:59:41.642 -> httpRequestData: api_key=tPmAT5Ab3j7F9&value1=22&value2=23&value3=26
    17:59:42.349 -> HTTP Response code: 400

    I’m getting this error can someone please help

    Reply
  37. if you get repnse 400 you must change the ligne
    http.begin(client, serverName);
    to
    http.begin( serverName);
    cordially

    Reply
  38. Hi, I’ve followed all the steps and server side everything works but when a try to update the DB i receive the error code 404 (not found). I can’t understand where is the problem. Have you some suggestion for the debug? Can i send the same request via the browser to understand where is the problem?
    Thanks, your work is awesome!

    Reply
    • I have also this problem, http response 301.
      I use php 8.

      I solved this by changed this part of code:
      // Your Domain name with URL path or IP address with path
      http.begin(client, serverName);

      To:
      http.begin(serverName);

      http response then change to 200

      I dont why in full code, they use http.begin(client, serverName);
      but in explanation they use http.begin(serverName);

      Reply
  39. Hi Sara and Rui,
    Thank you for great tutorial!

    I followed this project and it’s working great,
    but as SQL database grows, I decided to select each 10th value from database:
    $sql = “SELECT id, value1, value2, value3, reading_time FROM Sensor order by reading_time desc limit 1000
    WHERE id mod 10 = 0”;

    but this is not working.
    I tried <‘id’ mod 10 = 0> and but no success.

    Please help to make a proper SQL query.
    Thank you in advance!

    Reply
  40. Sara & Rui,
    Thanks for the great tutorial, realy enjoi the way you explained step by step the working.
    Stil i have a problem which a can’t solve .
    Downloaded your files, only changed necesairy variabels
    Running the arduino program the serial output says
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=23.12&value2=1008.19&value3=1008.19
    Error code: -1
    I checked in post-data.php and find out that the value of the $_SERVER[“REQUEST_METHOD] was “GET” instead of “POST”

    Where in the arduino can i change to send a post request ?

    Best regards
    Wouter

    Reply
  41. Hello Sara,

    Thanks for the advice.
    Did a lot of study to understand whats really happening
    Found out that the servername was wrong…
    I’m very happy, the project is (almost) working…
    Thanks again and keep on going to publish your fantastic projects.

    wouter

    Reply
    • Hi Wouter, what should the servername be? in the tutorial it’s stated as localhost, should that be different for everyone?

      Thanks

      Kind Regards

      George

      Reply
  42. Thank you so much for all this amazing tutorials. Did this one and the GET to control GPOIs from everywhere and worked like a charm. Adding to the wishlist, I hope you get to do one using websockets instead of GET and POST methods, similar to the ones you have done when the ESP acts as server.

    Thanks again and greetings from Mexico!!

    Reply
  43. Hi Rui! Thanks for yet another great tutorial!

    I followed this tutorial to the letter, and I have it hosted in bluehost, but I get an “HTPP ERROR 500” and I can’t figure out why. Data is being stored in the database, I can display it by other means, but every time I try to access ‘esp-chart.php’ I get the 500 error.

    Reply
    • Hi Chris, I have the same error, database and everything all connected and working and confirmed by BlueHost support team.

      Would it be something in the esp-chart.php code that has been modified and has a fault in it?
      not sure if anyone else getting the same issue?

      Reply
  44. Hi,
    i would like to tank you, i used this project with another sensor, changing the database and some minor things.

    i was struggling with an error, all works, http sent response code 200, but no rows was inserted inside the database, i solved by changing, in the ESP32 cide, the rows

    if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);

    }

    WITH THIS

    if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    Serial.print("HTTP get string: ");
    Serial.println(http.getString());
    }

    So you can find the errors on the server in the serial monitor of the ESP32 and debug it if there is some http or database issue.

    Hope this help

    Reply
  45. Hi sara and Rui,
    I realy appreciate your work. I benefit enormously from it.

    When a call the esp-chart.php, i get an empty page and an errors in the file manager appear :
    PHP Warning: Undefined variable $sensor_data in /home2/wdklmqmy/public_html/esp-chart.php on line 38
    [02-Mar-2022 07:35:59 America/Boise] PHP Fatal error: Uncaught TypeError: array_column(): Argument #1 ($array) must be of type array, null given in /home2/wdklmqmy/public_html/esp-chart.php:38

    Do you have any suggestions please ?

    Reply
  46. Nice tutorial
    With this, I know I don’t have to make use of thingsSpeak platform to publish my sensor values to the cloud which will still require me to use thingsSpeak API to get the data to my own database. I have a question though,
    How do I send a request from my website to an Arduino microcontroller to let say actuate a hardware device?

    Reply
  47. Excellent work you guys are producing.
    Apologies if this is a noobie question as I’ trying to learn php and html.
    The html code in this example also holds the php code containing the database, username and password.
    How secure is this information once on a live hosting site?
    Thank you

    Reply
  48. Hey Guysss
    Is there any way to host the database only on esp32 or something like that?
    Because I’m trying to do a project without internet access.
    If it is possible, can you send me any link or project to see?

    Cumprimentos xD

    Reply
  49. Thank you Rui and Sara for this awesome project. I have a few clarifications
    on How to change the time? or to set my project time zone to GMT+8 ?

    Thank you and more power.

    -Regards

    Reply
  50. Dear folks.

    Thank you sooo much for this outstandig well explained project.
    It inspired me to build it accordingly. I am trying to gain my knowledge and understanding of it. As I am an absolutly beginner, I am trying to put two datasets into one graph. Unfortunatley without any joy. I am sure, it is very simple once you got the hang of it.

    Can annyone please give a bit of support on how I can manage better understanding based on this example how to put two datasets into one graph?

    Much appreciated,
    Frank

    Reply
  51. Hi Rui,

    Thank you for your tutorial on this.
    I signed up for Bluehost through your link.
    I’ve followed your tutorial all the way but when I try to view the esp-chart.php through browser, I get the HTTP 500 error.
    Database are all connected and ready.
    I’ve only input username, dbname and password as mentioned in your tutorial.
    Not sure why or what the issue is that the chats do not show when I try view through websearch. the POST-data.php shows wording exactly as your tutorial.

    Can you please help me with this?
    I will greatly appreciate it.

    Thank you

    George

    Reply
  52. Hi rui,

    thanks for the great job, really helpfull for me as a beginner,

    right now i tried to reload the data without refresh the page..

    there is any toturial that i can follow ?

    thankss 3000

    Reply
  53. I can not get the mysql part working. I have a website with wordpress installed. WordPress is using mysql but there is a second database that I can use. Can wordpress interfere with this prosject in any way? I have generated the sql tables as instructed and uploaded the php files. When I try to run the …chart.php file nothing happens.

    Reply
  54. hi,

    all works great. the info is pushed on the table and displayed nicely on the webpage.

    my only problem is about the reading time: it seems that it is USA time.
    on PHP file i have :

    $readings_time = array_column($sensor_data, ‘reading_time’);

    // ******* Uncomment to convert readings time array to your timezone ********
    /$i = 0;
    foreach ($readings_time as $reading){
    // Uncomment to set timezone to – 1 hour (you can change 1 to any number)
    $readings_time[$i] = date(“Y-m-d H:i:s”, strtotime(“$reading – 1 hours”));
    // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
    $readings_time[$i] = date(“Y-m-d H:i:s”, strtotime(“$reading + 8 hours”));
    $i += 1;
    }
    /

    but is not working…
    any idea how to solve this ?

    thx,
    Gabriel

    Reply
  55. So I’ve followed a couple tutorials on this site to get my ESP32 and BME280 logging data to a mysql database. It’s been running flawlessly for about a month now.

    My question is multipart. Has anybody added a Real Time Clock (RTC) DS3231 to their project and added a second BME280.

    I notice when looking at the data in mysql the reading times seem to drift. I currently have it set to sample every 30 seconds. Lets say it samples 01:00:00PM then again at 01:00:30 then again at 01:01:01 and a 4th time at 01:01:31 and on and on it goes. I’d like to have it not ‘drift’ as much if possible so was wondering if adding a RTC and have it programmed to read every minute on the minute (or whatever interval I choose).

    Second request has anybody added a second BME280 to a ESP32? Reason I ‘d like to do this is to check the difference in humidity between sensors (one will be in a sealed can the second one outside it).

    Any help or links to other websites that might help with this is appreciated as I’m not a programmer so I’m learning by looking at what people have already done

    Reply
    • hi,

      the second you loose it might be caused by the connection delay.
      I an using the GSM data. The wake-up call is done correctly by the board, but between the wake-up and the time stamp of the data on server there are few seconds difference. Not sure that the real time clock it can help with this…

      A solution might be to write on micro sd card.

      my opinion…

      best,
      G

      Reply
  56. Thanks for the tutorial!
    The esp-chart.php works when you replace
    Sensor
    with
    SensorData
    in the sql query.

    For testing without the ESP you can fill the Database with the commandline:

    curl -v -H “Content-Type: application/x-www-form-urlencoded” -X POST -d “api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14” http:// your domain here /post-esp-data.php

    Reply
    • Hi, I am troubled on why does there’s no data entering into the database and also no data showing into the chart.

      In IDE this showing:

      httpRequestData: api_key=tPmAT5Ab3j7F9&value1=78.35&value2=78.35&value3=78.35
      HTTP Response code: 200

      What could be the problem? I already tried what you said but still not working. Thank you in advanced.

      Reply
  57. Hi, when I try to access my domain name in the following URL path, this is the result:

    Connection failed: No such file or directory

    This is the part when I am done editing the esp-chart.php.
    How can I resolve this? Thank you in advanced.

    Reply
  58. Hi, the problem now, is theres nothing show on the chart. Also there no data entering in database, but all is well in the serial monitor of the IDE. What could be the problem?

    Reply
  59. Hi again,

    This time I am troubled on why does there’s no data entering into the database and also no data showing into the chart.

    In IDE this showing:

    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=78.35&value2=78.35&value3=78.35
    HTTP Response code: 200

    What could be the problem? Thank you in advanced.

    Reply
  60. Hello Rui, I’ve learned a lot form your tutorials. They are excellent. I’ve built this tutorial based on BMP280 instead of BME280 some months ago and I succeeded in getting the database filled and the graph shown. About 4 weeks ago I switched to Bluehost as my new provider. I adjusted the database, imported the values that I previously have gathered and I adjusted the servernames, databasenames and password as requested. Now I’m receiving an HTTP response code of 301 and the data is not stored in the database. I found aout that the servername was rerouted from “http://cpelgrim.nl/BMP280_Strato_Test/BMP280_post-data.php”to “https://cpelgrim.nl/BMP280_Strato_Test/BMP280_post-data.php”. When I send my post to that location, I get an HTTP response code 406. Still nothing stored. When I replace the initial servername to https:// in my code I’m receiving HTTP response 400. When I use this servername with https:// in Postman, I can add a record to the database. I’m lost! Any indication where to search for a solution?

    Reply
  61. How does this compare to the Firebase base version of this project? Let me know if I’m wrong but to me they seem mostly the same one just uses Firebase and HTML while the other uses MySQL and PHP. Is there any major difference that would make one of them better than the other, I want to do a project similar to this but want to see if there would be a reason to chose one of these over the other or if it doesn’t really matter?

    Reply
  62. Hello, i hope you can help me, i am following this tutorial, and with changes about data sent, it works but i find out after 67 sending the 68, always got Error Code -1, no matter what i’ve done, always happened. I tried to change https.begin(serverName); also i force to close http to disconnect and reconnect wifi, and nothing worked, the only thing that works is to reboot the esp32, please how i can fix this, to send continuously data to my DB and not need to reboot the eps32, thank you

    Reply
    • I occasionally have the same error.
      I know it might not be the right way,
      but until a better solution comes along.
      I have chosen this solution
      Serial.print(“Error code: “);
      Serial.println(httpResponseCode);
      https.end();
      delay(100);
      ESP.restart();

      Reply
  63. thank you I will check that solution. but i dont know why this happen, maybe another library? what experience do you have about this situation?

    Reply
      • I disconnected from wifi, also from http, but no, still with -1 error code, I think that maybe it something relating with secure wifi client

        Reply
        • You can try using this emergency solution
          paste this in the code after this Serial.print(“Error code: “);
          then it restarts itself and continues from where it stopped
          Serial.print(“Error code: “);
          Serial.println(httpResponseCode);
          https.end();
          delay(100);
          ESP.restart();

          Reply
          • yes, i already did that, it’s the only solution that works for now, even so i will continue digging on internet to find a solution, meanwhile i will implement eeprom to store data due i am keeping some information recolected in the esp32 that will delete as soon as it boots, so, I’ll need to modify my sketch to add this funtion in order to avoid data lost.

          • If you find a solution, please let me know.
            I will also try to do some research on that issue.
            best regards J. Bredahl

        • Hi Eduardo.
          I think instead of using ESP.restart();
          you could use this.
          in the declaration section
          for example if it is an integer that must not be lost.

          static RTC_NOINIT_ATTR int variable = 0;
          #define uS_TO_S_FACTOR 1000000ULL

          and after the error code
          Serial.print(“Error code: “);
          Serial.println(httpResponseCode);
          https.end();
          esp_sleep_enable_timer_wakeup(1 * uS_TO_S_FACTOR);
          Serial.println(“Going to sleep now”);
          delay(100);
          esp_deep_sleep_start();
          this will restart esp32 after a second,
          without losing the value of your variable.

          Reply
  64. Does anyone know how to change this table
    If I return the time as a string value
    and how to set reading_time to that value.
    like value1, value2 and value3.
    it is readings from a ds3231.

    CREATE TABLE Sensor (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    value1 VARCHAR(10),
    value2 VARCHAR(10),
    value3 VARCHAR(10),
    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )

    Reply
    • It was simpler than I had expected
      I just had to insert a new variable
      value4 VARCHAR(20),
      and remove
      reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

      Reply
  65. Hi
    I tried to see if it was possible
    to run the raspberry pi in acces mode without a wifi router,
    by following the link below.
    learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software
    and this tutorial works great withthe pi in acces mode,
    where the esp32 is sending data to the data base on the pi.

    Reply
  66. Hi.
    Does anyone have a simple php script solution
    where the data is written to a csv file,
    rather than to a database file.
    Or is there anyone who can point me in the right direction.
    it would be great.

    Reply
  67. I have found the solution myself.
    but it can probably be done better.

    I have changed the post-data.php file to this
    in the simplest form without apikey or password.
    and it works.

    temp1 = temperature
    temp 2 = humidity
    temp 3 = pressure
    temp4 = time from rtc 3231 module

    Reply
  68. I’ll try again as the php parts were omitted.

    I have found the solution myself.
    but it can probably be done better.
    I changed the post-data.php file to this
    in the simplest form without apikey or password.
    and it works.
    temp1 = temperature
    temp 2 = humidity
    temp 3 = pressure
    temp4 = time from rtc 3231 module

    php file looks like this

    define(“LOG_FILE”, “./data.csv”);

    $temp1=$_POST[‘value1’];
    $temp2=$_POST[‘value2’];
    $temp3=$_POST[‘value3’];
    $temp4=$_POST[‘value4’];

    $file_handler = fopen(LOG_FILE, “a+”) or die(“Unable to open file”);
    fwrite($file_handler, $temp1 . “,” . $temp2 . “,” . $temp3 . “,” . $temp4 . “\n”);
    fflush($file_handler);
    echo “OK”;

    Reply
    • Not really……once data is in a database, there are many tools available to extract to a csv file. Sorting is also much easier in a db

      Reply
      • thank you for your honest answer.
        For my use, I think it is a bit overkill to use a database.
        But with that said, it really is a great tutorial Sara and Rui have created that shows all the aspects of using lamp server.

        Reply
          • Hello Sara. and thank you for your answer.
            but I have it up and running posting to csv file,
            based on this tutorial as you will be able to see
            if you look back in the comments on the page.
            I have removed access to my links
            Obviously, there was not much interest in my solution
            and the answer from Alan cross was a bit arrogant I think.
            so don’t worry, I’m posting and reading to a csv file
            from this tutorial

        • Hi JB, sorry that I came over as arrogant. That was not the intention. What is important is that if your application works for you then that’s great. The principle of the project is how to collect and record data. So you accomplished it in a way which suited your requirements. There are always multiple ways to achieve an end. I just happen to like db’s because I’m familiar with them. I’m glad you managed to tweak the project for your particular case.

          Reply
      • As a dedicated programmer, as I believe you are,
        I can’t understand why you think it’s uninteresting
        to know how to post to a text file using php or read the last x number of lines from a text using php,
        but you may already know how.

        Reply
        • I don’t think it’s uninteresting. I would preferred to have the data in a db. From there, I can manipulate and access the data in numerous applications and still have bona fide data as the source. The source remains in tact . If you are logging straight to a csv file, the data is only valid in the text file. You are limited to what you can do with the text file as the data is not relational. i.e. you cannot search easily using sql queries such as “find where time is xxx and temperature is yyy and pressure is zzz”. As I said, I can extract from a dab to a text file once results have been formulated.

          Reply
  69. Hi Rui
    I have removed access to all links in my posts and comments.
    so if possible please remove all my posts and comments.
    It will also make room for new and perhaps more relevant posts.
    best regards, Jørgen Bredahl.

    Reply
  70. Hi Sara and Rui,
    I have a suggestion.
    How about a like button next to the reply link.
    Sometimes I would like to give a comment thumbs up,
    without having to write a comment
    It would also save you a lot of space.

    Reply
    • Hi.
      Thanks for the suggestion.
      That would be a great feature. However, I dom’t think it’s possible to impelement something like that at the moment with the current strucure of our blog.
      Regards,
      Sara

      Reply
      • Hello Sara. and thank you for your answer.
        but I have it up and running posting to csv file,
        based on this tutorial as you will be able to see
        if you look back in the comments on the page.
        I have removed access to my links
        Obviously, there was not much interest in my solution
        and the answer from Alan cross was a bit arrogant I think.
        so don’t worry, I’m posting and reading to a csv file
        from this tutorial

        Reply
        • Great!
          Thanks for sharing your files.
          I’m currently out of the office, but I’ll take a look when I get home.
          Regards,
          Sara

          Reply
  71. Hi Sara.
    Material for one of your great tutorials.
    I made a python script or file
    which reads from a bme280 sensor connected to a raspberry pi board.
    and then writes the data
    to a database file and a csv file at the same time.
    I was inspired from this site
    github.com/jorgem0/raspberry_pi_bme280_mysql
    I had to modify the code to make it work on my platform
    here is link to my code under python
    drive.google.com/drive/folders/1uoEoTmaNWEUUwqxlLrDgYFrzqw4Nw-W2?usp=sharing
    Could it be material for one of your great tutorials.

    Reply
  72. Thanks for this great tutorial !
    Works like a charm!

    Now, Would it be possible to have a selector inserted on the esp_chart.php page where users could select, for example: last year/month/week/24h data to be displayed in the charts?

    Reply
  73. Hi
    if you are interested in how to get data from bme280 to a highcharts chart,
    where bme280 is connected to raspberry pi running apache server.
    here is how I have done it using cgi “common gate way interface”,
    no flask or other frameworks.
    just remember as always a lot of permissions has to be set.
    file to download is cgi.zip

    drive.google.com/drive/folders/1uoEoTmaNWEUUwqxlLrDgYFrzqw4Nw-W2?usp=sharing

    Reply
    • Ok it looks like cgi is being deprecated.
      I hadn’t seen that.
      but, it is easy to use
      I’d rather not use bottle.
      Does anyone have any suggestions to replace the cgi

      Reply
  74. Hi Rui and Sara, Thanks for all the great content. I am struggling with the -1 error code. I am using an 8266 and the test api string. The annoying thing is it was working fine last night then for some reason when i tried to move it to the project venue it started this error and i can seem to get rid of it or get my graph back!! Any ideas on this? I see a few others have had this but I couldn’t see anyone that has found a solution. Thanks in advance. Tanc

    Reply
  75. Hello Sara and Rui,
    thank you so much for this and all the other excellent tutorials. I am learning so much here!
    Yesterday I set up this project, using an ESP32-Board. All, including Database-access and Website, works fine, but after a certain time (between 10 and 45 minutes) I get errors and the connection to the web-based database is broken. Here’s the output from the terminal in VSCode:

    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.73&value2=43.44&value3=1006.61
    HTTP Response code: 200
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.76&value2=45.97&value3=1006.60
    [1994255][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-78) UNKNOWN ERROR CODE (004E)
    [1994256][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -78
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.87&value2=43.16&value3=1006.60
    [2025323][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-16) BIGNUM – Memory allocation failed
    [2025324][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -16
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.91&value2=42.91&value3=1006.62
    [2055463][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-17040) RSA – The public key operation failed : BIGNUM – Memory allocation failed
    [2055466][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -17040
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.95&value2=42.84&value3=1006.61
    [2085575][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-10368) X509 – Allocation of memory failed
    [2085576][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -10368
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.97&value2=42.79&value3=1006.61
    [2130050][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-76) UNKNOWN ERROR CODE (004C)
    [2130053][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -76
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=25.93&value2=43.55&value3=1006.61
    [2168624][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():276]: (-78) UNKNOWN ERROR CODE (004E)
    [2168627][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -78
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.05&value2=42.74&value3=1006.62
    [2198698][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2198699][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.08&value2=42.66&value3=1006.62
    [2228759][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2228759][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.03&value2=44.90&value3=1006.64
    [2258822][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2258823][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.04&value2=44.17&value3=1006.65
    [2288906][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2288906][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.16&value2=42.88&value3=1006.63
    [2318973][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2318973][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.20&value2=42.90&value3=1006.65
    [2349035][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2349036][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.25&value2=42.65&value3=1006.64
    [2379097][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2379097][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.33&value2=42.46&value3=1006.64
    [2409164][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2409164][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.34&value2=42.50&value3=1006.63
    [2439226][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2439227][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.37&value2=42.28&value3=1006.64
    [2469297][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2469297][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.40&value2=42.29&value3=1006.64
    [2499358][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2499358][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.42&value2=42.25&value3=1006.63
    [2529422][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2529423][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.37&value2=42.97&value3=1006.67
    [2559488][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2559488][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.43&value2=42.45&value3=1006.67
    [2589557][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2589558][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    httpRequestData: api_key=tPmAT5Ab3j7F9&value1=26.41&value2=42.26&value3=1006.66
    [2619624][E][ssl_client.cpp:37] _handle_error(): [start_ssl_client():267]: (-32512) SSL – Memory allocation failed
    [2619624][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -32512
    Error code: -1
    WiFi Disconnected

    Until the first occurence of the error the system worked well for about 30 minutes. Unfortunately I have no idea, what to do or where to search for a solution. What I realize is, that the measurement is working properly, but the connection to the database ist lost due to some spooky ssl-errors.

    Do you have an idea how to solve this problem?

    Best Regards,
    Thomas

    Reply
  76. Ok, I have done some homework 🙂

    I think calling “WiFiClientSecure *client = new WiFiClientSecure;” in every loop without freeing the allocated memory at the end of the loop causes a memory leak.
    Added “delete client;” after “https.end();”

    The system is now up for about 60 minutes and seems to work fine. 🙂

    Reply
  77. Hi
    I am runing a LAMP (Linux, Apache, MySQL, PHP) server on a Raspberry Pi
    from this tutorial
    https://randomnerdtutorials.com/raspberry-pi-apache-mysql-php-lamp-server/

    To make it all simpler
    I connected the bme280 sensor directly to the raspberry pi
    to get the sensor readings, instead of using esp32,

    Then I tried different ways to read the sensor readings
    into a highcharts chart, from the Raspberry Pi,
    which adds new data to the chart every 10 seconds.

    cgi which is an old framework and slow and.
    I then tried flask framework which is really fast,
    I then found that it can be done with just html, php and python.
    not as fast as the flask framework, but fast enough.

    here is a link to the last one with html, php and python.
    drive.google.com/drive/folders/1uoEoTmaNWEUUwqxlLrDgYFrzqw4Nw-W2?usp=sharing

    Reply
  78. Hi
    it looks like my last post has disappeared,
    so I’ll just post it again.

    I am runing a LAMP (Linux, Apache, MySQL, PHP) server on a Raspberry Pi
    from this tutorial
    https://randomnerdtutorials.com/raspberry-pi-apache-mysql-php-lamp-server/

    To make it all simpler
    I connected the bme280 sensor directly to the raspberry pi
    to get the sensor readings, instead of using esp32,

    Then I tried different ways to read the sensor readings
    into a highcharts chart, from the Raspberry Pi,
    which adds new data to the chart every 10 seconds.

    cgi which is an old framework and slow and.
    I then tried flask framework which is really fast,
    I then found that it can be done with just html, php and python.
    not as fast as the flask framework, but fast enough.

    here is a link to the last one with html, php and python.
    drive.google.com/drive/folders/1uoEoTmaNWEUUwqxlLrDgYFrzqw4Nw-W2?usp=sharing

    Reply
    • In the link where I share my files, further up the page
      is a link which helped me go from development server,
      to configure Apache for deploying a flask app
      on my raspberry pi.

      Reply
  79. Hi Sara and Rui Santos, I’m doing in step4 “PHP Script – Visualize Database Content in a Chart” after I create the “esp-chart.php” file and change the “$dbname, $username and $password” I try to access my domain name in “https://songthumbirdnest.com/esp-chart.php” but it not show everything. This link is my “esp-chart.php” file (drive.google.com/drive/folders/16eAt7vB4ar_gXTPJa2i4XTNLuTcL1q_D?usp=sharing).
    Waiting for a reply.

    Best Regards,
    Wongsatorn.p

    Reply
  80. hello,
    I just made this project and it works fantastic. I want to add more values in the databse (more than 3) and access them. How can I do that??

    Reply
  81. Hello you wonderful teachers. I just made this project as an example so I could learn how to do it. Now I just need incorporate it into my main project which is a hot tub controller using a WT32-SC01 module, four 30A solid state relays – 30A is overkill especially for the lighting but it is easier to order everything the same – a DS18B20 to measure water temperature and my own version of the BME280 using SHT21 and SPL06 sensors I had fabricated when the cost of BME280’s sky rocketed a couple of years back due to availability issues.

    Anyhow, the GUI shows the water temperature, air temperature, pressure, and humidity, and has buttons to turn the main, on-spa controller on and off, set the desired temperature and daily running times for the circ pump. It syncs the time once a day and uses the RTC the rest of the time. leaving the Wi-Fi connection free to handle a web page so the full functionality of the unit can be controlled from my iPad, Android phone etc. – I just haven’t got round to that bit yet. All of the various bits and pieces have been researched using RNT and it would have taken my so much longer to write them without your helpful tutorials. Thank you so much for doing it.

    Now, the sample code above connects to my Wi-Fi and is given an IP such as 192.168.1.246 however, if our power goes off (which is an all too regular occurrence here in Cyprus away from the coast) this may or may not be the IP it is assigned on next boot and because it is a stand alone unit, I am not able to simply find out the IP by looking at the serial monitor. However, the MAC is hard coded into the ESP32 chip and will not change so it could be used to identify the unit. Ideally, I would like to go onto my iPad or Phone and simply enter ‘hottub’ in the address bar rather than the IP address – even if it never changes, I still have to remember it!

    Do you know of any name servers which would work on an internal network and track the IP address of my separate modules? I have two PC’s in the paint shop of a large car manufacturing facility back home in UK. They are air gapped from the manufacturers own networks and connect to the internet using 4G modem/routers. I use noip.com to track the external IP addresses assigned to the routers so I can VNC into the servers using a memorable server name. I am sorry the post is so long winded but I wanted to fully explain my question.

    Once again, thank you for all your good work. Stay safe and healthy, Steve.

    Reply
  82. Hi thanks for the tutorial. I think it should be great for what i need to do. I do have a problem with the Esp-chart.php though – after following the tutorial I don’t see anything on my site when trying to access mydomain/esp-chart.php – was expecting to see 3 empty charts but just get a blank page. Can anyone help please? Not sure if i need to change a setting on myphpadmin to be able to see the page. Have typed and also copied and pasted the code but still get a blank page. Thanks in advance, jonathan

    Reply
  83. Hi! I need help with this tutorial. I’m using 000webhost for the website and database management. I was just wondering, what index file should I use or if I need to create my own? I noticed in the tutorial that no index file was made, and when I tried accessing the site I get to a page that says I need an index.php file. I’m totally new at this and any type of help regarding this is greatly appreciated. Thanks!

    Reply
  84. Hello, a newbie to ESP32 world. does this exercise uses FreeRTOS anywhere within the libraries ? or is it just a firmware kind running on baremetal system ?

    Reply

Leave a Comment

Download Our Free eBooks and Resources

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