


PHP mysqli extension library (object-oriented/database operation encapsulation/transaction control/precompilation), mysqli object-oriented_PHP tutorial
PHP mysqli extension library (object-oriented/database operation encapsulation/transaction control/precompilation), mysqli object-oriented
1. The difference with mysql extension library:
(1) Higher security and stability
(2 provides two styles of object-oriented and process-oriented
2. Extension=php_mysqli.dll in php.ini is unsealed
3. Object-oriented: query list
1 <?php 2 3 //mysqli 操作数据(面向对象风格) 4 5 #1、创建Mysql对象 6 7 $mysqli=new MySQLi("127.0.0.1","root","daomul","test"); 8 if(!$mysqli) 9 { 10 die("连接失败!".$mysqli->connect_error); 11 } 12 13 #2、操作数据库 14 15 $sql="select * from user1"; 16 $res=$mysqli->query($sql); 17 #3、处理结果 18 19 while($row=$res->fetch_row()) 20 { 21 foreach($row as $key=> $val) 22 { 23 echo "-- $val"; 24 } 25 echo "<br/>"; 26 } 27 #4、关闭资源 28 $res->free();//释放内存 29 $mysqli->close();//关闭连接 30 31 ?>

4. Object-oriented: implement after encapsulating the class
4.1 Sqliconnect.class.php

1 <?php 2 3 Class Sqliconnect 4 { 5 private $mysqli; 6 private static $host="127.0.0.1"; 7 private static $root="root"; 8 private static $password="daomul"; 9 private static $db="test"; 10 11 function __construct() 12 { 13 $this->mysqli=new MySQLi(self::$host,self::$root,self::$password,self::$db); 14 if(!$this->mysqli) 15 { 16 die("数据库连接失败!".$this->mysqli->connect_error); 17 } 18 19 $this->mysqli->query("set names utf8"); 20 } 21 22 //查询操作 23 public function excute_dql($sql) 24 { 25 $res=$this->mysqli->query($sql) or die("数据查询失败".$this->mysqli->error); 26 return $res; 27 28 } 29 30 //增删改操作 31 public function excute_dml($sql) 32 { 33 $res=$this->mysqli->query($sql) or die("数据操作失败".$this->mysqli->error); 34 if(!$res) 35 { 36 echo "数据操作失败"; 37 } 38 else 39 { 40 if($this->mysqli->affected_rows>0) 41 { 42 echo "操作成功!"; 43 } 44 else 45 { 46 echo "0行数据受影响!"; 47 } 48 } 49 } 50 51 } 52 ?>
4.2 Call page startsqli.php
1 <?php 2 3 //mysqli 操作数据(面向对象风格) 4 5 6 require_once "Sqliconnect.class.php"; 7 8 $Sqliconnect=new Sqliconnect(); 9 10 //$sql="insert into user1(name,password,email,age) values('帝都',md5('gg'),'sd@sohu.com',23)"; 11 //$sql="delete from user1 where id=11"; 12 //$res=$Sqliconnect->excute_dml($sql); 13 14 $sql="select name from user1;"; 15 $res=$Sqliconnect->excute_dql($sql); 16 while($row=$) 17 18 $res->free(); 19 ?>
5. Execute multiple database statements at the same time multiQuery.php
1 <?php 2 3 //mysqli 操作数据(面向对象风格) 4 5 #1、创建Mysql对象 6 7 $mysqli=new MySQLi("127.0.0.1","root","daomul","test"); 8 if(!$mysqli) 9 { 10 die("连接失败!".$mysqli->connect_error); 11 } 12 13 #2、操作数据库 14 15 $sqls="select * from user1;"; 16 $sqls.="select * from user1"; 17 18 #3、处理结果 19 20 if($res=$mysqli->multi_query($sqls)) 21 { 22 echo "211"; 23 do 24 { 25 //从mysqli连续取出第一个结果集 26 $result=$mysqli->store_result(); 27 28 //显示mysqli result对象 29 while($row=$result->fetch_row()) 30 { 31 foreach($row as $key=> $val) 32 { 33 echo "-- $val"; 34 } 35 echo "<br/>"; 36 } 37 38 $result->free();//及时释放当前结果集,并进入下一结果集 39 40 //判断是否有下一个结果集 41 if(!$mysqli->more_results()) 42 { 43 break; 44 } 45 echo "<br/>************新的结果集**************"; 46 47 }while($mysqli->next_result()); 48 } 49 50 #4、关闭资源 51 $mysqli->close();//关闭连接 52 53 54 ?>
6. Transaction control
1 <?php 2 3 //mysqli 操作数据(面向对象风格) 4 5 6 // 数据库 :create table account(id int primary key,balance float); 7 8 $mysqli=new MySQLi("127.0.0.1","root","daomul","test"); 9 if(!$mysqli) 10 { 11 die("数据库连接失败!".$mysqli->connect_error); 12 } 13 //将提交设为false 14 $mysqli->autocommit(false); 15 16 $sql1="update account set balance=balance+1 where id=1;";//没错的语句 17 $sql2="update accounterror2 set balance=balance-1 where id=2";//有错的语句 18 19 $res1=$mysqli->query($sql1); 20 $res2=$mysqli->query($sql2); 21 22 if(!$res1||!$res2) 23 { 24 //回滚:其中一个不成功即回滚不提交 25 echo "有错,回滚,请重新提交!"; 26 $mysqli->rollback();//die("操作失败!".$mysqli->error); 27 } 28 else 29 { 30 //所有均成功则提交 31 echo "所有提交成功!"; 32 $mysqli->commit(); 33 } 34 35 $mysqli->close(); 36 /* 37 1、 start transaction; 开启事务 38 2、svaepoint a; 做保存点 39 3、执行操作1; 40 4、 svaepoint b; 41 5、执行操作2; 42 ... 43 6、rollback to a/b; 回滚或者是提交 44 7、commit 45 46 事务控制特点acid 原子性/一致性/隔离性/持久性 47 */ 48 ?>
7. Preprocessing technology
It mainly streamlines the connection and compilation process, and can also prevent SQL injection
7.1 Pre-compile and insert multiple data
1 <?php 2 3 //mysqli 预编译演示 4 5 #1、创建mysqli对象 6 $mysqli=new MySQLi("127.0.0.1","root","daomul","test"); 7 if(!$mysqli) 8 { 9 die("数据库连接失败!".$mysqli->connect_error); 10 } 11 12 #2、创建预编译对象 13 $sql="insert into user1(name,password,email,age) values(?,?,?,?);";//暂时不赋值,用问号代替 14 $stmt=$mysqli->prepare($sql) or die($mysqli->error); 15 16 /********************************可重复执行时需要的代码start*********************************/ 17 #3、绑定参数 18 $name='小明5'; 19 $password='34f'; 20 $email='ssd@qq.com'; 21 $age='1'; 22 23 #4、参数赋值(第一个参数指代参数的类型缩写,string-s,int-i,double-d,bool-b 24 $stmt->bind_param("sssi",$name,$password,$email,$age); 25 26 #5、执行代码(返回布尔类型) 27 $flag=$stmt->execute(); 28 29 /********************************可重复执行时需要的代码 end************************************/ 30 31 #6、结果以及释放 32 33 if(!$flag) 34 { 35 die("操作失败".$stmt->error); 36 } 37 else 38 { 39 echo "操作成功!"; 40 } 41 42 $mysqli->close(); 43 44 45 ?>
7.2 Pre-compiled query for multiple data
1 <?php 2 3 //mysqli 预编译演示 4 5 #1、创建mysqli对象 6 $mysqli=new MySQLi("127.0.0.1","root","daomul","test"); 7 if(!$mysqli) 8 { 9 die("数据库连接失败!".$mysqli->connect_error); 10 } 11 12 /********************************可重复执行时需要的代码 start*******************************/ 13 14 #2、创建预编译对象 15 $sql="select id,name,email from user1 where id>?;";//id,name,email和后面的结果集bind_result()对应 16 $stmt=$mysqli->prepare($sql) or die($mysqli->error); 17 18 #3、绑定参数 19 $id=5; 20 21 #4、参数赋值(第一个参数指代参数的类型缩写,string-s,int-i,double-d,bool-b 22 $stmt->bind_param("i",$id);//绑定参数 23 $stmt->bind_result($id,$name,$email);//绑定结果集 24 25 #5、执行代码(返回布尔类型) 26 $stmt->execute(); 27 28 #6、取出结果集显示 29 while($stmt->fetch()) 30 { 31 echo "<br/>$id--$name--$email"; 32 } 33 34 /********************************可重复执行时需要的代码 end*******************************/ 35 36 #7、结果以及释放 37 38 //释放结果 39 $stmt->free_result(); 40 //关闭预编译语句 41 $stmt->close(); 42 //关闭数据库连接 43 $mysqli->close(); 44 45 46 ?>
8. Other functions
(1 Get the number of rows and columns num_rows field_count
(2 Get a column of the result set: header, for example
$result=$mysqli->query();
$result->fetch_field();
(3 Get data
$row=$result->fetch_row(); //Get each row of data
Taking each data through Foreach ($ Row as $ Val) {}

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
