HTTP POST 更新所有行

我有一个项目,我将数据从 ESP32 发送到 MySQL 数据库。我正在使用一个 PHP 脚本来获取 POST 并更新数据库中的数据。脚本如下:


<?php


$servername = "localhost";


// REPLACE with your Database name

$dbname = "licenta";

// REPLACE with Database user

$username = "admin";

// REPLACE with Database user password

$password = "mihnea";


// Keep this API Key value to be compatible with the ESP32 code provided in the project page$

// If you change this value, the ESP32 sketch needs to match

$api_key_value = "tPmAT5Ab3j7F9";


$api_key= $spot = $distance = $vacancy = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $api_key = test_input($_POST["api_key"]);

    if($api_key == $api_key_value) {

        $spot = test_input($_POST["spot"]);

        $distance = test_input($_POST["distance"]);

        $vacancy = test_input($_POST["vacancy"]);


        }


我的问题是,我的脚本不是搜索指定的位置并仅更新该特定行,而是更新所有行。我的数据库是这样构建的:


MariaDB [licenta]> describe SensorData;

+--------------+-----------------+------+-----+---------------------+-------------------------------+

| Field        | Type            | Null | Key | Default             | Extra                         |

+--------------+-----------------+------+-----+---------------------+-------------------------------+

| id           | int(6) unsigned | NO   | PRI | NULL                | auto_increment                |

| spot         | varchar(30)     | NO   |     | NULL                |                               |

| mcu          | varchar(30)     | YES  |     | NULL                |                               |

| distance     | int(6)          | YES  |     | NULL                |                               |

| vacancy      | varchar(10)     | YES  |     | NULL                |                               |

| reading_time | timestamp       | NO   |     | current_timestamp() | on update current_timestamp() |

+--------------+-----------------+------+-----+---------------------+-------------------------------+

如何编写查询,例如,如果我发送 spot = "B1",它将只更新 B1 所在的行。谢谢!


慕村9548890
浏览 126回答 1
1回答

慕姐8265434

您在查询中缺少WHERE条件。$sql您的代码中也有语法错误 - 我想$sql&nbsp;=&nbsp;"UPDATE&nbsp;SensorData&nbsp;SET&nbsp;distance&nbsp;=&nbsp;'"&nbsp;.&nbsp;$distance&nbsp;.&nbsp;"',&nbsp;vacancy&nbsp;=&nbsp;'"&nbsp;.&nbsp;$vacanc$无效。尝试将$sql变量值更改为$sql&nbsp;=&nbsp;"UPDATE&nbsp;SensorData&nbsp;SET&nbsp;distance&nbsp;=&nbsp;'".$distance."',&nbsp;vacancy&nbsp;=&nbsp;'".$vacancy."'&nbsp;WHERE&nbsp;spot&nbsp;=&nbsp;'".$spot."'";
打开App,查看更多内容
随时随地看视频慕课网APP