ESP32 Insert Data into MySQL Database using PHP and Arduino IDE

Paul Marturia
10 min readApr 11, 2021

--

Halo semuanyaa selamat berjumpa kembali para pembaca setia tulisan ini. Pada proyek kali ini kita akan membahas mengenai cara membangun client yang dapat membuat permintaan HTTP POST ke script PHP untuk memasukkan data (pembacaan sensor) ke dalam database MySQL.

Maksudnya gimana sih? Disini kita akan memiliki halaman web yang akan menampilkan pembacaan sensor, stempel waktu, dan informasi lain daripada database. Kita juga dapat melakukan visualisasi data dari mana saja dan kapan saja dengan cara mengakses server yang akan kita bangun.

Ada beberapa hal yang diperlukan dalam membangun server ini, antara lain :

  1. ESP32 yang akan diprogram dengan Arduino.
  2. Server hosting dan nama domain.
  3. Script PHP untuk memasukkan data ke dalam MySQL dan menampilkannya di website.
  4. Database MySQL untuk menyimpan bacaan web.

So, apalagi yang ditunggu? Langsung aja yok kita lakuin!

Hosting PHP Application and MySQL Database

Mula-mula yang akan kita lakukan adalah melakukan hosting pada PHP Application dan database MySQL. Tujuannya apa? Kita dapat memiliki nama domain dan akun hosting kita sendiri yang dapat memungkinkan kita untuk menyimpan pembacaan sensor dari ESP32. Kita juga dapat melakukan visualisasi bacaan dari mana saja dan kapan saja untuk mengakses domain server kita sendiri. Untuk lebih jelasnya, temen-temen bisa lihat ilustrasi berikut ini.

Dari gambar diatas dari pembacaan sensor yang terhubung kita perlu yang namanya domain untuk menaruh database kita. Dilansir dari randomnerdtutorials, ada dua layanan hosting yang disarankan. Berikut rinciannya.

  1. Bluehost. Nama domain tersedia secara gratis untuk paket 3 years.
  2. Digital Ocean. Server Linux yang dikelola melalui baris perintah. Direkomendasikan untuk pengguna tingkat lanjut.

YAH, semuanya bayar ya?! Jadi temen-temen, setelah aku pelajari, ternyata ini tuh BAYAR hueehehe. Kalau kalian ingin merogoh kocek juga ngga apa-apa, tapi aku punya satu lagi nih yang FREE. Kita bisa pilih 000webhost. Ini merupakan layanan free hosting. Daripada bayar, mending cari yang gratisan gak sih? Disini kita bisa create domain, pilih nama sesuka kita, bikin password. Dan voila, kita bisa langsung create database.

Prepare Web Hosting

Tadi kan udah ada tuh yang gratisan, sekarang kita coba masuk ke websitenya. Setelah itu kalian boleh log-in jika sudah punya akun, atau sign-up jika belum memiliki akun.

Setelah itu, kita akan membangun website kita, klik + Create New Site dan ikuti instruksi yang ada.

Preprare MySQL Database

Jadi guys, setelah kalian daftar akun hosting dan udah siap nih nama domainnya yang tadi dari 000webhost, kita bisa langsung masuk ke dashboard. Lalu, ikutilah langkah-langkah berikutnya. Kita akan membuat nama pengguna, kata sandi, dan tabel SQL Anda.

Mula-mula pergi ke Tools > Database Manager > + New Database. (di pojok sebelah kiri).

Lalu, masukkan nama, username, dan password database temen-temen.

Jika sudah create, tunggu hingga selesai, waktunya lumayan lama sih kira2 1–3 menitan.

Setelah itu, klik Manage > PhpMyAdmin.

Nanti kira-kira tampilan awalnya seperti ini, dan kalian klik Tab Databases,

Pastikan kalian menggunakan database yang benar, karena jika tidak akan fatal akibatnya, hehehe. Setelah itu klik Tab SQL.

Setelah itu, masukkan query ini. Query ini berfungsi untuk membuat tabel yang akan kita gunakan nantinya. Kalian bisa copy paste query ini.

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

Setelah itu, klik Go.

Ternyata gabisa guys, kita kena prank! Canda prank.

Coba perhatikan wejangan yang diberikan MySQL.

#1044 — Access denied for user ‘id16582211_paulsdatabase’@’%’ to database ‘information_schema

