PHP的扩展类 mysqli_stmt:预处理类

mysqli和mysqli_result能完成的功能 都可以使用mysqli_stmt类开完成
1.编译一次,使用多次,类似于存储过程
2.参数化查询,可防止sql注入

   1: <?php
   2: header("Content-Type:text/html; charset=utf8");
   3:  
   4: $mysqli = new mysqli("localhost","root","1234","test2");
   5:  
   6: if($mysqli->connect_error)
   7: {
   8:     die("连接数据库出错:".$mysqli->connect_error);
   9: }
  10:  
  11:  
  12: // 增
  13: // $sql = "insert into userinfo(uName,uAge,uPwd) values(?,?,?);";
  14: // 删
  15: // $sql = "delete from userinfo where id=?;";
  16: // 改
  17: // $sql = "update userinfo set uAge=? where Id=?;";
  18: // 查
  19: // $sql = "select top(?) uName,uAge,uPwd from userinfo where id>?;";
  20: $sql = "select uname,uage,upwd from test2.userinfo where id>? limit ?,5";
  21:  
  22:  
  23: //创建预编译对象
  24: $stmt=$mysqli->prepare($sql);
  25:  
  26: //按顺序给点位符绑定值(绑定参数)
  27: //s:string,i:int,d:double,b:二进制大数据类型
  28:  
  29: // 增
  30: // $stmt->bind_param("sis",$uName,$uAge,$uPwd);
  31: // $uName="阿斯顿";
  32: // $uAge=28;
  33: // $uPwd=3557;
  34:  
  35: // 删
  36: // $stmt->bind_param("i",$Id);
  37: // $Id=25;
  38:  
  39: // 改
  40: // $stmt->bind_param("ii",$uAge,$Id);
  41: // $uAge=15;
  42: // $Id=26;
  43:  
  44: // 查
  45: $stmt->bind_param("ii",$Id,$limitNum);
  46: $Id=10;
  47: $limitNum=5;
  48:  
  49: $stmt->bind_result($uName,$uAge,$uPwd);
  50:  
  51: //执行
  52: $result = $stmt->execute();
  53: if(!$result) echo "执行语句出错:".$stmt->error;
  54:  
  55: while ($stmt->fetch()) {
  56:     echo "$uName----$uAge----$uPwd
";
  57: }
  58:  
  59: // echo "最后一次添加的数据ID:".$stmt->insert_id."
";
  60: // echo "受影响行数".$stmt->affected_rows."
";//只返回最后一次执行sql受影响的行数
  61:  
  62: $stmt->close();
  63:  
  64:  
  65:  
  66: ?>
原文地址:https://www.cnblogs.com/lt-style/p/3511522.html