如何避免使用PDO进行mysql注入

时间:2012-06-07 09:22:48

标签: php mysql pdo code-injection

如何避免mysql注入?这是我现在的PHP文件

<?php
include 'config.php';

$Name = $_GET['Name'] ;

$sql = "Select * from tables where names =\"$Name\"";



try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->query('SET CHARACTER SET utf8');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->query($sql);  
    $names = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"key":'. json_encode($names) .'}'; 
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}


?>

当我将$stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name));放入代码时,它不起作用。那我该怎么做呢?

1 个答案:

答案 0 :(得分:7)

了解pdo prepared statements

这是一个例子

$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));