1

我目前mysql_real_escape_string在查询数据库时使用转义变量以防止 SQL 注入。例如,

   $keyword = mysql_real_escape_string($keyword);
        $guideline = mysql_real_escape_string($guideline);  
        mysql_query("INSERT INTO table1 VALUES('$keyword','$guideline')");

$get = mysql_query("SELECT * FROM table2 WHERE keyword='$keyword'");

  while($row = mysql_fetch_assoc($get)) {
  //code
  }

在阅读了有关 SQL 注入预防的内容后,我读到这还不足以阻止 SQL 注入(现在要检查和纠正这么多代码),我应该使用 PDO 准备好的语句吗?我可以举一个例子来说明如何使用上面相同的 $variables 执行 PDO 准备语句吗?

4

4 回答 4

4

它真的很简单:

$db = new PDO($dsn, $user, $password);
$stmt = $db->prepare('INSERT INTO table1 VALUES(?,?)');
$stmt->execute(array($keyword, $guideline));
$stmt->close();

$stmt2 = $db->prepare('SELECT * FROM table2 WHERE keyword= ?');
$stmt->execute(array($keyword));
while(false !== ($row = $stmt->fetch())) {
   // do stuff
}

请注意,您还可以使用命名占位符,这有助于使您的代码更具可读性,但更冗长:

$stmt2 = $db->prepare('SELECT * FROM table2 WHERE keyword= :keyword');
$stmt2->execute(array(':keyword' => $keyword));
于 2012-07-03T12:35:35.003 回答
3

首先你必须创建一个 PDO 对象:

$dbh = new PDO("mysql:dbname=$dbname", $username, $password);

然后有不同的方法可以将您的参数与您的查询相关联:

  1. 作为一个论点execute()

    $qry = $dbh->prepare("INSERT INTO table1 VALUES(?, ?)");
    $qry->execute(array($keyword, $guideline));
    
  2. 通过绑定值(保留函数调用时分配的值):

    $qry = $dbh->prepare("SELECT * FROM table2 WHERE keyword = ?");
    $qry->bindValue(1, $keyword);
    $qry->execute();
    
    while ($row = $qry->fetch()) {
      // code
    }
    
  3. 通过绑定参数(基础变量更改时更新):

    $qry = $dbh->prepare("SELECT * FROM table2 WHERE keyword = ?");
    $qry->bindParam(1, $keyword);
    $qry->execute();
    
    while ($row = $qry->fetch()) {
      // code
    }
    

您甚至可以使用命名占位符而不是匿名?

$qry = $dbh->prepare("SELECT * FROM table2 WHERE keyword = :kw");
$qry->bindValue(":kw", $keyword);
于 2012-07-03T12:36:01.217 回答
2

这个更有意义

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

http://www.php.net/manual/en/pdo.prepared-statements.php

于 2012-07-03T12:37:54.557 回答
0

这就是我所做的,不是自称是忍者,而是已经做了一段时间了。

//connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

//get Post data
$name = filter_input(INPUT_POST, $name, FILTER_SANITIZE_STRING);

//SQL
$SQL = $conn->prepare('SELECT * FROM users WHERE user_name=:name;');
$SQL->execute(array(':name' => $name));

//While Loop
while($names = $SQL->fetch(PDO::FETCH_OBJ){
 echo $names->user_email
}
于 2012-07-03T12:41:02.437 回答