Settings up a dht22 sending to a mysql being displayed on a web page.

Hello all back at it once again with another problem and the lack of my programming skills. I was searching a way online how to post a temperature sensor to a mysql and display it on a web page. I found a lot of stuff out there but nothing I can either get to work or was other sensors. So i decided to piece stuff together and see what happens. I mange to get the arduino and Ethernet to send the dht22 information to mysql and have it display on a web page that database information. But with my arduino lack of skills I'm trying to also send a text displaying a name. So i can identify that this sensor has a dht22 on it or maybe a light sensor. I'm working on a home automation project.

So my problem is I don't know how to send a text saying this "Sensor 1" from the arduino to the php page. I'm below adding my sketches and code. Can someone please help me?

my arduino sketch

#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; // RESERVED MAC ADDRESS

EthernetClient client;

#define DHTPIN 6 // SENSOR PIN
#define DHTTYPE DHT22 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

int t = 0;	// TEMPERATURE VAR
int h = 0;	// HUMIDITY VAR
String data;

void setup() { 
	Serial.begin(115200);

 pinMode(7, OUTPUT);      // sets the digital pin as output
 pinMode(5, OUTPUT);      // sets the digital pin as output
 digitalWrite(7, HIGH);   // sets +5v for the sensor
 digitalWrite(5, LOW);    // sets gnd for the sensor

	if (Ethernet.begin(mac) == 0) {
		Serial.println("Failed to configure Ethernet using DHCP"); 
	}

	dht.begin(); 
	delay(10000); // GIVE THE SENSOR SOME TIME TO START

	h = (int) dht.readHumidity(); 
	t = (int) dht.readTemperature(); 
 data = "";
}

void loop(){
  
currentMillis = millis();
	if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
		previousMillis = currentMillis;
		h = (int) dht.readHumidity();
		t = (int) dht.readTemperature();

	}

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);


if (client.connect("mysite.com",80)) { // REPLACE WITH YOUR SERVER ADDRESS
		client.println("POST /add.php HTTP/1.1"); // path to the add.php file
		client.println("Host: mysite.com"); // SERVER ADDRESS HERE TOO
		client.println("Content-Type: application/x-www-form-urlencoded"); 
		client.print("Content-Length: "); 
		client.println(data.length()); 
		client.println(); 
		client.print(data); 
    Serial.print(t);
    Serial.print("\n");
    Serial.print(h);
    Serial.print("\n");

	} 

	if (client.connected()) { 
		client.stop();	// DISCONNECT FROM THE SERVER
	}

	delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

Here is the php code that interfaces from the arduino to the mysql

<?php
   	include("connect.php");
   	$link=Connection();
$temp1=$_POST["temp1"];
	$press1=$_POST["press1"];
$hum1=$_POST["hum1"];
	$sensorname1=$_POST["sensorname"];
$query="update tempLog set temperature='$temp1',humidity='$hum1',pressure='$press1',user='$sensorname1'";
   	mysql_query($query,$link);
	mysql_close($link);
header("Location: index.php");
?>

I called it sensorname that is what is to the mysql.

and this is the index page that displays all the information from the mysql

<?php

	include("connect.php"); 	
	
	$link=Connection();

	$result=mysql_query("SELECT * FROM `tempLog` ORDER BY `timeStamp` DESC",$link);
?>

<html>
   <head>
      <title>Sensor Data</title>
      <meta http-equiv="refresh" content="15">  
   </head>
<body>
   <h1>Temperature / Humidity / Barometric Pressure Sensor Readings</h1>

   <table border="1" cellspacing="1" cellpadding="1">
		<tr>
			<td>&nbsp;Timestamp&nbsp;</td>
			<td>&nbsp;Temperature 1&nbsp;</td>
			<td>&nbsp;Humidity 1&nbsp;</td>
			<td>&nbsp;Pressure&nbsp;</td>
			<td>&nbsp;Sensor name&nbsp;</td>
		</tr>

      <?php 
		  if($result!==FALSE){
		     while($row = mysql_fetch_array($result)) {
		        printf("<tr><td> &nbsp;%s </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td></tr>", 
		           $row["timeStamp"], $row["temperature"], $row["humidity"], $row["pressure"], $row["sensorname"]);
		     }
		     mysql_free_result($result);
		     mysql_close();
		  }
      ?>
</table>
</body>
</html>

Please someone help me. To add this one part, I'm so lost.

