search
HomeBackend DevelopmentPHP TutorialPHP 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 ?>
PHP mysqli extension library (object-oriented/database operation encapsulation/transaction control/precompilation), mysqli object-oriented_PHP tutorial

4. Object-oriented: implement after encapsulating the class

4.1 Sqliconnect.class.php

PHP mysqli extension library (object-oriented/database operation encapsulation/transaction control/precompilation), mysqli object-oriented_PHP tutorial
 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) {}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133533.htmlTechArticlePHP mysqli extension library (object-oriented/database operation encapsulation/transaction control/precompilation), mysqli object-oriented 1. Differences from the mysql extension library: (1 higher security and stability (2 provides...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment