PDO 防注入的原理:将查询语句和具体的参数值分开发送到数据库服务器,在语句执行前参数值不会被解析。

示例代码:

$dbh = new PDO("mysql:host=localhost; dbname=demo", "user", "pass");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的仿真效果
$dbh->exec("set names 'utf8'"); 
$sql="select * from test where name = ? and password = ?";
$stmt = $dbh->prepare($sql); 
$exeres = $stmt->execute(array($testname, $pass)); 
if ($exeres) { 
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    print_r($row);
}
}
$dbh = null;

注意:占位符代替的值只能是需要用户输入的参数值,而不能是一组值(例如 in( ?))、数据表名或列名(例如 order by ?)或其他 sql 语法。

Enjoy it !

相关文章:

  • 2021-06-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-22
  • 2021-12-04
  • 2021-07-05
相关资源
相似解决方案