you need to concatenate the sensor name to your data that you send to the server, just like you did with the temperature and humidity.

data = "temp1=";
data.concat(t);
data.concat("&hum1=");
data.concat(h);
data.concat("&sensorname=Sensor1");

based on your existing code, you couldn't imagine you had to add the data?

I'm assuming that your code basically works and it is just your attempt to include the sensor name has failed.

It appears the target column name in the mySql table tempLog is "user":

$query="update tempLog set temperature='$temp1',humidity='$hum1',pressure='$press1',user='$sensorname1'";

and the key name in the http post is "sensorname"

$sensorname1=$_POST["sensorname"];

You'd do something like this:

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

data.concat("&sensorname=Sensor1"); // This will get text "Sensor1" into column "user" in your mySql table tempLog

In your 'index' page, however, the column appears to be called "sensorname". I'd have expected to see "user" there instead.

$row["timeStamp"], $row["temperature"], $row["humidity"], $row["pressure"], $row["sensorname"]);

Edit. Crossed with blh64

Hello i tried to name it user or sensor name or something it got all mixed up and that is what I'm trying to figure out.

updated code.

sketch

#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; // RESERVED MAC ADDRESS

EthernetClient client;

#define DHTPIN 6 // SENSOR PIN
#define DHTTYPE DHT22 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

int t = 0;  // TEMPERATURE VAR
int h = 0;  // HUMIDITY VAR
String data;

void setup() { 
  Serial.begin(115200);

 pinMode(7, OUTPUT);      // sets the digital pin as output
 pinMode(5, OUTPUT);      // sets the digital pin as output
 digitalWrite(7, HIGH);   // sets +5v for the sensor
 digitalWrite(5, LOW);    // sets gnd for the sensor

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP"); 
  }

  dht.begin(); 
  delay(10000); // GIVE THE SENSOR SOME TIME TO START

  h = (int) dht.readHumidity(); 
  t = (int) dht.readTemperature(); 
 data = "";
}

void loop(){
  
currentMillis = millis();
  if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
    previousMillis = currentMillis;
    h = (int) dht.readHumidity();
    t = (int) dht.readTemperature();

  }

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

data.concat("&sensorname=Sensor1");

