Controlling DHT11 Sensor Data with PHP and MySQL

This is the digital era and everything is going to be controlled through robots. In the future, it is not far away that most of our life will controllable with robots. Deployment of this robotic technology is not easy but not impossible too. In this tutorial, I’ll try to teach you controlling DHT11 Sensor Data with PHP and MySQL.

Table of Contents

Introduction to DHT11 Sensor

Basically DHT11 Sensor is Temperature and Humidity Sensor. This sensor can measure the temperature and humidity of any environment. This sensor is used with Arduino.

In the Arduino tutorials archive section, you can find other tutorials that can help you to learn more and more about Arduino. So let’s talk about our today’s topic, which is very interesting because today we shall work on PHP and MySQL to control DHT11 data. We will write a code that gets status from MySQL and based on that information you can stop receiving data or start receiving data.

What is PHP and MySQL?

PHP is a popular server-side scripting language, driver from C++, that is especially suited to web development. For more tutorials on PHP, you can visit our PHP’s tutorials archive.

MySQL is an open-source relational database management system where SQL stands for Structured Query Language. This language is used to manage databases. For MySql tutorials, you can visit our MySQL tutorials archive page.

Problem Statement:

Here is a problem. Let’s suppose you need a system that stores Sensors On/Off status into Database and you have a frontend that will show the current status of that sensor’s ON/OFF. If the sensor’s receiving data status is ON then you can OFF it or if it is OFF you can ON it.

If sensor status is ON then data will start to add into the database otherwise will stop. Later on, these collected data can be viewed in many ways like in the graph, on the list or in the chart, etc.

Solution for Controlling DHT11 Sensor Data with PHP and MySQL

We identify the problem, Now it is next step to find the solution of the problem.. For discussed situation, you have to perform 3 steps to complete this process as follows:

  1. Create a database
  2. Write PHP/HTML/CSS code
  3. Write code for Sensor on WeMos or Arduino

And that’s it. Now let’s begin with step No.1.

Creating MySQL Database for Storing Sensor Data

I assume that you set up a SQL server (maybe XAMPP or WAMP) and now create a database (I created temperature) and add some data.

CREATE TABLE `devices_status` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `device_name` varchar(50) DEFAULT NULL,
  `device_status` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

INSERT INTO `devices_status` VALUES ('1', 'home_sensor', '1');

