You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino通过PHP脚本向数据库上传数据时仅存入0的问题求助

问题根因

你出现的问题核心是GET请求参数传递方式错误:

  • HTTP协议中GET请求的查询参数必须拼接在URL路径后,格式为/路径?参数名=参数值,服务器不会解析GET请求的请求体内容
  • 你目前把waterlevel=xxx放在了请求体中,PHP的$_GET全局变量只能读取URL中的查询参数,因此拿到的$waterlevel为NULL,插入到数值型数据库字段时会被MySQL自动转换为0,就是你看到的现象
  • 额外问题:你构造GET请求行时用了client.print没有加换行,会导致请求头格式错误,也会影响服务器解析
解决方案

Arduino端修改

调整GET请求构造逻辑,把参数拼到URL中,删除POST请求才需要的Content-Type、Content-Length头和请求体发送代码,修改后的请求部分代码如下:

waterLevelString = "waterlevel=" + (String)waterLevel;
if (client.connect("<snip>", 80)) {
  // 参数拼接在URL后,请求行末尾加换行
  client.print("GET /arduino_connect_to_db.php?");
  client.print(waterLevelString);
  client.println(" HTTP/1.1");
  client.println("Host: <snip>");
  client.println("Connection: close");
  client.println(); // 空行表示请求头结束
}
if (client.connected()) { 
  client.stop();
}

PHP端优化

原有代码存在SQL注入风险,同时增加参数合法性校验,修改后代码如下:

<?php
require_once "sql_connect.php"; 

$connect = @mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);

if(!$connect){
    echo "Error: " . mysqli_connect_error();
    exit();
}

echo "Connection Success!<br><br>";

// 校验参数存在后强转为整数,避免非法值
$waterlevel = isset($_GET["waterlevel"]) ? intval($_GET["waterlevel"]) : 0;
echo "接收参数值:".$waterlevel;

// 使用预处理语句防止SQL注入
$stmt = mysqli_prepare($connect, "INSERT INTO waterLevelTable (waterlevel) VALUES (?)");
mysqli_stmt_bind_param($stmt, "i", $waterlevel);
$result = mysqli_stmt_execute($stmt);

if($result){
    echo "Insertion Success!<br>";
}else{
    echo "插入失败:".mysqli_error($connect);
}
?>
验证方法

修改前可先通过浏览器直接访问http://你的域名/arduino_connect_to_db.php?waterlevel=10,如果数据库能正常存入10,说明PHP逻辑正常,只需修改Arduino端请求逻辑即可。

内容的提问来源于stack exchange,提问作者Blan_C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:24:03