PHP从mysql_real_escape_string更改为PDO准备语句

时间:2012-07-03 12:30:55

标签: php mysql

我在查询数据库时使用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预处理语句吗?我可以举例说明如何用上面相同的$变量做PDO预处理语句吗?

4 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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
    }
    
  4. 您甚至可以使用命名占位符而不是匿名?

    $qry = $dbh->prepare("SELECT * FROM table2 WHERE keyword = :kw");
    $qry->bindValue(":kw", $keyword);
    

答案 2 :(得分: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

答案 3 :(得分: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
}