PDO预处理语句规避SQL注入攻击
所谓SQL注入式攻击,就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串,欺骗服务器执行恶意的SQL命令。在某些表单中,用户输入的内容直接用来构造(或者影响)动态SQL命令,或作为存储过程的输入参数,这类表单特别容易受到SQL注入式攻击。
第一种方法
<?php $dsn = "mysql:dbname=study;host=localhost"; $pdo = new PDO($dsn,"root","root"); //写一个预处理语句 $sql = "insert into class values(?,?)"; //将预处理语句扔到服务器等待执行,返回PDOStatement对象 $stm = $pdo->prepare($sql); //第二次将变量(参数)扔到服务器的SQL语句相应位置,给预处理语句绑定参数 $stm->bindParam(1,$Sclass); $stm->bindParam(2,$cla); $Sclass = "7"; $cla = "七班"; //执行 $stm->execute();
第一种方法简写
<?php $dsn = "mysql:dbname=study;host=localhost"; $pdo = new PDO($dsn,"root","root"); //写一个预处理语句 $sql = "insert into class values(?,?)"; //将预处理语句扔到服务器等待执行,返回PDOStatement对象 $stm = $pdo->prepare($sql); //定义索引数组 $arr = array("8","八班"); //执行 $stm->execute($arr);
第二种方法
<?php $dsn = "mysql:dbname=study;host=localhost"; $pdo = new PDO($dsn,"root","root"); //预处理语句 $sql = "insert into class VALUES (:Sclass,:cla)"; $stm = $pdo->prepare($sql); //造一个数组 $arr = array("Sclass"=>"10","cla"=>"十班"); //执行 $stm->execute($arr);
举例,第二种情况简单,建议应用第二种方法
<body xmlns="http://www.w3.org/1999/html"> <h1>添加数据</h1> <form action="pdoycl5.php" method="post"/> <div>代号:<input type="text" name="Sclass"> </div> <div>班级:<input type="text" name="cla"> </div> <input type="submit" value="添加"> </form> </body>
<?php $dsn = "mysql:dbname=study;host=localhost"; $pdo = new PDO($dsn,"root","root"); //预处理语句 $sql = "insert into class VALUES (:Sclass,:cla)"; $stm = $pdo->prepare($sql); //执行 $stm->execute($_POST);