The example in this article describes the method of adding, modifying and deleting multiple pieces of data using php+mysqli preprocessing technology. Share it with everyone for your reference. The specific analysis is as follows:
First of all, let’s talk about why we need preprocessing (precompilation) technology? For example: Suppose you want to add 100 users to the database. According to the conventional idea, 100 execution requests are sent to the database. At this time, according to the working principle of the mysql database, it needs to compile each execution statement (here are 100 Second-rate). Therefore, the efficiency here is very low.
The role of preprocessing (precompilation) technology is to reduce the number and time of compilation to improve the effect. Let’s use a case to illustrate how preprocessing (precompilation) technology is achieved (well, let’s make it clear first, when the php program sends the sql statement for the first time, the mysql database is compiled. After the next 99 times, php only needs to Just send the data there, no compilation is required).
<?php //1、创建数据库连接对象 $mysqli = new MySQLi("localhost","root","123456","liuyan"); if($mysqli->connect_error){ die($mysqli->connect_error); } $mysqli->query("set names 'GBK'"); //2、创建预编译对象 $sql = "insert into account(id,balance) values(?,?)"; //这里用 ? 来代替要插入的数据值 $stmt = $mysqli->prepare($sql); //返回一个statement对象,对象中的方法见手册 MySQLi_STMT //3、绑定参数(需要插入的数据),并执行 $id=null;//这里我数据库设置成了 primary key auto_increment $balance=100.5; $stmt->bind_param("id",$id,$balance); //绑定参数,返回值为布尔值。"if"按顺序代表插入数据的数据类型 //这里$id为int,用i表示,$balance为float型,用d表示,具体见手册 $res = $stmt->execute();//执行语句,返回值为布尔类型 //4、判断是否执行成功 if(!$res){ echo "数据插入失败,balance值为:".$balance; }else{ echo "成功"; } /* *****插入第二条数据 */ //3、绑定参数(需要插入的数据),并执行 $id=null;//这里我数据库设置成了 primary key auto_increment $balance=400.3; $stmt->bind_param("id",$id,$balance); //绑定参数,返回值为布尔值。"if"按顺序代表插入数据的数据类型 //这里$id为int,用i表示,$balance为float型,用d表示。 $res = $stmt->execute();//执行语句,返回值为布尔类型 //4、判断是否执行成功 if(!$res){ echo "数据插入失败,balance值为:".$balance; }else{ echo "成功"; } ?>
I hope this article will be helpful to everyone’s PHP programming design.