PHP-Mysqli扩展库的预编译
时间:2022-03-14 18:52
(1)预编译的好处
假如要执行100条类似的sql语句,每一次执行,在MySQL端都会进行一次编译,效率很低。提高效率的方法就是--减少编译的次数。
先制造一个sql语句的模板,在MySQL端预先编译好,之后每次只需要传递数据即可。
除了提高效率之外,预编译还可以防止sql注入。
(2)dml语句的预编译
以向一个表中插入数据为例。表结构如下:
+----------+----------------------------+
| Field | Type |
+----------+----------------------------+
| id | int(11) |
| name | varchar(20) |
| height | float(5,2) |
| gender | enum(‘male‘,‘female‘) |
| class_id | int(11) |
+----------+----------------------------+
1 // dml语句的预编译 2 // 1.连接数据库 3 $mysqli = new MySQLi(‘localhost‘,‘root‘,‘root‘,‘lianxi‘); 4 if(mysqli_connect_errno()){ 5 echo ‘连接失败 ‘.$mysqli->connect_error; 6 } 7 $mysqli->query(‘set names utf8‘); 8 // 2.进行预编译 9 // 问号是占位符 10 $sql = ‘insert into student values (?,?,?,?,?)‘; 11 // 通过MySQLi类的prepare()方法对sql模板进行编译,返回一个MySQLi_STMT类对象 12 $stmt = $mysqli->prepare($sql) or die($mysqli->connect_error); 13 // 利用MySQLi_STMT类中的bind_param()方法绑定参数。第一个参数表示各个字段的类型,i(int)、s(string)、d(double) 14 $stmt->bind_param(‘isdii‘,$id,$name,$height,$gender,$classId); 15 // 3.利用MySQLi_STMT类中的execute()方法插入数据 16 $id = null; 17 $name = ‘Mildred‘; 18 $height = 165.00; 19 $gender = 2; 20 $classId = 12; 21 $stmt->execute() or die($stmt->error); 22 // 继续插入数据 23 $id = null; 24 $name = ‘Shaw‘; 25 $height = 174.50; 26 $gender = 1; 27 $classId = 11; 28 $stmt->execute() or die($stmt->error); 29 30 // 关闭连接 31 $stmt->close(); 32 $mysqli->close();
(3)dql语句的预编译
和dml语句不同的地方在于,除了要绑定参数,还需要绑定结果集
1 // dql语句的预编译 2 // 1.连接数据库 3 $mysqli = new MySQLi(‘localhost‘,‘root‘,‘root‘,‘lianxi‘); 4 if(mysqli_connect_error()){ 5 die(‘连接失败 ‘.$mysqli->connect_error); 6 } 7 $mysqli->query(‘set names utf8‘); 8 // 2.编译sql语句 9 $sql = ‘select * from student where id>?‘; 10 $stmt = $mysqli->prepare($sql) or die($mysqli->error); 11 // 3.绑定参数 12 $stmt->bind_param(‘i‘,$id); 13 // 4.绑定结果集 14 $stmt->bind_result($id,$name,$height,$gender,$classId); 15 // 5.执行 16 $id = 2; 17 $stmt->execute(); 18 // 6.利用MySQLi_STMT类中的fetch()方法,通过循环得到查询的数据 19 while($stmt->fetch()){ 20 echo $id.‘--‘.$name.‘--‘.$height.‘--‘.$gender.‘--‘.$classId; 21 echo ‘<br>‘; 22 } 23 // 7.关闭连接 24 $stmt->free_result(); 25 $stmt->close(); 26 $mysqli->close();