通过Postman提交数据至Hostinger PHP接口返回成功但数据库无数据
问题分析与解决方案
我帮你排查出了几个核心问题,这就是为什么Postman返回成功但数据没写入数据库的原因:
1. SQL语句语法错误(标识符引号误用)
你在INSERT语句里用单引号'包裹了表名和列名,MySQL中表/列名这类标识符应该用反引号`包裹(或者不包裹,只要不是关键字),单引号会被识别为字符串常量,导致SQL无法找到对应表。
错误写法:
$result = "INSERT INTO 'climate'('temp', 'hum', 'time') VALUES('$temp', '$hum', '$time')";
正确写法:
$sql = "INSERT INTO `climate`(`temp`, `hum`, `time`) VALUES('$temp', '$hum', '$time')";
2. 未实际执行SQL语句
你只是把SQL字符串赋值给了$result变量,根本没有调用数据库连接去执行这条语句!所以if ($result)永远为真(因为非空字符串在PHP中是真值),直接返回成功,但数据库根本没收到插入请求。
需要用mysqli_query()执行SQL:
// 获取数据库连接 $con = $dbo->connect(); // 定义正确的SQL语句 $sql = "INSERT INTO `climate`(`temp`, `hum`, `time`) VALUES('$temp', '$hum', '$time')"; // 执行SQL并获取结果 $result = mysqli_query($con, $sql);
3. 数据库连接未选择目标数据库
你的db_connect.php中的connect()函数只完成了MySQL服务器的连接,没有指定要操作的数据库,导致SQL语句不知道该往哪个库的表里插入数据。
修改connect()函数,加上数据库选择:
function connect() { $filepath = realpath (dirname(__FILE__)); require_once($filepath."/dbconfig.php"); // 连接MySQL服务器 $con = mysqli_connect($dbhost_name, $username, $password); // 新增:选择目标数据库($dbname是你dbconfig.php中定义的数据库名称) mysqli_select_db($con, $dbname); return $con; }
4. URL参数的空格编码问题
你Postman请求中的time参数包含空格(2019-05- 09 08:00:00),URL中的空格需要编码为%20,否则会被服务器截断,导致time参数值异常。
正确的请求URL参数应该是:
time=2019-05-09%2008:00:00
5. 额外建议:修复SQL注入风险
直接将$_GET变量拼入SQL语句存在严重的SQL注入风险,建议使用预处理语句绑定参数,既安全又能避免语法错误:
$con = $dbo->connect(); // 预处理SQL $stmt = $con->prepare("INSERT INTO `climate`(`temp`, `hum`, `time`) VALUES(?, ?, ?)"); // 绑定参数("sss"表示三个字符串类型参数,根据你的字段类型调整,比如用"dds"表示两个浮点数+字符串) $stmt->bind_param("sss", $temp, $hum, $time); // 执行插入 $result = $stmt->execute();
修改后的核心代码示例(insert.php部分)
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $response = array(); if (isset($_GET['temp']) && isset($_GET['hum']) && isset($_GET['time'])) { $temp = $_GET['temp']; $hum = $_GET['hum']; $time = $_GET['time']; $filepath = realpath (dirname(__FILE__)); require_once($filepath."/db_connect.php"); $dbo = new DB_CONNECT(); $con = $dbo->connect(); // 使用预处理语句避免注入 $stmt = $con->prepare("INSERT INTO `climate`(`temp`, `hum`, `time`) VALUES(?, ?, ?)"); $stmt->bind_param("sss", $temp, $hum, $time); $result = $stmt->execute(); if ($result) { $response["success"] = 1; $response["message"] = "climate successfully created."; echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "Failed to insert data: " . mysqli_error($con); // 新增错误信息便于排查 echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "Parameter(s) are missing. Please check the request"; echo json_encode($response); } ?>
按照以上修改后,再用Postman测试,数据应该就能正常写入phpMyAdmin的数据库表了。
内容的提问来源于stack exchange,提问作者M.Saeed
相关产品推荐
相关产品推荐