CREATE TABLE `temps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `temp` int(11) NOT NULL,
  `humidity` int(11) DEFAULT NULL,
  `time` time DEFAULT NULL,
  `dated` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Above SQL queries, shall create 2 tables one for controlling device status and 2nd is for storing sensor data (Temperature and Humidity)

Now let’s move to our send part. We will write some PHP code along with some CSS. First, let’s see what is in PHP code:

PHP Code for Capturing and Storing Data into MySQL

Next, we need to word on PHP code to retrieve SQL stored data and then execute PHP command via SQL statements to show SQL stored data. For this purpose, we need three PHP pages and one inc page, one inc page for storing MySQL connection, one PHP page for getting device status, and the second PHP page for storing data into the database, and the last one is for showing you visual and functional button for sensor status. First of all, see the connection code. It is inc.inc file.

<?php
    $servername = "localhost"; // Server Name 
    $username = "root"; // User/Login of your Server username
    $password = ""; // Password of your Server
    $dbname = "temperature"; // Database Name that you want to create
    // Create connection.....
     $conn	=	mysqli_connect($servername, $username,$password);
    $connection = mysqli_select_db($conn,$dbname);
?>

Please don’t blind copy paste every script change values according to requirements. In the above PHP code, change values as per your server and save it as inc.inc. Now let’s see PHP code that will get status from Database. Copy an paste below code and save it as “get_status.php” without quotes:

<?php
 include_once('inc.inc');
 
 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }
 date_default_timezone_set("Asia/Karachi");
 $device_name = $_GET['device_name'];
 
 $sql = "SELECT device_status FROM devices_status WHERE device_name='$device_name'";
 $result = $conn->query($sql);
 if ($result->num_rows > 0) {
 while($row = $result->fetch_assoc())
 {
 echo $row['device_status'];
 }
 } else {
 echo "Error:" . $sql . "<br>" . $conn->error;
 }
 
 $conn->close();
?>

As you can see we used SQL select statement and where clause here to retrieve data and then used for-loop in PHP to loop through data and then print/echo required columns. This will get the current status of Sensor status and echo it out. On the other side, WeMos will catch this response as 1 or 0 and then perform an action. Our next page is “add_data.php”. It will store data into the database received from WeMos. Code is here:

<?php
    include_once('inc.inc');
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    date_default_timezone_set("Asia/Karachi");
    $val = $_GET['temp'];
    $humd = $_GET['humidity'];
    
    
    
    $date = date('Y-m-d');
    $time = date('H:i:s');
    $sql = "INSERT INTO temps(temp,humidity,dated,time) VALUES ($val,$humd,'$date','$time');";
    
    if ($conn->query($sql) === TRUE) {
        echo "Saved Successfully!";
    } else {
        echo "Error:" . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
?>

Very simple code. Just receiving $_GET[] request from somewhere and then stores it into the database. Now let’s see last page, very interesting, copy and paste this code and save the file as “status_page.php”:

<!DOCTYPE html>
<html lang="en">
    <head>
		<meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
		<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
        <title>Button Switches with Checkboxes and CSS3 Fanciness</title>
 
        <link rel="stylesheet" type="text/css" href="css/style.css" />
<style type="text/css">
body{
background: #614385;  /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #516395, #614385);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #516395, #614385); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

}
</style>
    </head>
    <body style="set_background">
    
    <?php
    include_once('inc.inc');
    
    if(isset($_GET['device_status']))
    {
       $status  =   $_GET['device_status'];
       if($status==1)
       {
        $update_status  =   0;
       }
       elseif($status==0)
       {
        $update_status  =   1;
       }
       $query   =   "UPDATE devices_status SET device_status='$update_status' WHERE device_name='home_sensor'";
       $conn->query($query);
    }

    
    $get_status_sql            =   "SELECT device_status FROM devices_status WHERE device_name='home_sensor'";
    $result         =   $conn->query($get_status_sql);
    
    if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc())
    {
        $current_status = $row['device_status'];
        
        if($current_status == 1)
        {
            $checked    =   'checked';
        }
        else
        {
            $checked    =   '';
        }}}
    
    ?>
    
        <div class="container">
		
			<section class="main">
				<h1 style="text-align: center; padding: 30px; font-size: 35px; font-family: fantasy;">Controll Sensor Data with PHP and MySQL</h1>
				<div class="switch demo3">
					<input onClick="location.href='<?php echo $_SERVER['PHP_SELF']; ?>?device_status=<?php echo $current_status; ?>'" type="checkbox" value="<?php echo $current_status;?>" <?php echo $checked;?> />
                    <label><i></i></label>
                </div>
                <h2 style="text-align: center;">Created by ICE786 Technologies Team </h2>
				
			</section>
			
        </div>

    </body>
</html>

One thing that I want to tell you that visual button, generated with CSS is not my code I downloaded it from HERE

However, PHP and some major changes in mine. For this page, you also need a CSS code. Copy and paste below code create a folder “css” and save in this folder and name it as “style.css”. But remember this is not mine:

@import url('normalize.css');
@import url('demo.css');

/* GLOBALS */

*,
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.switch {
  margin: 50px auto;
  position: relative;
}

.switch label {
  width: 100%;
  height: 100%;
  position: relative;
  display: block;
}

.switch input {
  top: 0; 
  right: 0; 
  bottom: 0; 
  left: 0;
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
  -moz-opacity: 0;
  opacity: 0;
  z-index: 100;
  position: absolute;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

/* DEMO 1 */

.switch.demo1 {
  width: 100px;
  height: 100px;
}

.switch.demo1 label {
  border-radius: 50%;
  background: #eaeaea;
  box-shadow: 
      0 3px 5px rgba(0,0,0,0.25),
      inset 0 1px 0 rgba(255,255,255,0.3),
      inset 0 -5px 5px rgba(100,100,100,0.1),
      inset 0 5px 5px rgba(255,255,255,0.3);
}

.switch.demo1 label:after {
  content: "";
  position: absolute;
  top: -8%; right: -8%; bottom: -8%; left: -8%;
  z-index: -1;
  border-radius: inherit;
  background: #ddd;
  background: -moz-linear-gradient(#ccc, #fff);
  background: -ms-linear-gradient(#ccc, #fff);
  background: -o-linear-gradient(#ccc, #fff);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#ccc), to(#fff));
  background: -webkit-linear-gradient(#ccc, #fff);
  background: linear-gradient(#ccc, #fff);
  box-shadow: 
    inset 0 2px 1px rgba(0,0,0,0.15),
    0 2px 5px rgba(200,200,200,0.1);
}

.switch.demo1 label:before {
  content: "";
  position: absolute;
  width: 20%;
  height: 20%;
  border-radius: inherit;
  left: 40%;
  top: 40%;
  background: #969696;
  background: radial-gradient(40% 35%, #ccc, #969696 60%);
  box-shadow:
      inset 0 2px 4px 1px rgba(0,0,0,0.3),
      0 1px 0 rgba(255,255,255,1),
      inset 0 1px 0 white;
}

.switch.demo1 input:checked ~ label {
  background: #dedede;
  background: -moz-linear-gradient(#dedede, #fdfdfd);
  background: -ms-linear-gradient(#dedede, #fdfdfd);
  background: -o-linear-gradient(#dedede, #fdfdfd);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#dedede), to(#fdfdfd));
  background: -webkit-linear-gradient(#dedede, #fdfdfd);
  background: linear-gradient(#dedede, #fdfdfd);
}

.switch.demo1 input:checked ~ label:before {
  background: #25d025;
  background: radial-gradient(40% 35%, #5aef5a, #25d025 60%);
  box-shadow:
      inset 0 3px 5px 1px rgba(0,0,0,0.1),
      0 1px 0 rgba(255,255,255,0.4),
      0 0 10px 2px rgba(0, 210, 0, 0.5);
}

/* DEMO 2 */

.switch.demo2 {
  width: 50px;
  height: 100px;
}

.switch.demo2 label {
  background: #cbc7bc;
  margin: 0 auto;
  border-radius: 5px;
  box-shadow:
      inset 0 1px 0 white,
      0 0 0 1px #999,
      0 0 5px 1px rgba(0,0,0,0.2),
      0 2px 0 rgba(255,255,255,0.6),
      inset 0 10px 1px #e5e5e5,
      inset 0 11px 0 rgba(255,255,255,0.5),
      inset 0 -45px 3px #ddd;
}

.switch.demo2 label:after {
  content: "";
  position: absolute;
  top: -20px;
  left: -25px;
  bottom: -20px;
  right: -25px;
  background: #ccc;
  background: -moz-linear-gradient(#ddd, #bbb);
  background: -ms-linear-gradient(#ddd, #bbb);
  background: -o-linear-gradient(#ddd, #bbb);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#ddd), to(#bbb));
  background: -webkit-linear-gradient(#ddd, #bbb);
  background: linear-gradient(#ddd, #bbb);
  z-index: -1;
  border-radius: 5px;
  border: 1px solid #bbb;
  box-shadow:
      0 0 5px 1px rgba(0,0,0,0.15),
      0 3px 3px rgba(0,0,0,0.3),
      inset 0 1px 0 rgba(255,255,255,0.5);
}

.switch.demo2 label:before {
  content: "";
  position: absolute;
  width: 8px;
  height: 8px;
  background: #666;
  top: -13px;
  left: 20px;
  border-radius: 50%;
  box-shadow:
      0 120px 0 #666,
      0 1px 0 white,
      0 121px 0 white;
}

.switch.demo2 input:checked ~ label {
  background: #d2cbc3;
  box-shadow:
      inset 0 1px 0 white,
      0 0 0 1px #999,
      0 0 5px 1px rgba(0,0,0,0.2),
      inset 0 -10px 0 #aaa,
      0 2px 0 rgba(255,255,255,0.1),
      inset 0 45px 3px #e0e0E0,
      0 8px 6px rgba(0,0,0,0.18);
}

/* DEMO 3 */

.switch.demo3 {
  width: 180px;
  height: 50px;
}

.switch.demo3 label {
  display: block;
  width: 100%;
  height: 100%;
  background: #a5a39d;
  border-radius: 40px;
  box-shadow:
      inset 0 3px 8px 1px rgba(0,0,0,0.2),
      0 1px 0 rgba(255,255,255,0.5);
}

.switch.demo3 label:after {
  content: "";
  position: absolute;
  z-index: -1;
  top: -8px; right: -8px; bottom: -8px; left: -8px;
  border-radius: inherit;
  background: #ababab;
  background: -moz-linear-gradient(#f2f2f2, #ababab);
  background: -ms-linear-gradient(#f2f2f2, #ababab);
  background: -o-linear-gradient(#f2f2f2, #ababab);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#ababab));
  background: -webkit-linear-gradient(#f2f2f2, #ababab);
  background: linear-gradient(#f2f2f2, #ababab);
  box-shadow: 0 0 10px rgba(0,0,0,0.3),
        0 1px 1px rgba(0,0,0,0.25);
}

.switch.demo3 label:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: -18px; right: -18px; bottom: -18px; left: -18px;
  border-radius: inherit;
  background: #eee;
  background: -moz-linear-gradient(#e5e7e6, #eee);
  background: -ms-linear-gradient(#e5e7e6, #eee);
  background: -o-linear-gradient(#e5e7e6, #eee);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#e5e7e6), to(#eee));
  background: -webkit-linear-gradient(#e5e7e6, #eee);
  background: linear-gradient(#e5e7e6, #eee);
  box-shadow:
      0 1px 0 rgba(255,255,255,0.5);
  -webkit-filter: blur(1px);
  -moz-filter: blur(1px);
  -ms-filter: blur(1px);
  -o-filter: blur(1px);
  filter: blur(1px);
}

.switch.demo3 label i {
  display: block;
  height: 100%;
  width: 60%;
  border-radius: inherit;
  background: silver;
  position: absolute;
  z-index: 2;
  right: 40%;
  top: 0;
  background: #b2ac9e;
  background: -moz-linear-gradient(#f7f2f6, #b2ac9e);
  background: -ms-linear-gradient(#f7f2f6, #b2ac9e);
  background: -o-linear-gradient(#f7f2f6, #b2ac9e);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#f7f2f6), to(#b2ac9e));
  background: -webkit-linear-gradient(#f7f2f6, #b2ac9e);
  background: linear-gradient(#f7f2f6, #b2ac9e);
  box-shadow:
      inset 0 1px 0 white,
      0 0 8px rgba(0,0,0,0.3),
      0 5px 5px rgba(0,0,0,0.2);
}

.switch.demo3 label i:after {
  content: "";
  position: absolute;
  left: 15%;
  top: 25%;
  width: 70%;
  height: 50%;
  background: #d2cbc3;
  background: -moz-linear-gradient(#cbc7bc, #d2cbc3);
  background: -ms-linear-gradient(#cbc7bc, #d2cbc3);
  background: -o-linear-gradient(#cbc7bc, #d2cbc3);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#cbc7bc), to(#d2cbc3));
  background: -webkit-linear-gradient(#cbc7bc, #d2cbc3);
  background: linear-gradient(#cbc7bc, #d2cbc3);
  border-radius: inherit;
}

.switch.demo3 label i:before {
  content: "off";
  text-transform: uppercase;
  font-style: normal;
  font-weight: bold;
  color: rgba(0,0,0,0.4);
  text-shadow: 0 1px 0 #bcb8ae, 0 -1px 0 #97958e;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 24px;
  position: absolute;
  top: 50%;
  margin-top: -12px;
  right: -50%;
}

.switch.demo3 input:checked ~ label {
  background: #9abb82;
}

.switch.demo3 input:checked ~ label i {
  right: -1%;
}

.switch.demo3 input:checked ~ label i:before {
  content: "on";
  right: 115%;
  color: #82a06a;
  text-shadow: 
    0 1px 0 #afcb9b,
    0 -1px 0 #6b8659;
}

/* DEMO 4 */

.switch.demo4 {
  width: 150px;
  height: 150px;
}

.switch.demo4 label {
  border-radius: 50%;
  background: #b2ac9e;
  background: -moz-linear-gradient(#f7f2f6, #b2ac9e);
  background: -ms-linear-gradient(#f7f2f6, #b2ac9e);
  background: -o-linear-gradient(#f7f2f6, #b2ac9e);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#f7f2f6), to(#b2ac9e));
  background: -webkit-linear-gradient(#f7f2f6, #b2ac9e);
  background: linear-gradient(#f7f2f6, #b2ac9e);
  position: relative;
  color: #a5a39d;
  font-size: 70px;
  text-align: center;
  line-height: 150px;

  -webkit-transition: all 0.3s ease-out;
  -moz-transition: all 0.3s ease-out;
  -ms-transition: all 0.3s ease-out;
  -o-transition: all 0.3s ease-out;
  transition: all 0.3s ease-out;

  text-shadow: 0 2px 1px rgba(0,0,0,0.25);

  box-shadow:
    inset 0 2px 3px rgba(255,255,255,0.13),
    0 5px 8px rgba(0,0,0,0.3),
    0 10px 10px 4px rgba(0,0,0,0.3);
  z-index: -1;
}

.switch.demo4 label:after {
  content: ""; 
  position: absolute;
  left: -20px;
  right: -20px;
  top: -20px;
  bottom: -20px;
  z-index: -2;
  border-radius: inherit;
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,0.1),
    0 1px 2px rgba(0,0,0,0.3),
    0 0 10px rgba(0,0,0,0.15);
  
}

.switch.demo4 label:before {
  content: ""; 
  position: absolute;
  left: -10px;
  right: -10px;
  top: -10px;
  bottom: -10px;
  z-index: -1;
  border-radius: inherit;
  box-shadow: inset 0 10px 10px rgba(0,0,0,0.13); 
  -webkit-filter:blur(1px);
  -moz-filter:blur(1px);
  -ms-filter:blur(1px);
  -o-filter:blur(1px);
  filter: blur(1px); 
}

.switch.demo4 input:checked ~ label {
  box-shadow:
    inset 0 2px 3px rgba(255,255,255,0.13),
    0 5px 8px rgba(0,0,0,0.35),
    0 3px 10px 4px rgba(0,0,0,0.2);
  color: #9abb82;
} 

.switch.demo4 .icon-off:after {
  content: "";
  display: block;
  position: absolute;
  width: 70%;
  height: 70%;
  left: 50%;
  top: 50%;
  z-index: -1;
  margin: -35% 0 0 -35%;
  border-radius: 50%;
  background: #d2cbc3;
  background: -moz-linear-gradient(#cbc7bc, #d2cbc3);
  background: -ms-linear-gradient(#cbc7bc, #d2cbc3);
  background: -o-linear-gradient(#cbc7bc, #d2cbc3);
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#cbc7bc), to(#d2cbc3));
  background: -webkit-linear-gradient(#cbc7bc, #d2cbc3);
  background: linear-gradient(#cbc7bc, #d2cbc3);
  box-shadow:
    0 -2px 5px rgba(255,255,255,0.05),
    0 2px 5px rgba(255,255,255,0.1);
}

Now let’s come to WeMos code which is our main target:

Arduino/WeMos Code

//include libraries
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <dht.h>
#define dht_apin D4 // Analog Pin sensor is connected to
dht DHT;
float get_temperature,get_humidity; // Setting up variables
int delay_time  = 3000; // Its mean 3 seconds wait to enter first record

//Access point credentials
const char* ssid        = "Password lyna hay";
const char* pwd         = "Google@007";
String get_status_url   = "http://192.168.8.100/device_controll/get_status.php";
String add_data_url     = "http://192.168.8.100/device_controll/add_data.php";
WiFiServer server(80);  // open port 80 for server connection

void setup() 
{
  Serial.begin(115200); //initialise the serial communication
  delay(20);
  WiFi.begin(ssid, pwd);

   
    //starting the server
    server.begin();

}

void loop()
{
    String device_status  = get_device_status("home_sensor");
    delay(2000);
    WiFiClient client = server.available();
    DHT.read11(dht_apin);
    get_temperature =   DHT.temperature;
    get_humidity    =   DHT.humidity;
    
    if(device_status=="1")
    {
     add_device_data(get_temperature, get_humidity);
    }
    else
    {
      Serial.println("Device Status is going OFF");
      }
    
    delay(delay_time);
      
      
}


///This is the function that will get status of device that is On or Off
void add_device_data(float get_temperature, float get_humidity)
  {
    
        WiFiClient client = server.available();

        HTTPClient http;
        String url = add_data_url+"?temp="+get_temperature+"&humidity="+get_humidity;
        http.begin(url);
        //GET method
        int httpCode = http.GET();
        String payload = http.getString();
        Serial.println(url);
        Serial.println(payload);
        http.end();
        
  
  }


String get_device_status(String device_name)
  {
    
        WiFiClient client = server.available();

        HTTPClient http;
        String url = get_status_url+"?device_name="+device_name;
        http.begin(url);
        int httpCode = http.GET();
        String payload = http.getString();
        Serial.println(url);
        Serial.println(payload);
        return payload;
        
  
  }  

Here is little explanation for this code.

Explanation of Arduino Code

First you connect with WiFi then you get sensor data and then you get status of sensor from MySQL via calling URL and then you add this data into Database via calling URL.

Now open serial monitor and upload this code, I assume that you setup Sensor on WeMos like this:

  1. Plus wire into 3 or 5 volt
  2. Minus wire into G
  3. Data wire into D4 or as you wish.

Browse for “status_page.php” to ON or OFF the sensor data. If status is OFF then your data should not be added into database if ON your sensor data should be added into database. Try toggle the button and check both status by watching serial monitor.

I hope you understand what I explained. However, you are free to comment and ask for anything.

Complete source code is here for download.

Before leaving this page, please take a look at our PHP tutorials

Or if you are interested into MySQL, you can read these tutorials.

Leave a Reply - I will show after approval