1,新建一个user表
create table user(
id int(4) not null primary key auto_increment,
name varchar(255) not null,
pwd varchar(255) not null)
CHARSET=utf8;
2,插入测试数据
INSERT INTO user(name,pwd) VALUES('bobo','bobo');
3,新建一个login.php文件,用来写登录html页面
代码如下:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/5 0005 * Time: 下午 1:12 */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="check.php" method="post"> 用户名:<input type="text" id="name" name="name"/><br> 密码:<input type="password" id="pwd" name="pwd" /><br> <input type="submit" id='login' name='login' value="登录"> </form> </body> </html>
4,新建check.php文件用来获取表单提交数据进行数据库连接处理
代码如下:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/5 0005 * Time: 下午 1:14 */ header('content-type:text/html;charset=utf-8'); $username=$_POST['name']; $pwd=$_POST['pwd']; try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name='{$username}' and pwd='{$pwd}'"; $stmt=$pdo->query($sql); //返回结果集中的行数 echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
浏览器运行结果如下:
输入用户名bobo,密码bobo打印出 1
输入错误的用户名密码打印0
输入注入sql语句'or 1=1#打印还是1,很明显这里错了,没有对sql进行防注入处理
5,第一种方式防注入(?方式)
<?php try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name=? and pwd=?"; $stmt=$pdo->prepare($sql); $stmt->execute(array($username,$pwd)); echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
6,第二种方式(占位符方式)
<?php try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name=:name and pwd=:pwd"; $stmt=$pdo->prepare($sql); $stmt->execute(array(":name"=>$username,":pwd"=>$pwd)); echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
两种方式输入'or 1=1#打印都是0,解决了sql注入问题。