【发布时间】:2017-11-13 10:09:55
【问题描述】:
我有一个用 Arduino 语言编程的 NodeMCU。我正在尝试将一些数据从我的传感器发送到我服务器上的 PHP 脚本,然后将数据写入 MySQL 服务器。当通过 URL 运行时,脚本运行良好,但是当我尝试从我的代码中发送值时,我得到了这个错误
200 插入传感器(温度、光线) VALUES ('', '')
SQLSTATE[HY000]:一般错误:1366 不正确的整数值:第 1 行的列 'temp' 的''
现在我知道这是因为没有数据发送到 PHP 脚本,并且空格不是整数。
这是 NodeMCU 上的代码
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200); //Serial connection
WiFi.begin("ssid", "password"); //WiFi connection
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
}
void loop() {
if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://server_public_ip_address/test3.php"); //Specify request destination
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
int httpCode = http.POST("?temp=20&light=88"); //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
http.end(); //Close connection
}else{
Serial.println("Error in WiFi connection");
}
delay(3000); //Send a request every 30 seconds
}
我怀疑问题出在http.addHeader("Content-Type", "text/plain"); 或int httpCode = http.POST("?temp=20&light=88"); 行中。
另外,这只是一个测试程序。最终程序将在这一行 int httpCode = http.POST("?temp=20&light=88"); 中使用变量而不是数字。那我该怎么写呢?
编辑:
也添加 PHP 脚本
<?php
$servername = "localhost";
$username = "root";
$password = "*************";
$dbname = "testbox1";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$temp = $_GET["temp"];
$light = $_GET["light"];
$sql = "INSERT INTO sensor (temp, light)
VALUES ('$temp', '$light')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
【问题讨论】:
标签: php mysql arduino arduino-esp8266