for my little project I tried posting data using php from soil moisture sensor to my LAMP server on RPi. When i try to post data I get response code -1 and no data is posted to database.
My code in arduino ide (didn't post whole, cause connecting to wifi and getting values works):
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char *ssid = "wifi_ssid";
const char *password = "wifi_passoword";
const char *host = "ip of LAMP server";
//void setup to connect to wifi
void loop() {
HTTPClient http;
String Analog_Value, Moisture, Data;
double A_value;
float moist;
//some code here to get values
Moisture = String(moisture_value);
Analog_Value = String(ADC);
//Post Data
Data = "Moisture=" +Moisture+ "&Analog=" +Analog_Value;
http.begin("LAMP's IP/post.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Serial.println("Data to post:"+Data);
int httpResponseCode = http.POST(Data); //Send the request
String response = http.getString(); //Get the response payload
if (httpResponseCode>0){
Serial.print("Response code");
Serial.println(httpResponseCode); //Print HTTP return code
Serial.println(response); //Print request response payload
}
else {
Serial.print("Response code");
Serial.println(httpResponseCode); //Print HTTP return code
Serial.println("Error");
}
http.end(); //Close connection
delay(5000); //Post Data at every 5 seconds
}
And my php code to post data:
<?php
include 'connect.php';
$d = date("Y-m-d");
$t = date("H:i:sa");
if(!empty($_POST["Moisture"])&& !empty($_POST["Analog"])){
$Moisture = $_POST["Moisture"];
$Analog = $_POST["Analog"];
$sql = "INSERT INTO Moisture (Date, Time, Moisture, Analog_value)
VALUES ('".$d."', '".$t."','".$Moisture."','".$Analog."')";
if ($conn->query($sql) === TRUE) {
echo "Data inserted succesfully";
} else{
echo "Error: " .$sql. " " .$conn->error;
}
}
$conn->close();
?>
In connect.php there is simple script to connect to databse, which works (I tried to manually insert some data to table in that databse and display them with another php script and it works, so problem shouldn't be there);
I watched some tutorials, but nothing has worked for me so far. Any help will be much appreciated.