Connect to a php web page using POST

Hello guys, i am trying to store data to a mysql database, however the values from the arduino are not getting passed to the add.php webpage here is my code

Arduino

#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>

String data;

int led = 3;
int DS18S20_Pin = 2;        // Set temperature sensor in pin 2


// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);


// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress server(192,168,1,3); // Your webserver IP

// Initialize the Ethernet client library
// with the IP address and port of the server 
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  
  sensors.begin();
  // start the serial library:
  Serial.begin(9600);
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
pinMode(3, OUTPUT);
}

void loop()
{
  Serial.println("connecting...");

  
  delay(5000);
  
   // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  Serial.print("Requesting temperatures...");
  
 sensors.requestTemperatures(); // Send the command to get temperatures
 
// delay(2000);
  
 int Temp1 = sensors.getTempCByIndex(1);
 int Temp2 = sensors.getTempCByIndex(0);
 int AverageTemp= (Temp1 + Temp2) / 2.0f; 
  

  
  Serial.println("DONE");
  
  Serial.print("Temperature for Device 1 is: ");
  Serial.println(Temp1); // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
  
  Serial.print("Temperature for Device 2 is: ");
  Serial.println(Temp2);
   
  
  Serial.print("Average temp is...");
  Serial.println (AverageTemp);
  
//---------------------------------------------------------------------------------------------------------

int t;
int h;

t=Temp1;
h=Temp2;

 data+="";

data+="temp1=";

data+=(int) Temp1;

data+="&hum1=";

data+=(int) Temp2;

//data+="&submit=Submit";






if (client.connect("192.168.1.3",8083)) { // REPLACE WITH YOUR SERVER ADDRESS

Serial.println("connected to server");
		client.println("POST /home/add.php HTTP/1.1"); 

Serial.println("send to add.php");
		client.println("Host: 192.168.1.3"); // SERVER ADDRESS HERE TOO
		client.println("Content-Type: application/x-www-form-urlencoded"); 
		client.print("Content-Length: "); 
		client.println(data.length()); 
		client.println(); 
		client.println(data); 

Serial.println ("DATA SENDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
client.stop();
}

 else {
    // if you didn't get a connection to the server:
    Serial.println("NO DATA");
  }

Serial.print(data);

data = "";
  
  delay(2000);
  
  
  
  
 
}

connect.php

<?php

	function Connection(){
		$server="localhost";
		$user="root";
		$pass="root";
		$db="arduino";

	   	
		$connection = mysqli_connect($server, $user, $pass );

		if (!$connection) {
	    	die('MySQL ERROR: ' . mysql_error());
		}
		
		mysqli_select_db($connection,"arduino") or die( 'MySQL ERROR: '. mysql_error() );



		return $connection;
	}
?>

index.php

<?php

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

	$result=mysql_query('SELECT * FROM tempLog ORDER BY timeStamp'); //DESC",$link);


?>

<html>
   <head>
      <title>Sensor Data</title>
   </head>
<body>
   <h1>Temperature / moisture sensor readings</h1>

   <table border="1" cellspacing="1" cellpadding="1">
		<tr>
			<td>&nbsp;Timestamp&nbsp;</td>
			<td>&nbsp;Temperature 1&nbsp;</td>
			<td>&nbsp;Moisture 1&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></tr>", 
		           $row["timeStamp"], $row["temperature"], $row["humidity"]);
		     }
		     mysql_free_result($result);
		     mysql_close();
		  }
      ?>

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

add.php

<?php
   	include("connect.php");
   	
   	//$link=Connection();
$link = mysqli_connect($server, $user, $pass );

	$temp1=$_POST['temp1'];
	$hum1=$_POST['hum1'];

if (empty($temp1)) {
    echo '$var is either 0, empty, or not set at all';
}



	$query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

mysql_query($query);
//	mysql_close($link);

if (!$query) {
    die('Invalid query: ' . mysql_error());
}

