How to avoid mysql injections using PDO

心不动则不痛 提交于 2019-12-11 18:43:31

问题


How can I avoid mysql injections? This is the PHP file I have right now

<?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() .'}}'; 
}


?>

When I put $stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name)); to the code it doesn't work. So how should I do it?


回答1:


Read about pdo prepared statements

Here is an example

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


来源:https://stackoverflow.com/questions/10929047/how-to-avoid-mysql-injections-using-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!