Nah, jadi tuh kita salah masukin databasenya. Maksudnya, harusnya kita run sql queries nya on database kita, bukan server ‘localhost’. Hayo siapa juga yang salah? WKWKWK

Mari kita ulang kembaliii. Coba perhatikan gambar dibawah ini. Tulisan yang aku highlight kuning harus berdasarkan database kalian ya. Tadi ituh bukan begitu, makanya kita salah gess.

Setelah itu, klik Go. Nanti hasilnya akan seperti ini.

PHP Script HTTP POST - Insert Data in MySQL Database

Pada bagian ini, kita akan melakukan pembuatan script yang bertanggung langsung terhadap permintaan masuk dari ESP32 dan memasukkan data yang tadi telah di request ke dalam MySQL.

Pergi ke files.000webhost.com dan log-in menggunakan website name dan password yang telah temen-temen bikin sebelumnya.

Tampilan awalnya akan seperti ini, kemudian double click pada folder public_html.

Setelah itu, create New File, aku bikin nama index.php dan setelah itu copy paste kode berikut ini.

<?php/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
// REPLACE with your Database name
$dbname = “REPLACE_WITH_YOUR_DATABASE_NAME”;
// REPLACE with Database user
$username = “REPLACE_WITH_YOUR_USERNAME”;
// REPLACE with Database user password
$password = “REPLACE_WITH_YOUR_PASSWORD”;
// Keep this API Key value to be compatible with the ESP32 code provided in the project page.
// If you change this value, the ESP32 sketch needs to match
$api_key_value = “tPmAT5Ab3j7F9”;
$api_key= $sensor = $location = $value1 = $value2 = $value3 = $value4 = $value5 = “”;
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$api_key = test_input($_POST[“api_key”]);
if($api_key == $api_key_value) {
$sensor = test_input($_POST[“sensor”]);
$location = test_input($_POST[“location”]);
$value1 = test_input($_POST[“value1”]);
$value2 = test_input($_POST[“value2”]);
$value3 = test_input($_POST[“value3”]);
$value4 = test_input($_POST[“value4”]);
$value5 = test_input($_POST[“value5”]);

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

$sql = “INSERT INTO SensorData (sensor, location, value1, value2, value3, value4, value5)
VALUES (‘“ . $sensor . “‘, ‘“ . $location . “‘, ‘“ . $value1 . “‘, ‘“ . $value2 . “‘, ‘“ . $value3 . “‘, ‘“ . $value4 . “‘,’” . $value5 . “‘)”;

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;
}

Sebelum kamu save, perlu diperhatikan bahwa kamu harus replace $dbname $username dan $password dengan database name, database user, dan database password kamu. Setelah itu SAVE.

Untuk memastikan bahwa semuanya berjalan dengan lancar, kamu dapat mengakses script nya dengan cara mengakses <nama-domain>/index.php

Sebagai contoh kalau aku https://laesihombing.000webhostapp.com/index.php

Nama domain didapat dari yang pertama kali saat kita membangun website.

Jika hasilnya yang keluar tulisan “No data posted with HTTP POST” maka kamu berhasil melakukannya. YEY, we did it!

PHP Script - Display Database Content

Lalu, pada bagian ini akan dijelaskan cara menampilkan database content ke dalam server.

Kita akan membuat file baru dengan tujuan untuk menampilkan data pada database ke halaman web.

Seperti biasa, buat file dalam folder public_html, dengan nama esp-data.php dan copy code ini.

<!DOCTYPE html>
<html><body>
<?php
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/$servername = "localhost";// REPLACE with your Database name
$dbname = “REPLACE_WITH_YOUR_DATABASE_NAME”;
// REPLACE with Database user
$username = “REPLACE_WITH_YOUR_USERNAME”;
// REPLACE with Database user password
$password = “REPLACE_WITH_YOUR_PASSWORD”;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}$sql = "SELECT id, sensor, location, value1, value2, value3, value4, value5, reading_time FROM SensorData ORDER BY id DESC";echo '<table cellspacing="5" cellpadding="5">
<tr>
<td>ID</td>
<td>Sensor</td>
<td>Location</td>
<td>Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
<td>Value 4</td>
<td>Value 5</td>
<td>Timestamp</td>
</tr>';

