PDO预处理案例

pdo防止sql注入预处理

1.查询



[html]  view plain  copy
 
  1. public function dologin2(){    
  2.     $dsn = "mysql:host=127.0.0.1;dbname=php7";//pdo 连接方法    
  3.     $db = new PDO($dsn, 'root', 'root');    
  4.     $name=$_POST['name'];//$name="zhangsan' or 'a' ='a"    
  5.     $pwd=$_POST['pwd'];    
  6.     /*    
  7.     $count = $db->exec("insert into pdo1(name,pwd) value('$name','$pwd')");    
  8.     echo $count;    
  9.     */    
  10.     $sql="SELECT * FROM pdo1 where name='$name' and pwd='$pwd'";    
  11.     $sql="select * from pdo1 where name = ? and pwd = ?";    
  12.     $stmt = $db->prepare($sql);    
  13.     $exeres = $stmt->execute(array($name,$pwd));    
  14.     if ($exeres) {    
  15.         while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {    
  16.             setcookie('name',$name);    
  17.             redirect("welcome/asdf");    
  18.         }    
  19.     }    
  20.     
  21. }    

2.添加
[html]  view plain  copy
 
  1. <?php    
  2.     header("content-type:text/html;charset=utf-8");    
  3.     $ch = curl_init();    
  4.     $url ='http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=117.89.65.68';    
  5.     $header = array(    
  6.         'apikey: 10d4752cc594de7808c253fccd754832',    
  7.     );    
  8.     curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);    
  9.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
  10.     curl_setopt($ch , CURLOPT_URL , $url);    
  11.     $res = curl_exec($ch);    
  12.     $arr=json_decode($res,true);    
  13.     //print_r($json);die;    
  14.     $dsn = "mysql:host=localhost;dbname=php7";    
  15.     $pdo=new PDO($dsn,'root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND=>'set names utf8'));    
  16.     $stmt=$pdo->prepare("insert into day15(ip,country,city,district,carrier,province)values(:ip,:co,:ci,:di,:ca,:pr)");    
  17.     $stmt->bindparam("ip",$arr['retData']['ip']);    
  18.     $stmt->bindparam("co",$arr['retData']['country']);    
  19.     $stmt->bindparam("ci",$arr['retData']['city']);    
  20.     $stmt->bindparam("di",$arr['retData']['district']);    
  21.     $stmt->bindparam("ca",$arr['retData']['carrier']);    
  22.     $stmt->bindparam("pr",$arr['retData']['province']);    
  23.     if($stmt->execute()){    
  24.         echo "执行成功";    
  25.         echo "最后插入的ID:".$pdo->lastInsertId();    
  26.     }else{    
  27.         echo "执行失败";    
  28.     }    
  29. ?>    

你可能感兴趣的:(PDO预处理案例)