我有以下执行SQL更新查询的PHP脚本,如何防止在两个POST值不为空之前执行它?
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);
$delivery_time = addslashes($_POST['delivery_time']);
$customer = addslashes($_POST['customer']);
$sql = "UPDATE Equipment SET time = '$time', customer = '$customer' WHERE status ='Broken' ";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
答案 0 :(得分:0)
警告::您对SQL Injections持开放态度,应该真正使用参数化的准备好的语句,而不是手动构建查询。它们由PDO或MySQLi提供。永远不要相信任何形式的输入,尤其是来自客户端的输入。即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。
为避免在提供$_POST
变量之前发送查询,请使用if
语句和isset
检查变量是否存在。
if (isset($_POST['delivery_time'], $_POST['customer'])) {
$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);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // switch off emulated prepares, but you should add charset=utf8mb4 in the contructor above too
$sql = "UPDATE Equipment SET `time` = ?, `customer` = ? WHERE `status` ='Broken' ";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute([
$_POST['delivery_time'],
$_POST['customer']
]);
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}