How can I send data with GET method NodeMCU?

64 Views Asked by At

I have NodeMCU v3 ESP8266 and RFID RC522 card reader. I want to send some data using the insert_status.php API on the server. But it gives an error. What I want to do is very simple, the php API will run and then add the data to the database. Also, to see if the problem might be related to https, I tried it as http and this time it gave me a 301 error.

insert_status.php

<?php
$servername = "localhost";
$username = "test_user";
$password = "test_password";
$dbname = "test_db";

$name = $_GET['name'];
$time = $_GET['time'];
$rfid = $_GET['rfid'];

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO status (name, time, uid) VALUES ('$name', '$time', '$rfid')";
if ($conn->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Code

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <MFRC522.h>
#include <SPI.h>

#define SS_PIN D4
#define RST_PIN D3

char ssid[] = "Qwerty";   
char pass[] = "12345678";       

String serverUrl = "https://website.org/insert_status.php";  
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  while (!Serial);

  Serial.printf("\nConnecting to %s", ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected to network");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
    String rfid = "";
    for (byte i = 0; i < mfrc522.uid.size; i++) {
      rfid += String(mfrc522.uid.uidByte[i], HEX);
    }
    Serial.printf("RFID Code: %s\n", rfid.c_str());

    HTTPClient http;
    String url = serverUrl + "?rfid=" + rfid.c_str() + "&name=TEST" + "&time=TEST_TIME";

    http.begin(url);
    
    int httpCode = http.GET();
    
    if (httpCode > 0) {
      Serial.printf("HTTP durum kodu: %d\n", httpCode);
      if (httpCode == 200) {
        Serial.println("Success!");
      } else {
        Serial.println("Fail!");
      }
    } else {
      Serial.printf("Fail. Error:: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();

    delay(5000); 
  }
}

Result:

��
Connecting to Qwerty...
Connected to network
IP Address: 192.168.43.177
RFID Code: 97****** (I did)
Fail. Error:: connection failed
0

There are 0 best solutions below