• 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 740 Times!

Facebook Twitter Pinterest

Abhishek Ghosh

About Abhishek Ghosh

Abhishek Ghosh is a Businessman, 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

Get new posts by email:

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 (24.3K Followers)
  • Twitter (5.8k Followers)
  • Facebook (5.7k Followers)
  • LinkedIn (3.7k Followers)
  • YouTube (1.3k Followers)
  • GitHub (Repository)
  • GitHub (Gists)
Looking to publish sponsored article on our website?

Contact us

Recent Posts

  • The Importance of Voice and Style in Essay Writing April 1, 2023
  • What Online Casinos Have No Deposit Bonus in Australia March 30, 2023
  • Four Foolproof Tips To Never Run Out Of Blog Ideas For Your Website March 28, 2023
  • The Interactive Entertainment Serving as a Tech Proving Ground March 28, 2023
  • Is it Good to Run Apache Web server and MySQL Database on Separate Cloud Servers? March 27, 2023

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, April 1, 2023, https://thecustomizewindows.com/2019/03/how-to-send-data-from-arduino-to-mysql-database/.

Source:The Customize Windows, JiMA.in

PC users can consult Corrine Chorney for Security.

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

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

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

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT