IT things

Personal blog about technologies and programming 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. In that post, I am going to share with you, my solution of that.

1 variant. Connecting via PHP script.

In that variant we will create a PHP script, which will connect to MySQL server, select data, show data on page and ESP will parse it  ( if you use another language, just use scheme, and you can build it by yourself). You can see source code behind:

$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:

#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 variant. Connecting directly to database.

In that case you need to install special library, which calles “MYSQL connector” it already contens code examples and everything what would you need. Download connector


  1. Bablofil

    Thanks, great article.

Leave a Reply

Theme by Anders Norén