mysqli_close ($link);

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

Serial print output from arduino

connecting...
Requesting temperatures...DONE
Temperature for Device 1 is: 19
Temperature for Device 2 is: 19
Average temp is...19
connected to server
send to add.php
DATA SENDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
temp1=19&hum1=19connecting...
Requesting temperatures...DONE
Temperature for Device 1 is: 19
Temperature for Device 2 is: 19
Average temp is...19
connected to server
send to add.php
DATA SENDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
temp1=19&hum1=19connecting...

when i access the add.php it displays this message

$var is either 0, empty, or not set at all
Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\Home\add.php:11) in C:\AppServ\www\Home\add.php on line 27

My root directory of my webpage is

192.168.1.3/home/index.php

i am stuck with this problem like forever :confused:

Any help would be greatly appreciated.

Thanks in advance

although you include the file connect.php within your add.php, it only contains a function ( Connection()) But you never call it.

The variables $server, $user, $pass and $db are defined within that function and would be local to it, but nevertheless since you never call the function they are never defined and you are not going to connect to the database server.

I'd suggest you put a form on the add.php that uses itself as the action and uses the post method. Then you can test it using the browser, thus seeing the error messages that the php processor generates.

KenF:
although you include the file connect.php within your add.php, it only contains a function ( Connection()) But you never call it.

The variables $server, $user, $pass and $db are defined within that function and would be local to it, but nevertheless since you never call the function they are never defined and you are not going to connect to the database server.

I'd suggest you put a form on the add.php that uses itself as the action and uses the post method. Then you can test it using the browser, thus seeing the error messages that the php processor generates.

Despite that add.php wouldnt make the connection to the database, shouldnt be able to store a value gotten from the arduino in $temp1 ?

thankss for you reply

Theomv:
Despite that add.php wouldnt make the connection to the database, shouldnt be able to store a value gotten from the arduino in $temp1 ?

thankss for you reply

How? You can't access the database until you make a successful connection.

Replace your add.php with the following then open it from your browser. Then perhaps you'll be able to see what's going on.

<?php
$server="localhost";
$user="root";
$pass="root";
$db="arduino";
?>

<html>
<head>
<title>Test for uploading data</title>
</head>
<body>

<?php
if(isset($_POST['temp1']))
{
  $temp1=$_POST['temp1'];
  $hum1=$_POST['hum1'];
  $link=mysqli_connect($server, $user, $pass );
  if(!$link)
    {echo mysql_error();
     echo "

";
    }
  
  $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

  if(!mysql_query($query))
    {echo mysql_error();
     echo "

";
    }

  mysql_close($link);
}

?>

<form action="add.php" method="POST">
value for temp1

<input type="text" name="temp1">


value for hum1

<input type="text" name="hum1">


<input type="submit">

</form>
</body>
</html>

BTW did you really change the password for root to "root" ?

KenF:
Replace your add.php with the following then open it from your browser. Then perhaps you'll be able to see what's going on.

<?php

$server="localhost";
$user="root";
$pass="root";
$db="arduino";
?>

