• Home
  • Archive
  • Tools
  • Contact Us

The Customize Windows

Technology Journal

  • Cloud Computing
  • Computer
  • Digital Photography
  • Windows 7
  • Archive
  • Cloud Computing
  • Virtualization
  • Computer and Internet
  • Digital Photography
  • Android
  • Sysadmin
  • Electronics
  • Big Data
  • Virtualization
  • Downloads
  • Web Development
  • Apple
  • Android
Advertisement
You are here: Home » How to Send Data from Arduino to MySQL Database

By Abhishek Ghosh March 28, 2019 4:47 am Updated on March 28, 2019

How to Send Data from Arduino to MySQL Database

Advertisement

In our recent past discussions, we have send data from ESP32 Arduino to IBM Watson IoT by either using MQTT or by using HTTP POST. In the same way, we have discussed how with CouchDB we can send data from ESP32 Arduino. Also, we have discussed different types of cloud database for IoT. MySQL is widely used database for PHP driven web applications. We can send data from Arduino, ESP32 to MySQL either by sending a HTTP POST request or by using a connector.

How to Send Data from Arduino to MySQL Database

 

Send Data from Arduino to MySQL Database by HTTP POST

 

Fundamentally this way involves using a PHP script for MySQL CRUD functions. It is kind of dirty way and of course will not be practical many of the use-cases. However, it is easy even with a little known microcontroller! You need a PHP file for keeping the configuration details, such as :

	define('DB_SERVER', 'localhost');
	define('DB_USER', 'USERNAME');
	define('DB_PASSWORD', 'PASSWORD');
	define('DB_NAME', 'database_name');
	define('TB_ENV', 'table_name');

The above file will remain on server. You need another PHP file to handle the incoming data from ESP32 Arduino :

Advertisement

---

include('config.php');
    $conn =  mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_NAME) or die("Unable to connect to MySQL");
    if (mysqli_real_escape_string($conn,$_POST['temperature']) ==NULL ||mysqli_real_escape_string($conn,$_POST['temperature']) ==NAN){
        $temperature="NULL";
    }else{
        $temperature=mysqli_real_escape_string($conn,$_POST['temperature']);
    }
    if (mysqli_real_escape_string($conn,$_POST['humidity']) ==NULL){
        $humidity="NULL";
    }else{
        $humidity=mysqli_real_escape_string($conn,$_POST['humidity']);
    }
    if (mysqli_real_escape_string($conn,$_POST['pressure']) ==NULL){
        $pressure="NULL";
    }else{
        $pressure=mysqli_real_escape_string($conn,$_POST['pressure']);
    }
    if (mysqli_real_escape_string($conn,$_POST['light']) ==NULL){
        $light="NULL";
    }else{
        $light=mysqli_real_escape_string($conn,$_POST['light']);
    }
    $logdate= date("Y-m-d H:i:s");

    $insertSQL="INSERT into ".TB_ENV." (logdate,temperature,humidity,pressure,light) values ('".$logdate."',".$temperature.",".$humidity.",".$pressure.",".$light.")";
    mysqli_query($conn,$insertSQL) or die("INSERT Query has Failed - ".$insertSQL );

?>

Third thing you’ll need is another PHP or HTML file to request data from that `post.php` by HTTP GET to create graph. Part of the code for ESP32 Arduino will be :

…
      HTTPClient http;
      http.begin("YOUR_SERVER/post.php");
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");

      int httpResponseCode = http.POST("temperature=" + String(t) +"&humidity=" + String(h));

      if (httpResponseCode >0){
          //check for a return code - This is more for debugging.
        String response = http.getString();
        Serial.println(httpResponseCode);
        Serial.println(response);
      }
      else{
        Serial.print("Error on sending post");
        Serial.println(httpResponseCode);
      }

      http.end();
…

 

Send Data from Arduino to MySQL Database by Using MySQL Connector

 

For directly writing to MySQL data table from ESP32 Arduino, you’ll need some MySQL connector library, like here is one :

https://github.com/ChuckBell/MySQL_Connector_Arduino

This is example code how to issue a SELECT query and how to read columns and rows :

#include 
#include 
#include 

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(10,0,1,35);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "secret";        // MySQL user login password

// Sample query
char query[] = "SELECT * FROM world.city LIMIT 12";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}


