Table of Contents
PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译),mysqli面向对象
Home php教程 php手册 PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译),mysqli面向对象

PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译),mysqli面向对象

Jun 17, 2016 am 08:51 AM
mysql database

PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译),mysqli面向对象

 

1、和mysql扩展库的区别:

     (1   安全性、稳定性更高

     (2  提供了面向对象和面向过程两种风格

 

2、php.ini  中的  extension=php_mysqli.dll 解除封印

3、面向对象:查询列表

 
 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 ?>
Copy after login

4、面向对象:封装类后实现

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 ?>
Copy after login

4.2 调用页面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 ?>
Copy after login

5、同时执行多条数据库语句 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 ?>
Copy after login

6、事务控制

 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 ?>
Copy after login

7、预处理技术

主要在连接和编译过程精简,还可以SQL防止注入

7.1 预编译插入多个数据

 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 ?>
Copy after login

7.2 预编译查询多个数据

 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 ?>
Copy after login
 

 

8、其他函数

    (1  获取行数和列数  num_rows   field_count

    (2  获取结果集的一列 :表头 例如

              $result=$mysqli->query();

              $result->fetch_field();

    (3 取出数据

             $row=$result->fetch_row(); //获得每一行数据

             再通过 foreach($row as $val){} 取出每一个数据

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP development practice: Use PHPMailer to send emails to users in the MySQL database PHP development practice: Use PHPMailer to send emails to users in the MySQL database Aug 05, 2023 pm 06:21 PM

PHP development practice: Use PHPMailer to send emails to users in the MySQL database Introduction: In the construction of the modern Internet, email is an important communication tool. Whether it is user registration, password reset, or order confirmation in e-commerce, sending emails is an essential function. This article will introduce how to use PHPMailer to send emails and save the email information to the user information table in the MySQL database. 1. Install the PHPMailer library PHPMailer is

Go language and MySQL database: How to separate hot and cold data? Go language and MySQL database: How to separate hot and cold data? Jun 18, 2023 am 08:26 AM

As the amount of data continues to increase, database performance has become an increasingly important issue. Hot and cold data separation processing is an effective solution that can separate hot data and cold data, thereby improving system performance and efficiency. This article will introduce how to use Go language and MySQL database to separate hot and cold data. 1. What is hot and cold data separation processing? Hot and cold data separation processing is a way of classifying hot data and cold data. Hot data refers to data with high access frequency and high performance requirements. Cold data

How to perform incremental data backup of MySQL database using Go language How to perform incremental data backup of MySQL database using Go language Jun 17, 2023 pm 02:28 PM

As the amount of data increases, database backup becomes more and more important. For the MySQL database, we can use the Go language to achieve automated incremental backup. This article will briefly introduce how to use Go language to perform incremental backup of MySQL database data. 1. Install the Go language environment. First, we need to install the Go language environment locally. You can go to the official website to download the corresponding installation package and install it. 2. Install the corresponding library. The Go language provides many third-party libraries for accessing MySQL databases, among which the most commonly used ones are

To what extent can I develop MySQL database skills to be successfully employed? To what extent can I develop MySQL database skills to be successfully employed? Sep 12, 2023 pm 06:42 PM

To what extent can I develop MySQL database skills to be successfully employed? With the rapid development of the information age, database management systems have become an indispensable and important component in all walks of life. As a commonly used relational database management system, MySQL has a wide range of application fields and employment opportunities. So, to what extent do MySQL database skills need to be developed to be successfully employed? First of all, mastering the basic principles and basic knowledge of MySQL is the most basic requirement. MySQL is an open source relational database management

How to use MySQL database for time series analysis? How to use MySQL database for time series analysis? Jul 12, 2023 am 08:39 AM

How to use MySQL database for time series analysis? Time series data refers to a collection of data arranged in time order, which has temporal continuity and correlation. Time series analysis is an important data analysis method that can be used to predict future trends, discover cyclical changes, detect outliers, etc. In this article, we will introduce how to use a MySQL database for time series analysis, along with code examples. Create a data table First, we need to create a data table to store time series data. Suppose we want to analyze the number

MySQL database and Go language: How to perform data caching? MySQL database and Go language: How to perform data caching? Jun 17, 2023 am 10:05 AM

In recent years, the Go language has become increasingly popular among developers and has become one of the preferred languages ​​for developing high-performance web applications. MySQL is also a popular database that is widely used. In the process of combining these two technologies, caching is a very important part. The following will introduce how to use Go language to handle the cache of MySQL database. The concept of caching In web applications, caching is a middle layer created to speed up data access. It is mainly used to store frequently requested data to

How to use MySQL database for image processing? How to use MySQL database for image processing? Jul 14, 2023 pm 12:21 PM

How to use MySQL database for image processing? MySQL is a powerful relational database management system. In addition to storing and managing data, it can also be used for image processing. This article will introduce how to use a MySQL database for image processing and provide some code examples. Before you begin, make sure you have installed a MySQL database and are familiar with basic SQL statements. Create a database table First, create a new database table to store the image data. The structure of the table can be as follows

How to make reliable MySQL database connection using Go language? How to make reliable MySQL database connection using Go language? Jun 17, 2023 pm 07:18 PM

With the large amount of data that needs to be stored and processed, MySQL has become one of the most commonly used relational databases in application development. The Go language is becoming more and more popular among developers due to its efficient concurrency processing and concise syntax. This article will lead readers to implement reliable MySQL database connection through Go language, allowing developers to query and store data more efficiently. 1. Several ways for Go language to connect to MySQL database. There are usually three ways to connect to MySQL database in Go language, which are: 1. Third-party library

See all articles