I am doing my school work to send sensor data to PHP. I'm using Wamp server and phpMyAdmin. I have connected NodeMCU WIFI and saw a data but I can't save data in my DB.
The error says:
GET FAILED, error no: -1, error: connection refused
Here's my code:
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
int value=analogRead(A0);
int heartbeat=int(60/(float(value)/1000));
float heart = heartbeat;
float temp = mlx.readObjectTempC();
String phpHost =host;
phpHost+="/DogSensor_pre.php?temp=" + String(temp) + "&heart=" + String(heart);
Serial.print("Connect to ");
Serial.println(phpHost);
http.begin(phpHost);
int httpCode = http.GET();
http.setTimeout(3000);
if(httpCode > 0) {
Serial.printf("GET code : %d\n\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
}
else {
Serial.printf("GET failed, error no: %d, error: %s\n", httpCode , http.errorToString(httpCode).c_str());
}
http.end();
}
}
<?php
$servername="*****";
$username="******";
$password="*****";
$dbname="*****";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(mysqli_connect_errno()){
echo "Failed to connect to MySql: ";
mysqli_connect_error();
}
$temp = $_GET["temp"];
$heart = $_GET["heart"];
$sql = "INSERT INTO ****.doghealth_pre(temp, heart) VALUES($temp, $heart)";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
http.GET() continuously has -1 value. I think this is where the problem is, but I'm not an expert in web programming.
How can I solve this problem? How can I fix connection refused error?
Related
I have written a code for my Arduino to read data from sensor and then post to a PHP file called post-data.php, which then the PHP will insert the data into a database.
However, my Arduino does not seemed to be able to post the data or it is not posting it correctly.
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#endif
#define signalPin 12
#define sensorPin A0
const char *ssid = "****";
const char *password = "*****";
const char* serverName = "http://smartswitchfyp.rf.gd/post-data.php";
String apiKeyValue = "*******";
ESP8266WebServer server(80);
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
Serial.print("Configuring access point...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFI connected");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
void loop() {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
sensor();
// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
//String httpRequestData = "api_key=******9&value1=24.75&value2=49.54";
//Serial.print("httpRequestData: ");
//Serial.println(httpRequestData);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(response);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
delay(1000);
}
I have checked that my serverName is correct.
I have tested the post-data.php, and it works fine as there is an update at my database. Below is the test code, test.php I used to test post-data.php
<html>
<body>
<form action="post-data.php" method="post">
api: <input type="text" name="api_key">
Name: <input type="text" name="value1">
Email: <input type="text" name="value2">
<input type="submit">
</form>
</body>
</html>
And below is my post-data.php file
<?php
$servername = "sql101.epizy.com";
$dbname = "epiz_28338452_smartswitch";
$username = "epiz_28338452";
$password = "********";
// Keep this API Key value to be compatible with the ESP32 code provided in the project page. If you change this value, the ESP32 sketch needs to match
$api_key_value = "*******";
$api_key = $value1 = $value2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$api_key = test_input($_POST["api_key"]);
if($api_key == $api_key_value) {
$value1 = test_input($_POST["value1"]);
$value2 = test_input($_POST["value2"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Sensor (value1, value2) VALUES ('" . $value1 . "', '" . $value2 . "')";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else {
echo "Wrong API Key provided.";
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm 90% sure that is not the post-data.php file problem but my Arduino not able to post the data to the php file.
At my Arduino code, I used the line
http.begin(serverName);
to connect to the post-data.php and then prepare the header:
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
and prepare the content:
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
where current and power is process in other function/method. I have tested the current and power output, and they are float variables. Finally I used the line
int httpResponseCode = http.POST(httpRequestData);
to post the 3 data to the php file.
When I startup the Arduino, the output shows HTTP Response code: 200, which I believe the php file was successfully called (correct me if I am wrong). However, my database does not have any data inserted. Again the test.php prove that the database can be inserted with data.
Below is image of the database value inserted by the test.php file
Can anyone help me as I'm not sure what cause the Arduino to not able to post the data. Thanks!
you can't access your infinity free site with your arduino because infinity free have a security system
see https://support.infinityfree.net/websites/what-is-the-i-1-suffix/ for more info
Kindly help me in my code. I have arduino code that is sending and getting data from mySql. It is running well and storing data to the database. The problem is that, if I switch ON the button the value 1 is stored in the database, but when I switch OFF the button the value 0 is not stored in the database.
Here is my arduino code:
//Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
s.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
bulbOnOff(buttonBulb);
}
int bulbOnOff(int buttonBulb) {
unsigned long currentMillis = millis();
// protect against overflow
if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
//Serial.println(!buttonBulb);
currentStatus = buttonBulb;
// update database here
if(s.available()>0)
{
s.write(!buttonBulb);
}
lastMillis = currentMillis;
}
}
return 0;
}
The following is nodeMCU ESP8266 code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone"; // Your wifi Name
const char* password = "Qaser.shah.123"; // Your wifi Password
const char *host = "172.20.10.6"; //Your pc or server (database) IP, example : 192.168.0.0 , if you are a windows os user, open cmd, then type ipconfig then look at IPv4 Address.
void setup() {
// put your setup code here, to run once:
wifiConnection();
s.begin(115200);
}
int wifiConnection() {
pinMode(Led_OnBoard, OUTPUT); // Initialize the Led_OnBoard pin as an output
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
digitalWrite(Led_OnBoard, HIGH);
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected to Network/SSID");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
s.write("s");
if (s.available() > 0)
{
buttonBulb = s.read();
Serial.println(buttonBulb);
int result = updateDatabase(buttonBulb);
if(result != 0){
//error updating database
Serial.print("error updating database");
}
}
}
int updateDatabase(int buttonBulb){
HTTPClient http; //Declare object of class HTTPClient
//String ButtonState;
String buttonValueSend, postData;
buttonValueSend = String(buttonBulb); //String to interger conversion
//Post Data
postData = "buttonBulb=" + buttonValueSend;
http.begin("http://172.20.10.6/Nodemcu_db_record_view/InsertDB.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
http.end(); //Close connection
return 0;
}
The following is my php code which stores the Arduino data
<?php
//Creates new record as per request
//Connect to database
$servername = "localhost"; //example = localhost or 192.168.0.0
$username = "root"; //example = root
$password = "";
$dbname = "automation";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
//Get current date and time
date_default_timezone_set('Asia/Karachi');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_POST['buttonBulb']))
{
$buttonBulb = $_POST['buttonBulb'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
See the image of output
In this image OK is printing at Value 1 but not printing OK at value 0
I think there is something wrong or I forgot something, that is why it is not happening.
Thanks a lot for any appericiation.
You can create a separate function to update the database and only call the update when the button state is changed.
Combined with my answer on your previous question it would look like this:
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database
int result = updateDatabase(buttonBulb);
if (result != 0) {
// error updating database
}
}
lastMillis = currentMillis;
}
}
int updateDatabase(int buttonvalue) {
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
buttonValueSend = String(buttonvalue); //String to integer conversion
// ...
http.end(); //Close connection
return 0; // for example return 0 on success, -1 on error
}
I have found the problem. The problem was in my php code that is why the 1 will stored in the database but 0 would not.
Here is what I have change in php code
I just removed if(!empty(&_POST['buttonBulb'])){}
The code that was used in if statement now it is outside from if statement.
Reason
The behind that, when I send 1 to this code it is OK but if send 0 the is statement assumes there is no value and buttonBulb variable is empty.
Thankyou all of you who help me in this code. Now I am going to next step of this project and if I have some problems I will ask.
Specially thanks to #Danny_ds
I'm currently doing a project regarding an attendance system using arduino uno and Ethernet shield. For now I have successfully saved the id I get from arduino to the database. My problem is how to make an alert or popup message that says the data has been received and stored in the database every time I receive data from arduino.
Thank you.
Below is my arduino code:
if (client.connect(myServer, 80)) {
Serial.println("Connecting to Database server");
// send the HTTP PUT request:
client.print("GET /school/inc/jaripelajar.php?P_ID=");
client.print(P_ID);
client.println(" HTTP/1.1");
client.println("Host: 192.168.137.1");
client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
}
php code
// GET request
if (isset($_GET['P_ID'])){
$data1 = $_GET['P_ID'];
}
else{
//echo "Data not received";
}
// Initialize connection to MySQL database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully <br>";
//Insert into database
$data1_sql = "INSERT INTO test (P_ID) VALUES ($data1);";
$data1_query = mysqli_query($conn, $data1_sql);
I want to do an HTTP GET request from the Python script to my server. The data I want to send is stored in a variable data.
I am using requests package of python to send it to my PHP page and I am getting the following error
import requests
data=850
r=requests.get("http://xxxxx.org/retrieve.php", params= str(data))
my retrieve.php file is
<?php
if (isset($_GET['data'])){
$data = $_GET['data'];
echo $data;
}
else{
echo "Data not received";
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$f=0;
$data= intval(data);
$sql="select max(ID) from moisture";
$res1 = mysqli_query($conn,$sql);
$row = mysqli_fetch_row($res1);
$ref = $row[0] + 1;
$sql1 = "INSERT INTO moisture VALUES ('$ref' , '$data')";
if (mysqli_query($conn, $sql1))
{
$f=1;
}
else {
$f=0;
}
mysqli_close($conn);
?>
I converted the data to string and then send it. On php script, I am getting the intval of the string but it is storing value '0' instead of '850'
My code is working for any static value that I am assigning to it. But it is not sending the data if I am receiving it from the sensor.
import serial
import requests
ser=serial.Serial('COM12',9600)
while True:
data=ser.readline()
r=requests.get("http://xxxxx.org/retrieve.php", params= data)
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost