{"id":26322,"date":"2022-11-19T16:43:22","date_gmt":"2022-11-19T09:43:22","guid":{"rendered":"https:\/\/tom.ji42.com\/?p=26322"},"modified":"2022-11-19T16:43:22","modified_gmt":"2022-11-19T09:43:22","slug":"esp32-esp8266-insert-data-into-mysql-database-using-php-and-arduino-ide","status":"publish","type":"post","link":"https:\/\/tom.tomwork.net\/?p=26322","title":{"rendered":"ESP32\/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE"},"content":{"rendered":"<p>In this project you\u2019ll build an ESP32 or ESP8266 client that makes an HTTP POST request to a PHP script to insert data (sensor readings) into a MySQL database.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"828\" height=\"466\" alt=\"ESP32 ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-Insert-Data-MySQL-Database-PHP-Arduino-IDE.jpg?resize=828%2C466&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>You\u2019ll also have a web page that displays the sensor readings, timestamp and other information from the database. You can visualize your data from anywhere in the world by accessing your own server.<\/p>\n<p><!--more--><\/p>\n<p>As an example, we\u2019ll 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.<\/p>\n<p>In order to create build this project, you\u2019ll use these technologies:<\/p>\n<ul>\n<li>ESP32 or ESP8266 programmed with Arduino IDE\n<li>Hosting server and domain name\n<li>PHP script to insert data into MySQL and display it on a web page\n<li>MySQL database to store readings<\/li>\n<\/ul>\n<h4>1. Hosting Your PHP Application and MySQL Database<\/h4>\n<p>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\u2019s a high level overview:<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-MySQL-Project-Overview.png?quality=100&amp;strip=all&amp;ssl=1\"><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"680\" alt=\"Hosting PHP Application and MySQL Database to post ESP32 or ESP8266 Sensor Readings\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-MySQL-Project-Overview.png?resize=750%2C680&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/a><\/p>\n<p>I recommend using one of the following hosting services that can handle all the project requirements:<\/p>\n<ul>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/bluehost\">Bluehost (user-friendly with cPanel)<\/a>: free domain name when you sign up for the 3-year plan. I recommend choosing the unlimited websites option;\n<li><a href=\"https:\/\/randomnerdtutorials.com\/digitalocean\">Digital Ocean<\/a>: Linux server that you manage through a command line. I only recommended this option for advanced users.<\/li>\n<\/ul>\n<p>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\u2019t have a hosting account, I recommend <a href=\"https:\/\/randomnerdtutorials.com\/bluehost\">signing up for Bluehost<\/a>.<\/p>\n<p><a href=\"https:\/\/randomnerdtutorials.com\/bluehost\">Get Hosting and Domain Name with Bluehost \u00bb<\/a><\/p>\n<p>When buying a hosting account, you\u2019ll also have to purchase a domain name. This is what makes this project interesting: you\u2019ll be able to go your domain name (http:\/\/example-domain.com) and see your ESP readings.<\/p>\n<p>If you like our projects, you might consider signing up to one of the recommended hosting services, because you\u2019ll be supporting our work.<\/p>\n<p><strong>Note: <\/strong>you can also run a <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-apache-mysql-php-lamp-server\/\">LAMP (Linux, Apache, MySQL, PHP) server<\/a> on a Raspberry Pi to <a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-raspberry-pi-lamp-server\/\">access data in your local network<\/a>. 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.<\/p>\n<h4>2. Preparing Your MySQL Database<\/h4>\n<p>After signing up for a <a href=\"https:\/\/randomnerdtutorials.com\/bluehost\">hosting account and setting up a domain name<\/a>, you can login to your cPanel or similar dashboard. After that, follow the next steps to create your database, username, password and SQL table.<\/p>\n<h5>Creating a database and user<\/h5>\n<p><strong>1.<\/strong> Type \u201cdatabase\u201d in the search bar and select \u201cMySQL Database Wizard\u201d.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"826\" height=\"300\" alt=\"CPanel select MySQL database wizard to create db\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/CPanel-select-MySQL-database-wizard-to-create-db.png?resize=826%2C300&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>2.<\/strong> Enter your desired Database name. In my case, the database name is esp_data. Then, press the \u201cNext Step\u201d button:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"609\" height=\"443\" alt=\"ESP32 ESP8266 CPanel Create MySQL Database\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-CPanel-Create-MySQL-Database.png?resize=609%2C443&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>Note: <\/strong>later you\u2019ll have to use the database name with the prefix that your host gives you (my database prefix in the screenshot above is blurred). I\u2019ll refer to it as example_esp_data from now on.<\/p>\n<p><strong>3.<\/strong> Type your Database username and set a password. You must save all those details, because you\u2019ll need them later to establish a database connection with your PHP code.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"736\" height=\"615\" alt=\"ESP32 ESP8266 CPanel Create MySQL Database User and Password\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-CPanel-Create-MySQL-Database-User-Password.png?resize=736%2C615&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>That\u2019s it! Your new database and user were created successfully. Now, save all your details because you\u2019ll need them later:<\/p>\n<ul>\n<li><strong>Database name<\/strong>: example_esp_data\n<li><strong>Username<\/strong>: example_esp_board\n<li><strong>Password<\/strong>: your password<\/li>\n<\/ul>\n<h5>Creating a SQL table<\/h5>\n<p>After creating your database and user, go back to cPanel dashboard and search for \u201cphpMyAdmin\u201d.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"766\" height=\"315\" alt=\"ESP32 ESP8266 CPanel Open PHPMyAdmin\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-CPanel-Open-PHPMyAdmin.png?resize=766%2C315&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>In the left sidebar, select your database name example_esp_data and open the \u201cSQL\u201d tab.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"797\" height=\"521\" alt=\"ESP32 ESP8266 PHPMyAdmin Open Database\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-PHPMyAdmin-Open-Database.png?resize=797%2C521&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>Important: <\/strong>make sure you\u2019ve opened the example_esp_data database. Then, click the SQL tab. If you don\u2019t follow these exact steps and run the SQL query, you might create a table in the wrong database.<\/p>\n<p>Copy the SQL query in the following snippet:<\/p>\n<pre><code>CREATE TABLE SensorData (\n    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n    sensor VARCHAR(30) NOT NULL,\n    location VARCHAR(30) NOT NULL,\n    value1 VARCHAR(10),\n    value2 VARCHAR(10),\n    value3 VARCHAR(10),\n    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\n)\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/RuiSantosdotme\/ESP32-ESP8266-PHP-MySQL\/raw\/master\/code\/SensorData_Table.sql\">View raw code<\/a><\/p>\n<p>Paste it in the SQL query field (highlighted with a red rectangle) and press the \u201cGo\u201d button to create your table:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"828\" height=\"412\" alt=\"ESP32 ESP8266 PHPMyAdmin Create SQL Table\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-PHPMyAdmin-Create-SQL-Table.png?resize=828%2C412&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>After that, you should see your newly created table called SensorData in the example_esp_data database as shown in the figure below:<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-PHPMyAdmin-View-SQL-Database.png?quality=100&amp;strip=all&amp;ssl=1\"><img loading=\"lazy\" decoding=\"async\" width=\"828\" height=\"276\" alt=\"ESP32 ESP8266 PHPMyAdmin View SQL Database\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-PHPMyAdmin-View-SQL-Database.png?resize=828%2C276&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/a><\/p>\n<h4>3. PHP Script HTTP POST \u2013 Insert Data in MySQL Database<\/h4>\n<p>In this section, we\u2019re going to create a PHP script that is responsible for receiving incoming requests from the ESP32 or ESP8266 and inserting the data into a MySQL database.<\/p>\n<p>If you\u2019re using a hosting provider with cPanel, you can search for \u201cFile Manager\u201d:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"761\" height=\"340\" alt=\"ESP32 ESP8266 CPanel Open Edit PHP Files\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-CPanel-Open-Edit-PHP-Files.png?resize=761%2C340&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>Then, select the <strong>public_html<\/strong> option and press the \u201c+ File\u201d button to create a new <em>.php<\/em> file.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"828\" height=\"337\" alt=\"ESP32 ESP8266 CPanel Create New PHP File\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-CPanel-Create-New-PHP-File.png?resize=828%2C337&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>Note: <\/strong>if you\u2019re following this tutorial and you\u2019re not familiar with PHP or MySQL, I recommend creating these exact files. Otherwise, you\u2019ll need to modify the ESP sketch provided with different URL paths.<\/p>\n<p>Create a new file in <strong>\/public_html<\/strong> with this exact name and extension: <em>post-esp-data.php<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"501\" height=\"246\" alt=\"PHP Create New file post esp data\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/PHP-Create-New-file-post-esp-data.png?resize=501%2C246&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>Edit the newly created file (<em>post-esp-data.php<\/em>) and copy the following snippet:<\/p>\n<pre><code>&lt;?php\n\n\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-esp8266-mysql-database-php\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n$servername = \"localhost\";\n\n\/\/ REPLACE with your Database name\n$dbname = \"REPLACE_WITH_YOUR_DATABASE_NAME\";\n\/\/ REPLACE with Database user\n$username = \"REPLACE_WITH_YOUR_USERNAME\";\n\/\/ REPLACE with Database user password\n$password = \"REPLACE_WITH_YOUR_PASSWORD\";\n\n\/\/ Keep this API Key value to be compatible with the ESP32 code provided in the project page. \n\/\/ If you change this value, the ESP32 sketch needs to match\n$api_key_value = \"tPmAT5Ab3j7F9\";\n\n$api_key= $sensor = $location = $value1 = $value2 = $value3 = \"\";\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n    $api_key = test_input($_POST[\"api_key\"]);\n    if($api_key == $api_key_value) {\n        $sensor = test_input($_POST[\"sensor\"]);\n        $location = test_input($_POST[\"location\"]);\n        $value1 = test_input($_POST[\"value1\"]);\n        $value2 = test_input($_POST[\"value2\"]);\n        $value3 = test_input($_POST[\"value3\"]);\n        \n        \/\/ Create connection\n        $conn = new mysqli($servername, $username, $password, $dbname);\n        \/\/ Check connection\n        if ($conn-&gt;connect_error) {\n            die(\"Connection failed: \" . $conn-&gt;connect_error);\n        } \n        \n        $sql = \"INSERT INTO SensorData (sensor, location, value1, value2, value3)\n        VALUES ('\" . $sensor . \"', '\" . $location . \"', '\" . $value1 . \"', '\" . $value2 . \"', '\" . $value3 . \"')\";\n        \n        if ($conn-&gt;query($sql) === TRUE) {\n            echo \"New record created successfully\";\n        } \n        else {\n            echo \"Error: \" . $sql . \"&lt;br&gt;\" . $conn-&gt;error;\n        }\n    \n        $conn-&gt;close();\n    }\n    else {\n        echo \"Wrong API Key provided.\";\n    }\n\n}\nelse {\n    echo \"No data posted with HTTP POST.\";\n}\n\nfunction test_input($data) {\n    $data = trim($data);\n    $data = stripslashes($data);\n    $data = htmlspecialchars($data);\n    return $data;\n}\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/RuiSantosdotme\/ESP32-ESP8266-PHP-MySQL\/raw\/master\/code\/post-esp-data.php\">View raw code<\/a><\/p>\n<p>Before saving the file, you need to modify the $dbname, $username and $password variables with your unique details:<\/p>\n<pre><code>\/\/ Your Database name\n$dbname = \"example_esp_data\";\n\/\/ Your Database user\n$username = \"example_esp_board\";\n\/\/ Your Database user password\n$password = \"YOUR_USER_PASSWORD\";<\/code><\/pre>\n<p>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\u2019ll see the following:<\/p>\n<pre><code>http:\/\/example-domain.com\/post-esp-data.php<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"697\" height=\"272\" alt=\"ESP32 ESP8266 Test POST ESP Data PHP URL\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-Test-POST-ESP-Data-URL.png?resize=697%2C272&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<h4>4. PHP Script \u2013 Display Database Content<\/h4>\n<p>Create another PHP file in the <strong>\/public_html<\/strong> directory that will display all the database content in a web page. Name your new file: <em>esp-data.php<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"501\" height=\"244\" alt=\"PHP Create New file esp data\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/PHP-Create-New-file-esp-data.png?resize=501%2C244&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>Edit the newly created file (<em>esp-data.php<\/em>) and copy the following code:<\/p>\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;&lt;body&gt;\n&lt;?php\n\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-esp8266-mysql-database-php\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n$servername = \"localhost\";\n\n\/\/ REPLACE with your Database name\n$dbname = \"REPLACE_WITH_YOUR_DATABASE_NAME\";\n\/\/ REPLACE with Database user\n$username = \"REPLACE_WITH_YOUR_USERNAME\";\n\/\/ REPLACE with Database user password\n$password = \"REPLACE_WITH_YOUR_PASSWORD\";\n\n\/\/ Create connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n\/\/ Check connection\nif ($conn-&gt;connect_error) {\n    die(\"Connection failed: \" . $conn-&gt;connect_error);\n} \n\n$sql = \"SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC\";\n\necho '&lt;table cellspacing=\"5\" cellpadding=\"5\"&gt;\n      &lt;tr&gt; \n        &lt;td&gt;ID&lt;\/td&gt; \n        &lt;td&gt;Sensor&lt;\/td&gt; \n        &lt;td&gt;Location&lt;\/td&gt; \n        &lt;td&gt;Value 1&lt;\/td&gt; \n        &lt;td&gt;Value 2&lt;\/td&gt;\n        &lt;td&gt;Value 3&lt;\/td&gt; \n        &lt;td&gt;Timestamp&lt;\/td&gt; \n      &lt;\/tr&gt;';\n \nif ($result = $conn-&gt;query($sql)) {\n    while ($row = $result-&gt;fetch_assoc()) {\n        $row_id = $row[\"id\"];\n        $row_sensor = $row[\"sensor\"];\n        $row_location = $row[\"location\"];\n        $row_value1 = $row[\"value1\"];\n        $row_value2 = $row[\"value2\"]; \n        $row_value3 = $row[\"value3\"]; \n        $row_reading_time = $row[\"reading_time\"];\n        \/\/ Uncomment to set timezone to - 1 hour (you can change 1 to any number)\n        \/\/$row_reading_time = date(\"Y-m-d H:i:s\", strtotime(\"$row_reading_time - 1 hours\"));\n      \n        \/\/ Uncomment to set timezone to + 4 hours (you can change 4 to any number)\n        \/\/$row_reading_time = date(\"Y-m-d H:i:s\", strtotime(\"$row_reading_time + 4 hours\"));\n      \n        echo '&lt;tr&gt; \n                &lt;td&gt;' . $row_id . '&lt;\/td&gt; \n                &lt;td&gt;' . $row_sensor . '&lt;\/td&gt; \n                &lt;td&gt;' . $row_location . '&lt;\/td&gt; \n                &lt;td&gt;' . $row_value1 . '&lt;\/td&gt; \n                &lt;td&gt;' . $row_value2 . '&lt;\/td&gt;\n                &lt;td&gt;' . $row_value3 . '&lt;\/td&gt; \n                &lt;td&gt;' . $row_reading_time . '&lt;\/td&gt; \n              &lt;\/tr&gt;';\n    }\n    $result-&gt;free();\n}\n\n$conn-&gt;close();\n?&gt; \n&lt;\/table&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/RuiSantosdotme\/ESP32-ESP8266-PHP-MySQL\/raw\/master\/code\/esp-data.php\">View raw code<\/a><\/p>\n<p>After adding the $dbname, $username and $password save the file and continue with this project.<\/p>\n<pre><code>\/\/ Your Database name\n$dbname = \"example_esp_data\";\n\/\/ Your Database user\n$username = \"example_esp_board\";\n\/\/ Your Database user password\n$password = \"YOUR_USER_PASSWORD\";<\/code><\/pre>\n<p>If you try to access your domain name in the following URL path, you\u2019ll see the following:<\/p>\n<pre><code>http:\/\/example-domain.com\/esp-data.php<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"682\" height=\"292\" alt=\"ESP32 ESP8266 Test ESP Data PHP URL\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-Test-ESP-Data-URL.png?resize=682%2C292&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>That\u2019s it! If you see that empty table printed in your browser, it means that everything is ready. In the next section, you\u2019ll learn how to insert data from your ESP32 or ESP8266 into the database.<\/p>\n<h4>5. Preparing Your ESP32 or ESP8266<\/h4>\n<p>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.<\/p>\n<h5>Parts Required<\/h5>\n<p>For this example we\u2019ll get sensor readings from the BME280 sensor. Here\u2019s a list of parts you need to build the circuit for this project:<\/p>\n<ul>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\">ESP32 board<\/a> (read <a href=\"https:\/\/makeradvisor.com\/esp32-development-boards-review-comparison\/\">Best ESP32 dev boards<\/a>)\n<li>Alternative \u2013 <a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\">ESP8266<\/a> board (read <a href=\"https:\/\/makeradvisor.com\/best-esp8266-wi-fi-development-board\/\">Best ESP8266 dev boards<\/a>)\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/bme280-sensor-module\/\">BME280 sensor<\/a>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\">Jumper wires<\/a>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\">Breadboard<\/a><\/li>\n<\/ul>\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&amp;utm_medium=post&amp;utm_campaign=post\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p>\n<p><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&amp;utm_medium=post&amp;utm_campaign=post\"><img decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=828&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/a><\/p>\n<h5>Schematics<\/h5>\n<p>The BME280 sensor module we\u2019re using communicates via I2C communication protocol, so you need to connect it to the ESP32 or ESP8266 I2C pins.<\/p>\n<h6>BME280 wiring to ESP32<\/h6>\n<p>The ESP32 I2C pins are:<\/p>\n<ul>\n<li><strong>GPIO 22:<\/strong> SCL (SCK)\n<li><strong>GPIO 21:<\/strong> SDA (SDI)<\/li>\n<\/ul>\n<p>So, assemble your circuit as shown in the next schematic diagram (<a href=\"https:\/\/randomnerdtutorials.com\/esp32-bme280-arduino-ide-pressure-temperature-humidity\/\">read complete Guide for ESP32 with BME280<\/a>).<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"652\" alt=\"BME280 wiring to ESP32\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/03\/ESP32-bme280_bb.png?resize=750%2C652&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>Recommended reading:<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/esp32-pinout-reference-gpios\/\">ESP32 Pinout Reference Guide<\/a><\/p>\n<h6>BME280 wiring to ESP8266<\/h6>\n<p>The ESP8266 I2C pins are:<\/p>\n<ul>\n<li><strong>GPIO 5 <\/strong>(D1): SCL (SCK)\n<li><strong>GPIO 4 <\/strong>(D2): SDA (SDI)<\/li>\n<\/ul>\n<p>Assemble your circuit as in the next schematic diagram if you\u2019re using an ESP8266 board (<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-bme280-arduino-ide\/\">read complete Guide for ESP8266 with BME280<\/a>).<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"705\" height=\"532\" alt=\"BME280 wiring to ESP8266\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP8266-BME280-Arduino-IDE.png?resize=705%2C532&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p><strong>Recommended reading:<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/esp8266-pinout-reference-gpios\/\">ESP8266 Pinout Reference Guide<\/a><\/p>\n<h5>ESP32\/ESP8266 Code<\/h5>\n<p>We\u2019ll 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\u2019re using:<\/p>\n<ul>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-windows-instructions\/\">Install the ESP32 Board in Arduino IDE<\/a> \u2013 you also need to <a href=\"https:\/\/randomnerdtutorials.com\/esp32-bme280-arduino-ide-pressure-temperature-humidity\/\">install the BME280 Library and Adafruit_Sensor library<\/a>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-esp8266-board-arduino-ide\/\">Install the ESP8266 Board in Arduino IDE<\/a> \u2013 you also need to <a href=\"https:\/\/randomnerdtutorials.com\/esp8266-bme280-arduino-ide\/\">install the BME280 Library and Adafruit_Sensor library<\/a><\/li>\n<\/ul>\n<p>After installing the necessary board add-ons, copy the following code to your Arduino IDE, but don\u2019t upload it yet. You need to make some changes to make it work for you.<\/p>\n<pre><code>\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-esp8266-mysql-database-php\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n\n*\/\n\n#ifdef ESP32\n  #include &lt;WiFi.h&gt;\n  #include &lt;HTTPClient.h&gt;\n#else\n  #include &lt;ESP8266WiFi.h&gt;\n  #include &lt;ESP8266HTTPClient.h&gt;\n  #include &lt;WiFiClient.h&gt;\n#endif\n\n#include &lt;Wire.h&gt;\n#include &lt;Adafruit_Sensor.h&gt;\n#include &lt;Adafruit_BME280.h&gt;\n\n\/\/ Replace with your network credentials\nconst char* ssid     = \"REPLACE_WITH_YOUR_SSID\";\nconst char* password = \"REPLACE_WITH_YOUR_PASSWORD\";\n\n\/\/ REPLACE with your Domain name and URL path or IP address with path\nconst char* serverName = \"http:\/\/example.com\/post-esp-data.php\";\n\n\/\/ Keep this API Key value to be compatible with the PHP code provided in the project page. \n\/\/ If you change the apiKeyValue value, the PHP file \/post-esp-data.php also needs to have the same key \nString apiKeyValue = \"tPmAT5Ab3j7F9\";\n\nString sensorName = \"BME280\";\nString sensorLocation = \"Office\";\n\n\/*#include &lt;SPI.h&gt;\n#define BME_SCK 18\n#define BME_MISO 19\n#define BME_MOSI 23\n#define BME_CS 5*\/\n\n#define SEALEVELPRESSURE_HPA (1013.25)\n\nAdafruit_BME280 bme;  \/\/ I2C\n\/\/Adafruit_BME280 bme(BME_CS);  \/\/ hardware SPI\n\/\/Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);  \/\/ software SPI\n\nvoid setup() {\n  Serial.begin(115200);\n  \n  WiFi.begin(ssid, password);\n  Serial.println(\"Connecting\");\n  while(WiFi.status() != WL_CONNECTED) { \n    delay(500);\n    Serial.print(\".\");\n  }\n  Serial.println(\"\");\n  Serial.print(\"Connected to WiFi network with IP Address: \");\n  Serial.println(WiFi.localIP());\n\n  \/\/ (you can also pass in a Wire library object like &amp;Wire2)\n  bool status = bme.begin(0x76);\n  if (!status) {\n    Serial.println(\"Could not find a valid BME280 sensor, check wiring or change I2C address!\");\n    while (1);\n  }\n}\n\nvoid loop() {\n  \/\/Check WiFi connection status\n  if(WiFi.status()== WL_CONNECTED){\n    WiFiClient client;\n    HTTPClient http;\n    \n    \/\/ Your Domain name with URL path or IP address with path\n    http.begin(client, serverName);\n    \n    \/\/ Specify content-type header\n    http.addHeader(\"Content-Type\", \"application\/x-www-form-urlencoded\");\n    \n    \/\/ Prepare your HTTP POST request data\n    String httpRequestData = \"api_key=\" + apiKeyValue + \"&amp;sensor=\" + sensorName\n                          + \"&amp;location=\" + sensorLocation + \"&amp;value1=\" + String(bme.readTemperature())\n                          + \"&amp;value2=\" + String(bme.readHumidity()) + \"&amp;value3=\" + String(bme.readPressure()\/100.0F) + \"\";\n    Serial.print(\"httpRequestData: \");\n    Serial.println(httpRequestData);\n    \n    \/\/ You can comment the httpRequestData variable above\n    \/\/ then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)\n    \/\/String httpRequestData = \"api_key=tPmAT5Ab3j7F9&amp;sensor=BME280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14\";\n\n    \/\/ Send HTTP POST request\n    int httpResponseCode = http.POST(httpRequestData);\n     \n    \/\/ If you need an HTTP request with a content type: text\/plain\n    \/\/http.addHeader(\"Content-Type\", \"text\/plain\");\n    \/\/int httpResponseCode = http.POST(\"Hello, World!\");\n    \n    \/\/ If you need an HTTP request with a content type: application\/json, use the following:\n    \/\/http.addHeader(\"Content-Type\", \"application\/json\");\n    \/\/int httpResponseCode = http.POST(\"{\\\"value1\\\":\\\"19\\\",\\\"value2\\\":\\\"67\\\",\\\"value3\\\":\\\"78\\\"}\");\n        \n    if (httpResponseCode&gt;0) {\n      Serial.print(\"HTTP Response code: \");\n      Serial.println(httpResponseCode);\n    }\n    else {\n      Serial.print(\"Error code: \");\n      Serial.println(httpResponseCode);\n    }\n    \/\/ Free resources\n    http.end();\n  }\n  else {\n    Serial.println(\"WiFi Disconnected\");\n  }\n  \/\/Send an HTTP POST request every 30 seconds\n  delay(30000);  \n}\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/RuiSantosdotme\/ESP32-ESP8266-PHP-MySQL\/raw\/master\/code\/ESP32_ESP8266_MySQL_Database_PHP.ino\">View raw code<\/a><\/p>\n<h6>Setting your network credentials<\/h6>\n<p>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.<\/p>\n<pre><code>\/\/ Replace with your network credentials\nconst char* ssid     = \"REPLACE_WITH_YOUR_SSID\";\nconst char* password = \"REPLACE_WITH_YOUR_PASSWORD\";<\/code><\/pre>\n<h6>Setting your serverName<\/h6>\n<p>You also need to type your domain name, so the ESP publishes the readings to your own server.<\/p>\n<pre><code>const char* serverName = \"http:\/\/example-domain.com\/post-esp-data.php\";<\/code><\/pre>\n<p>Now, you can upload the code to your board. It should work straight away both in the ESP32 or ESP8266 board. If you want to learn how the code works, read the next section.<\/p>\n<h6>How the code works<\/h6>\n<p>This project is already quite long, so we won\u2019t cover in detail how the code works, but here\u2019s a quick summary:<\/p>\n<ul>\n<li>Import all the libraries to make it work (it will import either the ESP32 or ESP8266 libraries based on the selected board in your Arduino IDE)\n<li>Set variables that you might want to change (apiKeyValue, sensorName, sensorLocation)\n<li>The apiKeyValue is just a random string that you can modify. It\u2019s used for security reasons, so only anyone that knows your API key can publish data to your database\n<li>Initialize the serial communication for debugging purposes\n<li>Establish a Wi-Fi connection with your router\n<li>Initialize the BME280 to get readings<\/li>\n<\/ul>\n<p>Then, in the loop() is where you actually make the HTTP POST request every 30 seconds with the latest BME280 readings:<\/p>\n<pre><code>\/\/ Your Domain name with URL path or IP address with path\nhttp.begin(client, serverName);\n\n\/\/ Specify content-type header\nhttp.addHeader(\"Content-Type\", \"application\/x-www-form-urlencoded\");\n\n\/\/ Prepare your HTTP POST request data\nString httpRequestData = \"api_key=\" + apiKeyValue + \"&amp;sensor=\" + sensorName                      + \"&amp;location=\" + sensorLocation + \"&amp;value1=\" + String(bme.readTemperature())                      + \"&amp;value2=\" + String(bme.readHumidity()) + \"&amp;value3=\" + String(bme.readPressure()\/100.0F) + \"\";\n\nint httpResponseCode = http.POST(httpRequestData);<\/code><\/pre>\n<p>You can comment the httpRequestData variable above that concatenates all the BME280 readings and use the httpRequestData variable below for testing purposes:<\/p>\n<pre><code>String httpRequestData = \"api_key=tPmAT5Ab3j7F9&amp;sensor=BME280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14\";<\/code><\/pre>\n<h4>Demonstration<\/h4>\n<p>After completing all the steps, let your ESP board collect some readings and publish them to your server.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"421\" alt=\"ESP32 BME280 Arduino IDE MySQL\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-BME280-Arduino-IDE-MySQL.jpg?resize=750%2C421&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>If everything is correct, this is what you should see in your Arduino IDE Serial Monitor:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"828\" height=\"475\" alt=\"ESP32 ESP8266 BME280 Readings Arduino IDE Serial Monitor\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-BME280-Readings-Arduino-IDE-Serial-Monitor.png?resize=828%2C475&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>If you open your domain name in this URL path:<\/p>\n<pre><code>http:\/\/example-domain.com\/esp-data.php<\/code><\/pre>\n<p>You should see the all the readings stored in your database. Refresh the web page to see the latest readings:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"670\" height=\"587\" alt=\"ESP32 ESP8266 View Sensor Readings Webpage PHP\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-View-Sensor-Readings-Webpage-PHP.png?resize=670%2C587&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<p>You can also go to phpMyAdmin to manage the data stored in your SensorData table. You can delete it, edit, etc\u2026<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"688\" height=\"619\" alt=\"ESP32 ESP8266 View Sensor Readings PHPMyAdmin SQL Database\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/06\/ESP32-ESP8266-View-Sensor-Readings-PHPMyAdmin-SQL-Database.png?resize=688%2C619&amp;quality=100&amp;strip=all&amp;ssl=1\"><\/p>\n<h4>Wrapping Up<\/h4>\n<p>In this tutorial you\u2019ve 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 <a href=\"https:\/\/randomnerdtutorials.com\/bluehost\">server and domain name<\/a> (you can use a <a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-raspberry-pi-lamp-server\/\">Raspberry Pi for local access<\/a>).<\/p>\n<p>The example provided is as simple as possible so that you can understand how everything works. After understanding this example, you may change the appearance of the table, publish different sensor readings, publish from multiple ESP boards, and much more.<\/p>\n<p><strong>You might also like reading:<\/strong><\/p>\n<ul>\n<li><strong><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">[Course] <\/a><\/strong><strong><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE<\/a><\/strong>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-publish-sensor-readings-to-google-sheets\/\">ESP32 Publish Sensor Readings to Google Sheets (ESP8266 Compatible)<\/a>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-bluetooth-classic-arduino-ide\/\">ESP32 Bluetooth Classic with Arduino IDE \u2013 Getting Started<\/a>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-web-server-arduino-ide\/\">ESP32 Web Server with Arduino IDE<\/a><\/li>\n<\/ul>\n<p>I hope you liked this project. If you have any questions, post a comment below and we\u2019ll try to get back to you.<\/p>\n<p>If you like ESP32, you might consider enrolling in our course \u201c<a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE<\/a>\u201c. You can also access our free <a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32\/\">ESP32 resources here<\/a>.<\/p>\n<p>Thank you for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this project you\u2019ll build an ESP32 or ESP8266 client that makes an HTTP POST request to a PHP script to insert data (sensor readings) into a MySQL database. You\u2019ll also have a web page that displays the sensor readings, timestamp and other information from the database. You can visualize your data from anywhere in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1],"tags":[],"class_list":["post-26322","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6cOVM-6Qy","_links":{"self":[{"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/posts\/26322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=26322"}],"version-history":[{"count":1,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/posts\/26322\/revisions"}],"predecessor-version":[{"id":26323,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=\/wp\/v2\/posts\/26322\/revisions\/26323"}],"wp:attachment":[{"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=26322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=26322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tom.tomwork.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=26322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}