1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > php预编译mysql扩展_PHP-Mysqli扩展库的预编译

php预编译mysql扩展_PHP-Mysqli扩展库的预编译

时间:2022-05-30 14:03:07

相关推荐

php预编译mysql扩展_PHP-Mysqli扩展库的预编译

(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 '

';22 }23 //7.关闭连接

24 $stmt->free_result();25 $stmt->close();26 $mysqli->close();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。