我将一个值从 ESP32 发送到我的 apache 网络服务器,并使用 PHP 脚本将其存储在 MySQL 数据库中。我的 PHP 脚本非常基本并且似乎可以工作,因为 ESP32 发送的值已正确存储在我的数据库中。它应该在我的网页上显示“成功创建新记录”,但事实并非如此。
此外,我在串行监视器上获得了正确的有效负载。
感谢您的帮助!
ESP32代码:
#include <WiFi.h>
#include <HTTPClient.h>
/************************* Wifi Prerequisites **************************/
const char* ssid = "*******";
const char* password = "********";
void wifiConnection(const char* ssid, const char* password);
/**********************************************************************/
/******************* HTTP Request Prerequisites ***********************/
String URL = "http://domain/test.php";
int http_code{};
int test_number{20};
String post_data;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
wifiConnection(ssid, password);
}
void loop() {
// put your main code here, to run repeatedly:
post_data = "number=" + String(test_number);
HTTPClient http;
http.begin(URL);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http_code = http.POST(post_data);
String payload = http.getString();
Serial.print("URL : "); Serial.println(URL);
Serial.print("Data: "); Serial.println(post_data);
Serial.print("httpCode: "); Serial.println(http_code);
Serial.print("Payload: "); Serial.println(payload);
Serial.println("-----------------------------------------");
}
void wifiConnection(const char* ssid, const char* password){
Serial.print("Connecting to ");
Serial.print(ssid);
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
WiFi.begin(ssid, password);
delay(1000);
}
Serial.println();
Serial.print("Connected!");
}
PHP 脚本:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed" . mysqli_connect_error());
}
echo "Database connection is OK<br>";
if(isset($_POST["number"])){
$number = $_POST["number"];
$sql = "INSERT INTO number (number) VALUES ($number);";
}
if(mysqli_query($conn, $sql)){
echo "New Record created successfully";
} else{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
您正在通过 ESP32 发送 POST 请求,并且您的 php 按预期工作。
但是浏览器在加载您的网页时会发送 GET 请求。所以你的
if(isset($_POST["number"]))
陈述是错误的。在这种情况下,变量$sql
甚至没有被创建...