if (client.connect("mysite.com",80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /add.php HTTP/1.1"); // path to the add.php file
    client.println("Host: mysite.com"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/x-www-form-urlencoded"); 
    client.print("Content-Length: "); 
    client.println(data.length()); 
    client.println(); 
    client.print(data); 
    Serial.print(t);
    Serial.print("\n");
    Serial.print(h);
    Serial.print("\n");

  } 

  if (client.connected()) { 
    client.stop();  // DISCONNECT FROM THE SERVER
  }

  delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

interface php page

<?php
   	include("connect.php");
   	
   	$link=Connection();

	$temp1=$_POST["temp1"];
	$press1=$_POST["press1"];
$hum1=$_POST["hum1"];
	$sensorname=$_POST["sensorname"];
$query="update tempLog set temperature='$temp1',humidity='$hum1',pressure='$press1',user='$sensorname'";
   	mysql_query($query,$link);
	mysql_close($link);

   	header("Location: index.php");
?>

and index page

<?php

	include("connect.php"); 	
	
	$link=Connection();

	$result=mysql_query("SELECT * FROM `tempLog` ORDER BY `timeStamp` DESC",$link);
?>

<html>
   <head>
      <title>Sensor Data</title>
      <meta http-equiv="refresh" content="15">  
   </head>
<body>
   <h1>Temperature / Humidity / Barometric Pressure Sensor Readings</h1>

   <table border="1" cellspacing="1" cellpadding="1">
		<tr>
			<td>&nbsp;Timestamp&nbsp;</td>
			<td>&nbsp;Temperature 1&nbsp;</td>
			<td>&nbsp;Humidity 1&nbsp;</td>
			<td>&nbsp;Pressure&nbsp;</td>
			<td>&nbsp;Sensor name&nbsp;</td>
		</tr>

      <?php 
		  if($result!==FALSE){
		     while($row = mysql_fetch_array($result)) {
		        printf("<tr><td> &nbsp;%s </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td></tr>", 
		           $row["timeStamp"], $row["temperature"], $row["humidity"], $row["pressure"], $row["usensorname"]);
		     }
		     mysql_free_result($result);
		     mysql_close();
		  }
      ?>

   </table>
</body>
</html>

Am i missing anything?

This looks wrong:

$row["usensorname"]

I guess it should be "user" but if you print out the structure of the table tempLog, it should be clear what the column is called.

Okay what I'm next confused about is what to put in the mysql field. The field name i called it sensorname VARCHAR, TEXT, INT? I put the Length/Values as 50 anything i need to add to it?

If you are defining the column in the table, just use varchar(50) as the datatype and accept the defaults for now.

I forgot to add something in the interface add.php page to add the sensor name so i added it then upload it. When i did i got this.

timeStamp temperature humidity pressure sensorname
2018-11-28 16:42:53 28 31 0 Sensor1

It works. Thank you so much i was banging my hand on my desk and Scaring the cat and my wife tried to put a pillow under my head. That didn't to well LOL again thank you so much.

Hello everything is working great. I just wanted to update this post. But i did have one programming question. And i can not figure out a way to do this. but say If the arduino is offline. Is there a way in the php to send something to the arduino and say hey are you still there yes or not? and If yes then it keeps on updating the mysql with the latest information of the dht22. But if the arduino is offline then somehow can send something to the mysql reading zero meaning offline? Is this possible and how could i be able to do it? At this moment when i unplug the arduino and Ethernet the mysql only shows the last reading from the arduino. So i can't really tell if it's still online or offline.

You do it the other way round. The Web server has a time stamp of the last message from the Arduino. When the last message is too old, it displays "Arduino offline" or similar in response to a request instead of the normal temperature and humidity readings.

Hello 6v6gt That is awesome i didn't even think of the timestamp idea. Thank you. That would solve a lot of things.

hello all I'm facing a new problem i never noticed before. it looks like it takes 23 updates before it displays current temperature and humidity same as if it was updating to mysql. I set the delay to upload 7 seconds so if i add it up that means it takes 3 minutes to update and display the current Temperature on serial monitor and mysql. I'm not sure why i never notice this into the other day wondering why when i unplugged the dht22 and still displays the last temperature and not current. my sketch is below.

#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; // RESERVED MAC ADDRESS
EthernetClient client;

#define DHTPIN 6 // SENSOR PIN
#define DHTTYPE DHT22 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

int t = 0;	// TEMPERATURE VAR
int h = 0;	// HUMIDITY VAR
String data;

void setup() { 
	Serial.begin(115200);

 pinMode(7, OUTPUT);      // sets the digital pin as output
 pinMode(5, OUTPUT);      // sets the digital pin as output
 digitalWrite(7, HIGH);   // sets +5v for the sensor
 digitalWrite(5, LOW);    // sets gnd for the sensor

	if (Ethernet.begin(mac) == 0) {
		Serial.println("Failed to configure Ethernet using DHCP"); 
	}

	dht.begin(); 
	delay(10000); // GIVE THE SENSOR SOME TIME TO START

	h = (int) dht.readHumidity(); 
	t = (int) dht.readTemperature(); 

	data = "";
}

void loop(){
       Serial.print("\n");
       Serial.print("t: ");
         Serial.print(t);
           Serial.print("\n");
             Serial.print("\h: ");
               Serial.print(h);
                 Serial.print("\n");

	currentMillis = millis();
	if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
		previousMillis = currentMillis;
		h = (int) dht.readHumidity();
		t = (int) dht.readTemperature();
	}

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);
  
	if (client.connect("mysite.com",80)) { // REPLACE WITH YOUR SERVER ADDRESS
		client.println("POST /add.php HTTP/1.1"); // path to the add.php file
		client.println("Host: mysite.com"); // SERVER ADDRESS HERE TOO
		client.println("Content-Type: application/x-www-form-urlencoded"); 
		client.print("Content-Length: "); 
		client.println(data.length()); 
		client.println(); 
		client.print(data);
    Serial.print(data); 

	} 

	if (client.connected()) { 
		client.stop();	// DISCONNECT FROM THE SERVER
	}

	delay(7000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

Sounds odd. Some service providers (like Thingspeak) allow some free use, but restrict the number of posts you can make in a period unless you subscribe to a paid service. Or maybe they regard a post every seven seconds as a "denial of service" attack attempt and block it.

I found out what it is.

long interval = 250000; // READING INTERVAL

Is set way to high. I set it for 1 second reading and it works now with no problem and updating to mysql with no problem on the current information.

Well i came across my very last problem LOL. where i wanted to put this sensor at I can not run a Ethernet. My self i should of thought about that before i wired it all up and tested it and put all the problems in here. Well i can't say it is a problem being in here because i learn a lot on what i need to learn. So more more i through about it and i came up with the idea of just using a eps8266 with the dht22. So i searched online trying to figure out how can i do the same thing. And i found a site now i can't seem to find it again. But there was a example of Post that help me to get started. So i have added some stuff to the esp from the arduino sketch with the ethernet. And it keeps to kinda transmit But when viewing in the mysql they come up as all zeros. sketch is below so is the output on serial monitor

Sketch

#include <ESP8266WiFi.h>
#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT22 
 
const char* ssid     = "my wifi id";
const char* password = "my wifi password";
const char* host = "mysite.com";
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  delay(100);
  dht.begin();
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password); 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Netmask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
}
void loop() {
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("connecting to ");
  Serial.println(host);

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  String url = "add.php?temp1=" + String(t) + "&hum1="+ String(h) + "&sensor1="+ String("22446688");
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(7000);
  
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  
  Serial.println();
  Serial.println("closing connection");
  delay(3000);
}