Test for uploading data <?php if(isset($_POST['temp1'])) {   $temp1=$_POST['temp1'];   $hum1=$_POST['hum1'];   $link=mysqli_connect($server, $user, $pass );   if(!$link)     {echo mysql_error();     echo " ";     }     $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";   if(!mysql_query($query))     {echo mysql_error();     echo " ";     }   mysql_close($link); } ?> value for temp1

value for hum1

> ``` > > > > BTW did you really change the password for root to "root" ?

I got this error

No database selected


Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in C:\AppServ\www\Home\add.php on line 32
value for temp1

Ok, i fixed the mysql close statement with mysqli_close($link);

So i got this out of the way, however the No database selected is showing up

Well we're almost there then :slight_smile:

Try it like this

<?php
$server="localhost";
$user="root";
$pass="root";
$db="arduino";
?>

<html>
<head>
<title>Test for uploading data</title>
</head>
<body>

<?php
if(isset($_POST['temp1']))
{
  $temp1=$_POST['temp1'];
  $hum1=$_POST['hum1'];
  $link=mysqli_connect($server, $user, $pass );
  if(!$link)
    {echo mysql_error();
     echo "

";
    }
  
  if(!mysqli_select_db($link,"arduino"))
    {echo mysql_error();
     echo "

";
    }


  $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

  if(!mysql_query($query))
    {echo mysql_error();
     echo "

";
    }

   mysqli_close($link);
}

?>

<form action="add.php" method="POST">
value for temp1

<input type="text" name="temp1">


<input type="text" name="hum1">


<input type="submit">

</form>
</body>
</html>

KenF:
Well we're almost there then :slight_smile:

Try it like this

<?php

$server="localhost";
$user="root";
$pass="root";
$db="arduino";
?>

Test for uploading data <?php if(isset($_POST['temp1'])) {   $temp1=$_POST['temp1'];   $hum1=$_POST['hum1'];   $link=mysqli_connect($server, $user, $pass );   if(!$link)     {echo mysql_error();     echo " ";     }     if(!mysqli_select_db($link,"arduino"))     {echo mysql_error();     echo " ";     }   $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";   if(!mysql_query($query))     {echo mysql_error();     echo " ";     }   mysqli_close($link); } ?> value for temp1 > ```

Again the same message, no database selected :S

And you're sure you've actually overwritten the file.

The following part should EITHER successfuly select the database OR give an error message.

 if(!mysqli_select_db($link,"arduino"))
    {echo mysql_error();
     echo "

";
    }

You're sure you "saved changes" !

Theomv:
Again the same message, no database selected :S

I removed the mysql_error() and placed some echoes, the code seems to break after this line

  $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

  if(!mysql_query($query))
    {echo AAAAAAAAAAA;
     echo "

";
    }

And it displays AAAA on the webpage

Actually I've just spotted a problem.

Try this

<?php
$server="localhost";
$user="root";
$pass="root";
$db="arduino";
?>

<html>
<head>
<title>Test for uploading data</title>
</head>
<body>

<?php
if(isset($_POST['temp1']))
{
  $temp1=$_POST['temp1'];
  $hum1=$_POST['hum1'];
  $link=mysqli_connect($server, $user, $pass );
  if(!$link)
    {echo mysql_error();
     echo "

";
    }
  
  if(!mysqli_select_db($link,"arduino"))
    {echo mysql_error();
     echo "

";
    }


  $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

  if(!mysqli_query($link,$query))
    {echo mysql_error();
     echo "

";
    }

  mysql_close($link);
}

?>

<form action="add.php" method="POST">
value for temp1

<input type="text" name="temp1">


<input type="text" name="hum1">


<input type="submit">

</form>
</body>
</html>

IT WORKED!!!!!!!!!!!!!!!!!!!!!

The arduino now sends the data to the database!!!!!!!!!!!!!!!!!!!

the code you send me had an error

The sql close() function it needed mysqli

Then i pressed the submit , no errors, but no data were populating the database

I was about to start crying again , but then i searched the mysqli insert into function

we had $query = "INSERT INTO tempLog('temperature','humidity') VALUES ('$temp1','$hum1')";

The correct one is $query = "INSERT INTO tempLog(temperature,humidity) VALUES ($temp1,$hum1)";

And when i go to see the values on the database the arduino was also storing the values!!!!!!!!!!!!!!!!!!

Hurray! thanks a lot , you made my day!!!!

The apostrophes around the field names should NOT be apostrophes. They should be back ticks. If your field names are not reserved words and have no spaces they are not needed.

In future though, it's good practice to use the back ticks around table names and field names. These are backticks ```` whereas these are appostrophes ' ' ' ' ' ' They look very similar but they're on a completely different key.

Anyhow. Glad to have helped :slight_smile: