ESP 32 Receiving HTTP Response code: 200 but nothing is inserted to database table

I'm using Arduino Nano ESP32 and Bme680.

When I run the code,

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Wire.h>
#include "bsec.h"

// Replace with your network credentials
const char* ssid     = "XXXX";
const char* password = "XXXX";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "https://example.com/post-data.php";

// Keep this API Key value to be compatible with the post-data.PHP. 
String apiKeyValue = "tPmAxxxxF9";

#define SEALEVELPRESSURE_HPA (1013.25)

void checkIaqSensorStatus(void);
void errLeds(void);

// Create an object of the class Bsec
Bsec iaqSensor; //instantiate the BSEC object
String output;
String httpRequestData;

void setup() {
  /* Initializes the Serial communication */
  Serial.begin(115200);
  Wire.begin(); //initialize I2C communication
  delay(1000);

  /* WiFi Connection*/
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  /*Sensor Connection*/
  pinMode(LED_BUILTIN, OUTPUT);
  iaqSensor.begin(BME68X_I2C_ADDR_LOW, Wire); //initialize BME68X sensor with I2C address and Wire object
  checkIaqSensorStatus();

  bsec_virtual_sensor_t sensorList[7] = 
  {
    BSEC_OUTPUT_IAQ,
    BSEC_OUTPUT_STATIC_IAQ,
    BSEC_OUTPUT_CO2_EQUIVALENT,
    BSEC_OUTPUT_BREATH_VOC_EQUIVALENT,
    BSEC_OUTPUT_RAW_GAS,
    BSEC_OUTPUT_STABILIZATION_STATUS,
    BSEC_OUTPUT_RUN_IN_STATUS
  };

  iaqSensor.updateSubscription(sensorList, 7, BSEC_SAMPLE_RATE_LP); //update subscription with sensor list, size of list, and sample rate
  checkIaqSensorStatus();
}

void loop() {

  /*Check WiFi connection status*/
  if(WiFi.status()== WL_CONNECTED){
    
    WiFiClientSecure *client = new WiFiClientSecure;
    client->setInsecure(); //don't use SSL certificate
    HTTPClient https;

    // Your Domain name with URL path or IP address with path
    https.begin(*client, serverName);

    // Specify content-type header
    https.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    if (iaqSensor.run())
    {
      // Prepare your HTTP POST request data
      httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(iaqSensor.iaq)
                     + "&value2=" + String(iaqSensor.co2Equivalent) + "&value3=" + String(iaqSensor.breathVocEquivalent) + "";

    }
    else 
    {
      checkIaqSensorStatus();
    } 

    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);

    // Send HTTP POST request
    int httpResponseCode = https.POST(httpRequestData);

    if (httpResponseCode>0) 
    {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      Serial.print("HTTP Response: ");
      Serial.println(https.getString());
    }
    else 
    {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }

    // Free resources
    https.end();
    delete client; 
  }
  else 
  {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(1000);  
}

// Helper function definitions
void checkIaqSensorStatus(void)
{
  if (iaqSensor.bsecStatus != BSEC_OK) {
    if (iaqSensor.bsecStatus < BSEC_OK) {
      output = "BSEC error code : " + String(iaqSensor.bsecStatus);
      Serial.println(output);
      for (;;)
        errLeds(); /* Halt in case of failure */
    } else {
      output = "BSEC warning code : " + String(iaqSensor.bsecStatus);
      Serial.println(output);
    }
  }

  if (iaqSensor.bme68xStatus != BME68X_OK) {
    if (iaqSensor.bme68xStatus < BME68X_OK) {
      output = "BME68X error code : " + String(iaqSensor.bme68xStatus);
      Serial.println(output);
      for (;;)
        errLeds(); /* Halt in case of failure */
    } else {
      output = "BME68X warning code : " + String(iaqSensor.bme68xStatus);
      Serial.println(output);
    }
  }
}

void errLeds(void)
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
  delay(100);
}

The serial output prints:
httpRequestData: api_key=tPmAxxxxxF9&value1=50.00&value2=600.00&value3=0.50

HTTP Response code: 200

HTTP Response:

But nothing is inserted to my database table (I'm using Bluehost).

However if I'm sending

curl -X POST -d "api_key=txxxxx&value1=27.88&value2=9.45&value3=1004.7" "https://iotgassensory.com/post-data.php"

in command prompt, it successfully insert the data, so I think my post-data.php file works.

I also receive those in serial output,
HTTP Response:

<html>
<head>
<meta http-equiv='refresh' content='1; url=https://iotgassensory.com/post-data.php?cmd=redirect&arubalp=12345'>
</head>
</html>

Also I'm following Visualize ESP32/ESP8266 Sensor Readings from Anywhere in the World | Random Nerd Tutorials .

is your php really behind https?
can you have your php file return something?

This is my post-data.php file

<?php


ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$servername = "localhost";

// REPLACE with your Database name
$dbname = "vvfaaymy_esp_data";
// REPLACE with Database user
$username = "vvfaaymy_esp_board";
// REPLACE with Database user password
$password = "esp_board_two";

// 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 = "tPxxxxxxj7F9";

$api_key = $value1 = $value2 = $value3 = "";

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"]);
        $value3 = test_input($_POST["value3"]);
        
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql = "INSERT INTO SensorData (value1, value2, value3)
        VALUES ('" . $value1 . "', '" . $value2 . "', '" . $value3 . "')";
        
        if ($conn->query($sql) === 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 not sure if I understand your questions, but using command curl -X POST -d in command prompt did insert data to my database.

this is weird

why would your server redirect the request?

I don't know, it seems in Arduino when I try to do https.POST(httpRequestData);, it automatically redirect to another url

do you control https://iotgassensory.com ?

when you curl there, is it from a command line on a computer in the same ethernet network?

when you try from the Arduino, is it through some sort of open Wifi without the same credentials?

Yes.
I connect to Wifi using network credentials.

I also try to upload data to ThingSpeak, but it returns HTTP error code -303. Do you think it's the Wifi problem, even though Arduino is able to connected it

Did you run the curl command in the same network environment?

do you see any text returned from the curl command?

can you try with

if (WiFi.status() == WL_CONNECTED) {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;

  String url = "https://iotgassensory.com/post-data.php";
  String payload = "api_key=" + apiKey +  "&value1=27.88&value2=9.45&value3=1004.7";
  http.begin(client, url);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    String response = http.getString();
    Serial.println(response);
  } else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }

  http.end();
}

The curl command returns: New record created successfully
This code still return same thing

HTTP Response code: 200
<html>
<head>
<meta http-equiv='refresh' content='1; url=https://iotgassensory.com/post-data.php?cmd=redirect&arubalp=12345'>
</head>
</html>

can you clarify this?

Yes

I solved the problem!!!! It end up that there something wrong with my network and I thought seeing connected means fine so I never doubt that. But I just change it to my hotspot, and it works perfectly fine.

Very appreciate your help.

Glad it’s fixed

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.