SQL注入原因
SQL注入的原因是开发人员没有对数据进行严格的筛选,过滤以及书写了不规范的sql语句
举例
已经创建一张user表,存在一条数据username = 'cyx' password = '123'
在sql语句中对于\*
和#
都可以将后面的语句给注释掉
<?php
$host = "127.0.0.1";
$username = "root";
$password = 123;
$database = "game";
$port = 3306;
$mysqli = new mysqli($host, $username, $password, $database,$port);
if ($mysqli->connect_error) {
die ("Connection error :".$mysqli->connect_error);
}
$username = "'cyx'#";//通过sql特性实现注入
//$username = "'cyx' or 1=1";//通过逻辑实现简单注入
$password = "12";
$sql = "select * from user where username = $username and password=$password";//不规范的sql语句
echo $sql;
$res = $mysqli->query($sql);
$mysqli->close();
var_dump($res->num_rows);
解决办法 prepareStatement
+Bind_Variable
什么是
prepareStatement
?
PrepareStatement是预编译的sql语句对象,sql语句被预编译并保存在对象中。被封装的sql语句代表某一类操作,语句中可以包含动态参数“?”,在执行时可以为“?”动态设置参数值。举例
<?php
$host = "127.0.0.1";
$username = "root";
$password = 123;
$database = "game";
$port = 3306;
$mysqli = new mysqli($host, $username, $password, $database,$port);
if ($mysqli->connect_error) {
die ("Connection error :".$mysqli->connect_error);
}
$username = "'cyx";
$password = "123";
$sql = "select * from user where username = ? and password = ?";//绑定变量
echo $sql;
$res = $mysqli->prepare($sql);
$res->bind_param("si", $username, $password);
$res->execute();
$id ="";
$username = "";
$password = "";
$res->bind_result($id,$username,$password);
//显示绑定结果的变量
while($res->fetch()){
echo $id."--".$username."--".$password;//输出 1-cyx-123
}
//关闭数据库的链接
$mysqli->close();
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。