if ($result = $conn->query($sql)) {
while ($row = $result->fetch_assoc()) {
$row_id = $row["id"];
$row_sensor = $row["sensor"];
$row_location = $row["location"];
$row_value1 = $row["value1"];
$row_value2 = $row["value2"];
$row_value3 = $row["value3"];
$row_value4 = $row["value4"];
$row_value5 = $row["value5"];
$row_reading_time = $row["reading_time"];
// Uncomment to set timezone to - 1 hour (you can change 1 to any number)
//$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time - 1 hours"));

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

echo '<tr>
<td>' . $row_id . '</td>
<td>' . $row_sensor . '</td>
<td>' . $row_location . '</td>
<td>' . $row_value1 . '</td>
<td>' . $row_value2 . '</td>
<td>' . $row_value3 . '</td>
<td>' . $row_value4 . '</td>
<td>' . $row_value5 . '</td>
<td>' . $row_reading_time . '</td>
</tr>';
}
$result->free();
}$conn->close();
?>
</table>
</body>
</html>

Seperti biasa, sebelum kamu save, perlu diperhatikan bahwa kamu harus replace $dbname $username dan $password dengan database name, database user, dan database password kamu. Setelah itu SAVE.

Untuk memastikan bahwa semuanya berjalan dengan lancar, kamu dapat mengakses script nya dengan cara mengakses <nama-domain>/esp-data.php

Sebagai contoh kalau aku https://laesihombing.000webhostapp.com/esp-data.php

Nama domain didapat dari yang pertama kali saat kita membangun website.

Kalau kamu mendapatkan notifikasi seperti gambar diatas, coba perhatikan lagi nama databasenya, idnya juga harus masukin yaa. Aku juga mendapat hal yang serupa, karena idnya gaikut, padahal saat masukin index.php idnya ngga ikut lancar2 aja..

Kalau masih bingung idnya yang mana, coba scroll lagi ya keatas.

Nah, kalau udah gambar seperti diatas ini, berarti udah bisaaaa.

Prepare ESP32 and Sensor

Siapkan alat-alat yang akan dibutuhkan, yaitu sebagai berikut.

  1. Microcontroller ESP32
  2. Breadboard
  3. Sensor BMP180 (sesuaikan sama sensor yang kalian punya)
  4. Kabel Jumper
  5. Kabel USB dan Laptop

Kalau udah siap, coba perhatiin dulu gambar skema diagram berikut ini.

Lalu, ikutilah rangkaiannya.

Nah jika sudah, pastikan kalian sudah menginstall board serta library dari sensor dan Adafruit (seharusnya kalau temen2 ikutin medium aku dari awal harusnya udah install).

Copy paste kode berikut ini.

/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

*/

#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085.h>
// Replace with your network credentials
const char* ssid = "Insert your wifi name";
const char* password = "Insert your wifi password";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://example-domain.com/index.php";
// Keep this API Key value to be compatible with the PHP code provided in the project page.
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key
String apiKeyValue = "tPmAT5Ab3j7F9"; String sensorName = "BMP180";
String sensorLocation = "Office";Adafruit_BMP085 bmp;
// I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
// software SPIvoid 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 = bmp.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BMP180 sensor, check wiring or change I2C address!");
while (1);
}
}void loop() {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;

// Your Domain name with URL path or IP address with path
http.begin(serverName);

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

// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
+ "&location=" + sensorLocation
+ "&value1=" + String(bmp.readTemperature())
+ "&value2=" + String(bmp.readPressure()/100.0F)
+ "&value3=" + String(bmp.readAltitude())
+ "&value4=" + String(bmp.readSealevelPressure())
+"&value5=" + String(bmp.readAltitude(102000))+ "";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);

// You can comment the httpRequestData variable above
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
//String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);

// If you need an HTTP request with a content type: text/plain
//http.addHeader("Content-Type", "text/plain");
//int httpResponseCode = http.POST("Hello, World!");

// If you need an HTTP request with a content type: application/json, use the following:
//http.addHeader("Content-Type", "application/json");
//int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");

if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
//Send an HTTP POST request every 30 seconds
delay(15000);
}

Jangan lupa untuk mengganti kredensial temen-temen semua, seperti nama SSID dan passwordnya.

// Replace with your network credentials
const char* ssid = "Insert your wifi name";
const char* password = "Insert your wifi password";

Jangan lupa juga untuk mengganti nama server temen-temen semua, yang index.php yaa.

const char* serverName = “http://example-domain.com/index.php";

Okeyy sekian dulu ya teman-teman, terima kasih sudah menyimakkk, thankyou!

Sumber.

--

--

No responses yet