PHP阻止SQL注入

PHP阻止SQL注入,php,mysql,pdo,sql-injection,Php,Mysql,Pdo,Sql Injection,我试图阻止使用PHP和PDO进行SQL注入。我把这个作为参考。我的代码没有给我任何错误,但是得到的值都是空的 我试图插入的值不是空的。我知道这一点,因为我已经呼应了他们: echo“\n日期:.$date.”名称:.$Name.”邮件:.$mail.”评论:.$Comment.”网站:.$website $sql = "INSERT post SET timeDate = :timeDate and name = :name and mail = :mail and comment = :com

我试图阻止使用PHP和PDO进行SQL注入。我把这个作为参考。我的代码没有给我任何错误,但是得到的值都是空的

我试图插入的值不是空的。我知道这一点,因为我已经呼应了他们:
echo“\n日期:.$date.”名称:.$Name.”邮件:.$mail.”评论:.$Comment.”网站:.$website

$sql = "INSERT post SET timeDate = :timeDate and name = :name and mail = :mail and comment = :comment and website = :website";
$stmt = $db->prepare($sql);
$stmt->bindParam(":timeDate", $date);
$stmt->bindParam(":name", $name);
$stmt->bindParam(":mail", $mail);
$stmt->bindParam(":comment", $comment);
$stmt->bindParam(":website", $website);
$stmt->execute();

不要使用
,作业之间使用逗号

$sql = "INSERT post
        SET timeDate = :timeDate,
            name = :name,
            mail = :mail,
            comment = :comment,
            website = :website";
在术语之间使用
的语句没有错误,因为该语句实际上是有效的。它只是没有做到你想的那样

就好像你这样做了:

SET timeDate = (:timeDate and name = :name and mail = :mail and comment = :comment and website = :website")
这将仅将timeDate设置为一个长布尔表达式的结果

其他列没有得到任何赋值,它们只是与参数化值进行比较。由于这是一个尚未插入的新行,因此所有其他列自然都为空,因此比较结果将为空。因此,
-将它们组合在一起将为空,这是将分配给
时间日期
列的最终值

其他列在此语句中没有分配任何值,它们的默认值可能为NULL

这是一个奇怪而无用的说法,但严格来说,这不是一个错误

我还鼓励您更简单地使用PDO。您可以将数组传递给
execute()
,而不是对所有内容使用
bindParam()
。这与您为每个参数执行的
bindValue()
操作相同。可以使用命名参数或位置参数执行此操作

$stmt = $db->prepare($sql);
$stmt->execute([
  "timeDate" => $date,
  "name" => $name,
  "mail" => $mail,
  "comment" => $comment,
  "website" => $website]);
如果已经将参数值存储在数组中,则这一点尤其方便


对SQL注入的保护与在旁注中使用
bindParam()

一样好,实际上您不需要这么长且复杂的代码,实际上两行就足够了:
$SQL=“INSERT post SET name=,mail=?”
$db->prepare($sql)->执行([$name,$mail])但是这种注入安全吗?是的,但是您需要添加其他字段以及查询中的其他字段