zoukankan      html  css  js  c++  java
  • php mysqli扩展之预处理

      在前一篇 mysqli基础知识中谈到mysqli的安装及基础操作(主要是单条sql语句的查询操作),今天介绍的是mysqli中很重要的一个部分:预处理。

      在mysqli操作中常常涉及到它的三个主要类:MySQLi类,MySQL_STMT类,MySQLi_RESULT类。预处理主要是利用MySQL_STMT类完成的。

      预处理是一种重要的 防止SQL注入的手段,对提高网站安全性有重要意义。

      本文案例为 数据库名为test,数据表名为test,  字段有id ,title 两个,id自增长主键。

     

      使用mysqli预处理执行插入操作:

    <?php 
    
    define("HOST", "localhost");
    define("USER", 'root');
    define("PWD", '');
    define("DB", 'test');
    
    $mysqli=new Mysqli(HOST,USER,PWD,DB);
    
    if ($mysqli->connect_errno) {
        "Connect Error:".$mysqli->connect_error;
    }
    
    $mysqli->set_charset('utf8');
    
    $id='';
    $title='title4';
    //用?代替 变量
    $sql="INSERT test VALUES (?,?)";
    //获得$mysqli_stmt对象,一定要记住传$sql,预处理是对sql语句的预处理。
    $mysqli_stmt=$mysqli->prepare($sql);
    
    //第一个参数表明变量类型,有i(int),d(double),s(string),b(blob)
    $mysqli_stmt->bind_param('is',$id,$title);
    
    //执行预处理语句
    if($mysqli_stmt->execute()){
        echo $mysqli_stmt->insert_id;
    }else{
        echo $mysqli_stmt->error;
    
    }
    $mysqli->close();

    使用mysqli预处理防止sql注入:

    $id='4';
    $title='title4';
    
    $sql="SELECT * FROM test WHERE id=? AND title=?";
    $mysqli_stmt=$mysqli->prepare($sql);
    $mysqli_stmt->bind_param('is',$id,$title);
    
    if ($mysqli_stmt->execute()) {
        $mysqli_stmt->store_result();
        if($mysqli_stmt->num_rows()>0){
            echo "验证成功";
        }else{
            echo "验证失败";
        }
    }
        $mysqli_stmt->free_result();
        $mysqli_stmt->close();

    使用mysqli预处理执行查询语句:

    $sql="SELECT id,title FROM test WHERE id>=?";
    
    $mysqli_stmt=$mysqli->prepare($sql);
    $id=1;
    
    $mysqli_stmt->bind_param('i',$id);
    
    if($mysqli_stmt->execute()){
        $mysqli_stmt->store_result();
    //将一个变量绑定到一个prepared语句上用于结果存储
    $mysqli_stmt->bind_result($id,$title); while ($mysqli_stmt->fetch()) { echo $id.' :'.$title.'<br/>'; } }

        更多mysqli技术请参见php官方手册,查手册是学习的最好方法~

    越学习越感到自己无知
  • 相关阅读:
    前段性能----详细渲染过程
    前段性能----repaint和reflow
    前段性能----缓存机制
    前段性能----带宽与延迟
    前端性能----从输入URL开始到返回数据的中间经历过程
    前端性能----TCP协议
    前端性能----CDN
    前端性能优化-学习链接,待持续更新
    前端性能----图像优化(图片)
    前端性能----静态资源,资源压缩
  • 原文地址:https://www.cnblogs.com/DeanChopper/p/4679808.html
Copyright © 2011-2022 走看看