该方案防止sql注入
注意:这里只需建立一次连接,以后都是发数据即可!
案例1:利用简单预处理,往数据库中执行dml语句插入(更新,删除同种方法)信息:preparestatment.php
<?php//创建mysqli对象 $mysqli=new mysqli("localhost","root","123456","test");//创建预编译对象$sql="insert into user (name,password,email,age) html' target='_blank'>values(?,?,?,?)";$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);$mysqli->query("set names utf8");//绑定参数$name="张三";$password="zs";$email="zs@163.com";$age=26;//参数绑定->给?赋值,这里类型和顺序要一致!$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);$a=$mysqli_stmt->execute();if(!$a){die("操作失败".$mysqli_stmt->execute());}else {echo " 操作ok ";}//释放$mysqli->close();
用命令增加的新记录!成功!
如果继续添加,就不需要再执行$mysqli->prepare()了!
现在是只发数据,连接也没断开,这样效率会很高!
<?php//创建mysqli对象 $mysqli=new mysqli("localhost","root","123456","test");//创建预编译对象$sql="insert into user (name,password,email,age) values(?,?,?,?)";$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);$mysqli->query("set names utf8");//绑定参数$name="张三";$password="zs";$email="zs@163.com";$age=26;//参数绑定->给?赋值,这里类型和顺序要一致!$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);$a=$mysqli_stmt->execute();//每一个语句后面都要有一个执行语句!//继续添加$name="李四";$password="ls";$email="ls@sohu.com";$age="58";$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);$a=$mysqli_stmt->execute();$name="王五";$password="ww";$email="ww@sohu.com";$age="109";$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);$a=$mysqli_stmt->execute();if(!$a){die("操作失败".$mysqli_stmt->execute());}else {echo " 操作ok ";}//释放$mysqli->close();
执行时,一次添加3条记录!
案例2:用预处理执行dql语句,查询id>10的用户,如何预防sql注入
<?php//创建mysqli对象$mysqli=new mysqli("localhost","root","123456","test");if(mysqli_connect_error()){die (mysqli_connect_error());}//创建预编译对象$sql="select id,name,email from user where id>?";$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);$mysqli->query("set names utf8");//绑定参数$id=10;//参数绑定->给?赋值,这里类型和顺序要一致!$mysqli_stmt->bind_param("i",$id);//绑定结果集$mysqli_stmt->bind_result($id,$name,$email);//执行$mysqli_stmt->execute();//取出绑定的值while($mysqli_stmt->fetch()){echo "<br/>--$id--$name--$email---";}//关闭资源//释放结果$mysqli_stmt->free_result();//关闭预编译语句$mysqli_stmt->close();//关闭链接$mysqli->close();
Id>10的都列出来了!
地址引用,所以结果能返回回来!
Sql注入的情况:
还有一种方式,用limit命令也可导致!
不小心输入的命令,就可以获取到更多的信息,这对开发者来说,是非常危险的漏洞!
案例3:
<?phpfunction showtable($table_name){$mysqli=new mysqli("localhost","root","123456","test");if (mysqli_connect_error()){die (mysqli_connect_error());}$sql="select * from $table_name";$res=$mysqli->query($sql);echo "共有 行".$res->num_rows."--列=".$res->field_count;$res->free();$mysqli->close();}showtable("user");
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答