Now here is the output.

closing connection
connecting to mysite.com
Requesting URL: /add.php?temp1=30.00&hum1=26.70&sensor1=22446688
HTTP/1.1 302 Moved Temporarily
Date: Tue, 04 Dec 2018 06:49:14 GMT
Server: Apache
Location: index.php
Content-Length: 0
Connection: close
Content-Type: text/html

and here is what the mysql says
2018-12-03 23:52:09 0 0 and nothing for the sensor name

now it looks like it is transmitting. a timestamp did come up with no problem. Just not the temperature or humidity and sensor name. I tired to do it the same way kinda as the Ethernet arduino one. Not sure what to do next. I really need help?

now it looks like it is transmitting. a timestamp

No, you are not transmitting a timestamp. The PHP script, or the MySQL instance, is adding one.

What that reply is telling you is that the GET request was redirected to index.php, which doesn't seem like the kind of script that would write to a database. Show us the add.php script (and some proof that it is being executed) and the index.php script.

If add.php is similar to the PHP code in your opening post, then you appear to be attempting to use HTTP GET to send the file to the web server, but HTTP PUT to receive it.
You can use one or the other method but not both.

C++:
client.print(String("GET ") + url + " HTTP/1.1\r\n" + . . .

PHP:
$press1=$_POST["press1"];

HTTP GET is a bit easier to use because you can test your PHP/Database configuration using a web browser instead of the Arduino.

It does look like your table templog has column timestamp which is automatically created when you insert a new row in the table.

I don't why I feel so messed up i didn't realized that it wasa Get instead of a post. sorry here is a updated sketch i just took the Ethernet one and changed all the Ethernet to the ESP one and this is what i got.

#include <ESP8266WiFi.h>
#include <DHT.h>
#include <SPI.h>

const char* ssid = "SSID";
const char* password = "SSID PASSWORD";

const char* host = "mysite.com";
#define DHTPIN 6 // SENSOR PIN
#define DHTTYPE DHT22 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 1000; // READING INTERVAL

int t = 0;  // TEMPERATURE VAR
int h = 0;  // HUMIDITY VAR
String data;

void setup()
{
  Serial.begin(9600);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  dht.begin(); 
  delay(10000); // GIVE THE SENSOR SOME TIME TO START

  h = (int) dht.readHumidity(); 
  t = (int) dht.readTemperature(); 

}


void loop()
{

  currentMillis = millis();
  if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
    previousMillis = currentMillis;
    h = (int) dht.readHumidity();
    t = (int) dht.readTemperature();
  }

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host: mysite.com");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(data);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

Everything looks like it's working and it is transmitting i think but i get this in the serial monitor.

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16 
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

Not sure what all this is and why i can not see the what i'm transmitting sense I'm Serial printing everything but what I'm transmitting.

In mysql nothing being added.

Your error is a watch dog timer error. This is quite old but it has some recent updates:

Start by deleting the 10 second delay in setup() and accept some rough data. If delays are necessary, many short delays (<500mS) are better than one long delay.

Hello 6v6gt i did take out the 10 second delay and now it looks like it is transmitting.

[Connecting to mysite.com ... connected]
temp1=2147483647&hum1=2147483647

[Disconnected]

I know it's not showing the correct temperature and humidity that is because i have it on the wrong gpio pin.

It is working now. That delay was blocking it looks like. Do i need that delay there? I know the dht22 takes a little time to get ready.