IT things

Blog about techologies and everything else with computer by Andrei Morozov

Electronics, IoT, PHP, Web

Connecting ESP8266 to the MySQL


A lot of people, when they start to make some IoT devices, have a question, how to connect MySQL server to your device, and save the data inside. In that post, I am going to share with you my solution.

1 option. Connecting via PHP script.

In that option we will create a PHP script, which will connect to the MySQL server, select data, show data on page and ESP8266 will parse it (if you use different language, just use scheme, and you can build it by yourself).

Server code (PHP):

$connect = mysqli_connect("localhost", "my_user", "my_password", "my_db");
//Request row from database
$get_data_sql = mysqli_query($connect, "SELECT * FROM `your_table`");
//Creating array with data of that line of db
$get_data_row = mysqli_fetch_array($get_data_sql, MYSQLI_ASSOC);
//Output data which we got
echo $get_data_row['info'];

Code for ESP8266 (C++):

#include Arduino.h

#include ESP8266WiFi.h
#include ESP8266WiFiMulti.h

#include ESP8266HTTPClient.h

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

void setup() {



for (uint8_t t = 4; t 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);

WiFiMulti.addAP("ssid", "password");


String payload;

void loop() {
// wait for WiFi connection
if (( == WL_CONNECTED)) {

HTTPClient http;

USE_SERIAL.print("[HTTP] begin...\n");
// configure traged server and url
http.begin("http://Your_URL"); //HTTP

USE_SERIAL.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();

// httpCode will be negative on error
if (httpCode 0) {
// HTTP header has been send and Server response header has been handled
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

// file found at server
if (httpCode == HTTP_CODE_OK) {
payload = http.getString();

if (payload == "No new requests!") {
} else {
USE_SERIAL.println("Hell, someone sent the request!");

} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());



2 option. Connecting directly to the database.

In that case you would need to install special library, which called “MYSQL connector” it already contents code examples and everything what would you need to work with it. Visit connector’s page

Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.
I agree to have my personal information transfered to MailChimp ( more information )


  1. Bablofil

    Thanks, great article.

Leave a Reply

Enter Captcha Here : *

Reload Image

Theme by Anders Norén