时间:2021-07-01 10:21:17 帮助过:21人阅读
下面的是防止sql注入 问号占位
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <?php //造对象 $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root",""); //写SQL语句,预处理语句 $sql = "insert into nation values(?,?)"; //准备SQL语句,返回statement对象 $st = $pdo->prepare($sql); //绑定参数 /*$st->bindParam(1,$code); $st->bindParam(2,$name); $code="n022"; $name="矮人族";*/ $attr = array("n023","魔族"); //直接扔就可以了! //提交执行,不用给SQL语句了,已经传过去了 var_dump($st->execute($attr)); //预处理语句里面用?占位的,给数组的时候要给索引数组 ?> </body> </html>
另一种方法 名称占位
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>无标题文档</title> 6 </head> 7 8 <body> 9 10 <?php 11 12 //造对象 13 $dsn = "mysql:dbname=mydb;host=localhost"; 14 $pdo = new PDO($dsn,"root",""); 15 16 //写SQL语句,预处理语句,使用name占位 17 $sql = "insert into nation values(:code,:name)"; //注意用前面加冒号!! 18 19 //准备执行 20 $st = $pdo->prepare($sql); 21 22 //绑定参数 23 /*$st->bindParam(":code",$code,PDO::PARAM_STR); 24 $st->bindParam(":name",$name,PDO::PARAM_STR); 25 26 $code="n024"; 27 $name="神族";*/ 28 29 $attr = array("code"=>"n025","name"=>"虫族"); 30 31 //执行 32 $st->execute($attr); //注意执行方法 33 34 35 36 ?> 37 </body> 38 </html>
名称占位有点好处就是$_POST[""]提交的值就是处理页面要用的,省去重新赋的步骤
查询
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <?php //造对象 $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root","123"); //写SQL语句,预处理语句 $sql = "select * from nation"; //准备执行 $st = $pdo->prepare($sql); //执行 $st->execute(); //读数据 var_dump($st->fetchAll(PDO::FETCH_ASSOC)); ?> </body> </html>
PDO的基本应用【访问不同的数据库】【事务功能】【防止SQL注入】
标签:div local 名称 var_dump 准备 statement cti 模式 color