所以我在过去的几个小时里一直试图理解这个异常,但它一直说插入值列表与列列表不匹配。 这是我的 php 代码:
function insert_data($humidity, $temperature, $sensor_id, $log_time) {
$conn = db_connect(); //connects to database
$sql = "INSERT INTO data(humidity, temperature, log_time, sensor_id)\n"
. "VALUES ($humidity, $temperature, '$log_time', '$sensor_id');";
$statement = $conn -> prepare($sql);
$ok = $statement -> execute();
$conn = null;
return $ok;
}
该函数在这里调用:
<?php
include("lib_db.php");
include("header.php");
if(isset($_POST["data_send"]) && filter_var($_POST["data_send"], FILTER_VALIDATE_BOOLEAN)) {
$sensor_id = $_POST["sensor_id"] ?? '';
$humidity = $_POST["humidity"] ?? '';
$temperature = $_POST["temperature"] ?? '';
$log_time = $_POST["log_time"] ?? '';
$res = insert_data($humidity, $temperature, $sensor_id, $log_time);
if(!$res) throw new ErrorException;
}
$res = select_data();
?>
<div class="container-xxl bg-danger hero-header py-5">
<div class="container-xxl py-5">
<div class="container-xxl py-5 px-lg-5 wow fadeInUp">
<div class="table-responsive">
<table class="table table-hover table-dark">
<thead>
<tr>
<th>#ID</th>
<th>Humidity</th>
<th>Temperature</th>
<th>Log time</th>
<th>#Sensor ID</th>
</tr>
</thead>
<tbody>
<?php if(isset($res)) {
foreach($res as $row) {
?>
<tr>
<td><?= $row["id"]?></td>
<td><?= $row["humidity"]?></td>
<td><?= $row["temperature"]?></td>
<td><?= $row["log_time"]?></td>
<td><?= $row["sensor_id"]?></td>
</tr>
<?php } } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php
include("footer.php");
?>
从帖子中检索的数据是从我测试过且功能正常的外部 C# 应用程序发送的。
我的“数据”表结构是data(id,湿度,温度,log_time,sensor_id) id 是 A-I 密钥。
当我尝试运行插入时,它给了我这个错误:
<b>Fatal error</b>: Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 in C:\UniServerZ\www\Agriculture IOT\digital-agency-html-template\lib_db.php:115
Stack trace:
#0 C:\UniServerZ\www\Agriculture IOT\digital-agency-html-template\lib_db.php(115): PDOStatement->execute()
#1 C:\UniServerZ\www\Agriculture IOT\digital-agency-html-template\sensor_api.php(12): insert_data('48,755359214191', '20,443338532373...', '278e8f10-c667-4...', '2023-12-02 20:0...')
#2 {main}
thrown in <b>C:\UniServerZ\www\Agriculture IOT\digital-agency-html-template\lib_db.php</b> on line <b>115</b><br />
我尝试检查标点符号错误、撇号错误、变量错位和表格结构错误。
我在 PhPmyAdmin 上运行了查询,效果很好。
我在调用堆栈中看到了一些数据值:
insert_data('48,755359214191', '20,443338532373...', '278e8f10-c667-4...', '2023-12-02 20:0...')
因此您的 INSERT 语句最终格式为:
INSERT INTO data(humidity, temperature, log_time, sensor_id)
VALUES (48,755359214191, 20,443338532373, '2023-12-02 20:0...', '278e8f10-c667-4...');
^ ^ ^ ^ ^
我在逗号出现的地方放了
^
。您的两个值包含逗号。在 SQL 语法中,用逗号分隔参数。预期值之间的逗号和值内的逗号是相同的,MySQL 无法区分它们。所以这使得 MySQL 认为您想要在 VALUES
子句中包含 6 个项目,而不是 4 个。
您可以通过使用 SQL 查询参数来解决此问题并防止类似问题,而不是将 PHP 变量插入到 SQL 查询字符串中。