void loop() {
  delay(2000);

  Serial.println("\nRunning SELECT and printing results\n");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(query);
  // Fetch the columns and print them
  column_names *cols = cur_mem->get_columns();
  for (int f = 0; f < cols->num_fields; f++) {
    Serial.print(cols->fields[f]->name);
    if (f < cols->num_fields-1) {
      Serial.print(", ");
    }
  }
  Serial.println();
  // Read the rows and print them
  row_values *row = NULL;
  do {
    row = cur_mem->get_next_row();
    if (row != NULL) {
      for (int f = 0; f < cols->num_fields; f++) {
        Serial.print(row->values[f]);
        if (f < cols->num_fields-1) {
          Serial.print(", ");
        }
      }
      Serial.println();
    }
  } while (row != NULL);
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

Although this way appears easy and advanced, not in all cases we can actually use it.

Tagged With arduino mysql , aurdino mysql , Arduino send data to mysql , how to send arduino data to sql , arduino mysql web server , send data from arduino to mysql , esp32 mysql post send arduino , upload arduino data to db , arduin senddata , arduino sql query

This Article Has Been Shared 192 Times!

Facebook Twitter Pinterest
Abhishek Ghosh

About Abhishek Ghosh

Abhishek Ghosh is a Businessman, Orthopaedic Surgeon, Author and Blogger. You can keep touch with him on Twitter - @AbhishekCTRL.

Here’s what we’ve got for you which might like :

Articles Related to How to Send Data from Arduino to MySQL Database

  • WROOM ESP32 Example Codes For IBM Watson IoT Platform

    Here Are Few WROOM ESP32 Example Codes For IBM Watson IoT Platform So That Anyone Can Get Started With Both of Them Without Huge Experience.

  • Arduino GSM Shield : Getting Started With DIY IoT

    Compared to Wi-Fi Shield, Arduino GSM Shield is Practical as It Opens the Door Towards Real IoT. We Need to Control Things Over Internet.

  • WiFi With Arduino For IoT : ESP8266, ESP32, NodeMCU, Adafruit Feather

    ESP8266 has wider range of models and ESP 01 commonly seen as cheapest. ESP32 has Bluetooth too. NodeMCU, Adafruit Feather has WiFi and Bluetooth.

  • Send Basic Push Message from Arduino ESP32 using Blynk

    How to Send Basic Push Message from Arduino ESP32 using Blynk? With Blynk like web service & library, it is easy to create such basic project.

  • Arduino ESP32 Basic Graphing/Visualization on IBM Watson IoT Platform

    IBM’s IoT platform provides widgets for simple graphing which avoids pushing own application. We can use our example code to get basic temperature graphng.

Additionally, performing a search on this website can help you. Also, we have YouTube Videos.

Take The Conversation Further ...

We'd love to know your thoughts on this article.
Meet the Author over on Twitter to join the conversation right now!

If you want to Advertise on our Article or want a Sponsored Article, you are invited to Contact us.

Contact Us

Subscribe To Our Free Newsletter

You can subscribe to our Free Once a Day, Regular Newsletter by clicking the subscribe button below.

Click To Subscribe

Please Confirm the Subscription When Approval Email Will Arrive in Your Email Inbox as Second Step.

Search this website…

 

Popular Articles

Our Homepage is best place to find popular articles!

Here Are Some Good to Read Articles :

  • Cloud Computing Service Models
  • What is Cloud Computing?
  • Cloud Computing and Social Networks in Mobile Space
  • ARM Processor Architecture
  • What Camera Mode to Choose
  • Indispensable MySQL queries for custom fields in WordPress
  • Windows 7 Speech Recognition Scripting Related Tutorials

Social Networks

  • Pinterest (20K Followers)
  • Twitter (4.9k Followers)
  • Facebook (5.8k Followers)
  • LinkedIn (3.7k Followers)
  • YouTube (1.2k Followers)
  • GitHub (Repository)
  • GitHub (Gists)
Looking to publish sponsored article on our website?

Contact us

Recent Posts

  • What is Inertial Navigation System? January 25, 2021
  • What is Miniaturization? January 24, 2021
  • What is Domain-Driven Design (DDD)? January 23, 2021
  • Top 10 Anti Hacking Software for Microsoft Windows January 22, 2021
  • What is Software Modernization? January 21, 2021

 

About This Article

Cite this article as: Abhishek Ghosh, "How to Send Data from Arduino to MySQL Database," in The Customize Windows, March 28, 2019, January 25, 2021, https://thecustomizewindows.com/2019/03/how-to-send-data-from-arduino-to-mysql-database/.

Source:The Customize Windows, JiMA.in

 

This website uses cookies. If you do not want to allow us to use cookies and/or non-personalized Ads, kindly clear browser cookies after closing this webpage.

Read Cookie Policy.

PC users can consult Corrine Chorney for Security.

Want to know more about us? Read Notability and Mentions & Our Setup.

Copyright © 2021 - The Customize Windows | dESIGNed by The Customize Windows

Copyright  · Privacy Policy  · Advertising Policy  · Terms of Service  · Refund Policy