添加filter_var后,PHP代码在SQL表中插入空值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了添加filter_var后,PHP代码在SQL表中插入空值相关的知识,希望对你有一定的参考价值。
添加filter_var然后清理输入后,我的php代码现在在SQL表中插入空值。我的代码工作正常,但现在不起作用。怎么会?我正在尝试清理输入,因此没有人可以破解我的数据。
<?php
$servername = "localhost";
$username = "****";
$password = "*********";
$dbname = "app";
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = filter_var($firstname, FILTER_SANITIZE_STRING, $_POST["firstname"]);
$lastname = filter_var($lastname, FILTER_SANITIZE_STRING, $_POST["lastname"]);
$email = filter_var($email, FILTER_SANITIZE_EMAIL, $_POST["email"]);
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
答案
看起来你没有将正确的变量传递给filter_var
而不检查数据是否有效。
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");
// Validate input *BEFORE* binding to statement
$firstname = filter_var($_POST["firstname"], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST["lastname"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if ($firstname && $lastname && $email) {
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$stmt->execute();
echo "New records created successfully";
} else {
echo "Failed Data Check: First Name (" . $firstname . ") - Last Name (" . $lastname . ") - EMail (" . $email . ")" ;
}
您可能想要调整最后一个调试行。
以上是关于添加filter_var后,PHP代码在SQL表中插入空值的主要内容,如果未能解决你的问题,请参考以下文章
PHP 的 filter_var FILTER_VALIDATE_EMAIL 真的有效吗?