MySQL Drivers and Plugins

目录

PHP offers several MySQL drivers and plugins for accessing and handling MySQL.

The differences and functionality of the MySQL extensions are described within the overview of this section.

Overview of the MySQL PHP drivers

目录

Introduction

目录

Depending on the version of PHP, there are either two or three PHP APIs for accessing the MySQL database. PHP 5 users can choose between the deprecated mysql extension, mysqli, or PDO_MySQL. PHP 7 removes the mysql extension, leaving only the latter two options.

This guide explains the terminology used to describe each API, information about choosing which API to use, and also information to help choose which MySQL library to use with the API.

Terminology overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term “driver” is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

Choosing an API

PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "user" and the password "password". And a query is run to greet the user.

示例 #1 Comparing the three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>

Recommended API

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

Feature comparison

 ext/mysqliPDO_MySQLext/mysql
PHP version introduced5.05.12.0
Included with PHP 5.xYesYesYes
Included with PHP 7.xYesYesNo
Development statusActiveActiveMaintenance only in 5.x; removed in 7.x
LifecycleActiveActiveDeprecated in 5.x; removed in 7.x
Recommended for new projectsYesYesNo
OOP InterfaceYesYesNo
Procedural InterfaceYesNoYes
API supports non-blocking, asynchronous queries with mysqlndYesNoNo
Persistent ConnectionsYesYesYes
API supports CharsetsYesYesYes
API supports server-side Prepared StatementsYesYesNo
API supports client-side Prepared StatementsNoYesNo
API supports Stored ProceduresYesYesNo
API supports Multiple StatementsYesMostNo
API supports TransactionsYesYesNo
Transactions can be controlled with SQLYesYesYes
Supports all MySQL 5.1+ functionalityYesMostNo

Choosing a library

The mysqli, PDO_MySQL and mysql PHP extensions are lightweight wrappers on top of a C client library. The extensions can either use the mysqlnd library or the libmysqlclient library. Choosing a library is a compile time decision.

The mysqlnd library is part of the PHP distribution since 5.3.0. It offers features like lazy connections and query caching, features that are not available with libmysqlclient, so using the built-in mysqlnd library is highly recommended. See the mysqlnd documentation for additional details, and a listing of features and functionality that it offers.

示例 #1 Configure commands for using mysqlnd or libmysqlclient

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd

// Alternatively recommended, compiles with mysqlnd as of PHP 5.4
$ ./configure --with-mysqli --with-pdo-mysql --with-mysql

// Not recommended, compiles with libmysqlclient
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config --with-mysql=/path/to/mysql_config

Library feature comparison

It is recommended to use the mysqlnd library instead of the MySQL Client Server library (libmysqlclient). Both libraries are supported and constantly being improved.

 MySQL native driver (mysqlnd)MySQL client server library (libmysqlclient)
Part of the PHP distributionYesNo
PHP version introduced5.3.0N/A
LicensePHP License 3.01Dual-License
Development statusActiveActive
LifecycleNo end announcedNo end announced
PHP 5.4 and above; compile default (for all MySQL extensions)YesNo
PHP 5.3; compile default (for all MySQL extensions)NoYes
Compression protocol supportYes (5.3.1+)Yes
SSL supportYes (5.3.3+)Yes
Named pipe supportYes (5.3.4+)Yes
Non-blocking, asynchronous queriesYesNo
Performance statisticsYesNo
LOAD LOCAL INFILE respects the open_basedir directiveYesNo
Uses PHP's native memory management system (e.g., follows PHP memory limits)YesNo
Return numeric column as double (COM_QUERY)YesNo
Return numeric column as string (COM_QUERY)YesYes
Plugin APIYesLimited
Read/Write splitting for MySQL ReplicationYes, with pluginNo
Load BalancingYes, with pluginNo
Fail overYes, with pluginNo
Lazy connectionsYes, with pluginNo
Query cachingYes, with pluginNo
Transparent query manipulations (E.g., auto-EXPLAIN or monitoring)Yes, with pluginNo
Automatic reconnectNoOptional

Concepts

目录

These concepts are specific to the MySQL drivers for PHP.

Buffered and Unbuffered queries

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process. This allows additional operations like counting the number of rows, and moving (seeking) the current result pointer. It also allows issuing further queries on the same connection while working on the result set. The downside of the buffered mode is that larger result sets might require quite a lot memory. The memory will be kept occupied till all references to the result set are unset or the result set was explicitly freed, which will automatically happen during request end the latest. The terminology "store result" is also used for buffered mode, as the whole result set is stored at once.

Note:

When using libmysqlclient as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

Unbuffered MySQL queries execute the query and then return a resource while the data is still waiting on the MySQL server for being fetched. This uses less memory on the PHP-side, but can increase the load on the server. Unless the full result set was fetched from the server no further queries can be sent over the same connection. Unbuffered queries can also be referred to as "use result".

Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

示例 #1 Unbuffered query example: mysqli

<?php
$mysqli  = new mysqli("localhost", "my_user", "my_password", "world");
$uresult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);

if ($uresult) {
   while ($row = $uresult->fetch_assoc()) {
       echo $row['Name'] . PHP_EOL;
   }
}
$uresult->close();
?>

示例 #2 Unbuffered query example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

示例 #3 Unbuffered query example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

$uresult = mysql_unbuffered_query("SELECT Name FROM City");
if ($uresult) {
   while ($row = mysql_fetch_assoc($uresult)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

Character sets

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

Caution

The character set should be understood and defined, as it has an affect on every action, and includes security implications. For example, the escaping mechanism (e.g., mysqli_real_escape_string for mysqli, mysql_real_escape_string for mysql, and PDO::quote for PDO_MySQL) will adhere to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

示例 #1 Problems with setting the character set with SQL

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8');

// But, this will NOT affect it (utf-8 vs utf8) -- don't use dashes here
$mysqli->set_charset('utf-8');

?>

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

Note: Possible UTF-8 confusion

Because character set names in MySQL do not contain dashes, the string "utf8" is valid in MySQL to set the character set to UTF-8. The string "utf-8" is not valid, as using "utf-8" will fail to change the character set.

示例 #2 Setting the character set example: mysqli

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

printf("Initial character set: %s\n", $mysqli->character_set_name());

if (!$mysqli->set_charset('utf8')) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit;
}

echo "New character set information:\n";
print_r( $mysqli->get_charset() );

?>

示例 #3 Setting the character set example: pdo_mysql

Note: This only works as of PHP 5.3.6.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", 'my_user', 'my_pass');
?>

示例 #4 Setting the character set example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

echo 'Initial character set: ' .  mysql_client_encoding($conn) . "\n";

if (!mysql_set_charset('utf8', $conn)) {
    echo "Error: Unable to set the character set.\n";
    exit;
}

echo 'Your current character set is: ' .  mysql_client_encoding($conn);
?>

MySQL增强版扩展

目录

mysqli扩展允许我们访问MySQL 4.1及以上版本提供的功能。关于MySQL数据库 服务端的信息请参阅» http://www.mysql.com/

是在PHP中可以用于MySQL访问的软件的一个概览。

Mysql的文档请查看» http://dev.mysql.com/doc/

本文档中部分内容经过Oracle公司授权引自MySQL手册。 Parts of this documentation included from MySQL manual with permissions of Oracle Corporation.

示例

所有mysqli文档示例使用的都是world数据库,该数据库可以从» http://dev.mysql.com/doc/world-setup/en/index.html下载。

Overview

这一部分对在PHP应用开发过程中需要和Mysql数据库交互时可用的选择进行一个简单介绍。

什么是API?

一个应用程序接口(Application Programming Interface的缩写),定义了类,方法,函数,变量等等一切 你的应用程序中为了完成特定任务而需要调用的内容。在PHP应用程序需要和数据库进行交互的时候所需要的API 通常是通过PHP扩展暴露出来(给终端PHP程序员调用)。

API可以是面向过程的,也可以是面向对象的。对于面向过程的API,我们通过调用函数来完成任务,而对于面向对象的API, 我们实例化类,并在实例化后得到的对象上调用方法。对于这两种接口而言,后者通常是首选的,因为它更加现代化,并且 给我们带来了良好的代码结构。

当构建一个需要连接到MySQL服务端的PHP应用的时候,有好几种API可供选择。此文档就是讨论这些可用的API并讨论如何为 你的应用选择一个最佳的解决方案。

什么是连接器?

在MySQL文档中,术语connector解释为“一段允许你的应用连接到MySQL数据库服务器的软件代码”。 MySQL提供了很多语言的连接器,其中包括PHP的。

在你的PHP应用需要和一个数据库服务器交互的时候,你需要书写PHP代码去完成“连接数据库服务器”,“查询数据库“以及其他数据库相关功能 等一系列活动。你的PHP应用将会使用提供这些API的软件,或者在需要的时候使用一些中间库,来处理你的应用和数据库服务器之间的交互。 这种软件通常被认为是连接器,它允许你的引用连接到数据库服务器。

什么是驱动?

驱动是一段设计用来于一种特定类型的数据库服务器进行交互的软件代码。驱动可能会调用一些库,比如MySQL客户端库或者MySQL Native驱动库。 这些库实现了用于和MySQL数据库服务器进行交互的底层协议。

通过一个例子PDO(PHP Database Object的缩写)数据库抽象层可以 使用多种特定数据库的驱动。其中一种驱动就是PDO MYSQL驱动,它就是与MySQL服务器之间的接口。

有时大家会不加区分的使用连接器和驱动这两个术语。在MySQL相关文档中“driver”术语被作为一个连接器包 中提供特定数据库部分的软件代码。

什么是扩展?

在PHP文档中你还会发现很多其他的扩展。PHP代码是由一个核心,一些可选扩展组成了核心功能。PHP 的MySQL相关扩展,比如mysqlimysql都是基于PHP扩展框架实现的。

扩展一个典型的作用就是暴露一个API给PHP程序员,允许扩展自己的功能可以被程序员使用。当然,也有一部分基于PHP扩展框架 开发的扩展不会给PHP程序员暴露API接口。

比如说PDO MySQL驱动扩展,就没有向PHP程序员暴露API接口,但是向它上层的PDO层提供了一个接口。

术语API和扩展描述的不是同一类事物,因为扩展可能并不需要暴露一个API接口给程序员。

PHP中提供的用于MySQL的主要API是什么?

当考虑连接到MySQL数据库服务器的时候,有三种主要的API可供选择:

  • PHP的MySQL扩展

  • PHP的mysqli扩展

  • PHP数据对象(PDO)

三者都有各自的优缺点。下面的讨论就是为了对每种API的关键方面给出一个简短的介绍。

什么是PHP的MySQL扩展?

这是设计开发允许PHP应用与MySQL数据库交互的早期扩展。mysql扩展提供了一个面向过程 的接口,并且是针对MySQL4.1.3或更早版本设计的。因此,这个扩展虽然可以与MySQL4.1.3或更新的数据库服务端 进行交互,但并不支持后期MySQL服务端提供的一些特性。

Note:

如果你是使用MySQL4.1.3或更新的服务端版本,强烈建议你使用mysqli 扩展替代它。

mysql扩展的源代码在PHP扩展目录ext/mysql下。

对于mysql扩展的更多信息,请参阅

什么是PHP的mysqli扩展?

mysqli扩展,我们有时称之为MySQL增强扩展,可以用于使用 MySQL4.1.3或更新版本中新的高级特性。mysqli扩展在PHP 5及以后版本中包含。

mysqli扩展有一系列的优势,相对于mysql扩展的提升主要有:

  • 面向对象接口

  • prepared语句支持(译注:关于prepare请参阅mysql相关文档)

  • 多语句执行支持

  • 事务支持

  • 增强的调试能力

  • 嵌入式服务支持

Note:

如果你使用MySQL4.1.3或更新版本,强烈建议你使用这个扩展。

在提供了面向对象接口的同时也提供了一个面向过程的接口。

mysqli扩展是使用PHP扩展框架构建的,它的源代码在PHP源码目录下的ext/mysqli中。

对于mysqli扩展的更多信息,请参阅

什么是PDO?

PHP数据对象,是PHP应用中的一个数据库抽象层规范。PDO提供了一个统一的API接口可以使得你的PHP应用不去关心具体要 连接的数据库服务器系统类型。也就是说,如果你使用PDO的API,可以在任何需要的时候无缝切换数据库服务器,比如从Firebird 到MySQL,仅仅需要修改很少的PHP代码。

其他数据库抽象层的例子包括Java应用中的JDBC以及Perl中的DBI。

当然,PDO也有它自己的先进性,比如一个干净的,简单的,可移植的API,它最主要的缺点是会限制让你不能使用 后期MySQL服务端提供所有的数据库高级特性。比如,PDO不允许使用MySQL支持的多语句执行。

PDO是基于PHP扩展框架实现的,它的源码在PHP源码目录的ext/pdo下。

PDO的更多信息,请参阅PDO

什么是PDO的MySQL驱动器?

PDO的MySQL驱动并不是一套API,至少从PHP程序员的角度来看是这样的。实际上,PDO的MySQL驱动处于PDO自己的下层, 提供了特定的Mysql功能。程序员直接调用PDO的API,而PDO使用了PDO的MySQL驱动完成与MySQL服务器端的交互。

PDO的MySQL驱动是众多PDO驱动中的一个。其他可用的PDO驱动包括Firebird,PostgreSQL等等。

PDO的MySQL驱动是基于PHP扩展框架实现的。它的源码在PHP源码目录下的ext/pdo_mysql。 它没有向PHP程序员暴露API。

PDO的MySQL扩展的更多信息请参阅

什么是PHP的MySQL Native 驱动?

为了与MySQL数据库服务端进行交互,mysql扩展,mysqli扩展, PDO MySQL驱动都使用了实现了必要的协议的底层库。以前,可用的库只有MySQL客户端库和libmysql

然而,libmysql包含的接口没有针对与PHP的应用交互进行优化,libmysql 是早期为C应用程序设计的。基于这个原因,MySQL Native驱动mysqlnd,作为libmysql的一个 针对PHP应用的修改版本被开发。

mysqlmysqli以及PDO Mysql驱动都可以各自配置使用 libmysql或者mysqlndmysqlnd作为一个专门设计 用于PHP系统的库,它在内存和速度上都比libmysql有很大提升。非常希望你去尝试这些提升。

Note:

MySQL Native驱动仅仅可以在MySQL服务端版本为4.1.3及以后版本才可以使用。

MySQL Native驱动是基于PHP扩展框架实现的。源代码位于PHP源码目录的ext/mysqlnd下。 它没有向PHP程序员暴露接口。

特性比较

下表比较了PHP中三种主要的MySQL连接方式的功能:

 PHP的mysqli扩展PDO (使用PDO MySQL驱动和MySQL Native驱动)PHP的mysql扩展
引入的PHP版本5.05.03.0之前
PHP5.x是否包含
MySQL开发状态活跃在PHP5.3中活跃仅维护
在MySQL新项目中的建议使用程度建议 - 首选建议不建议
API的字符集支持
服务端prepare语句的支持情况
客户端prepare语句的支持情况
存储过程支持情况
多语句执行支持情况大多数
是否支持所有MySQL4.1以上功能大多数

Quick start guide

目录

This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API.

This quick start gives an overview on the mysqli extension. Code examples are provided for all major aspects of the API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL.

Required: A familiarity with the PHP programming language, the SQL language, and basic knowledge of the MySQL server.

Dual procedural and object-oriented interface

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigm.

Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension. In many cases, the function names differ only by prefix. Some mysqli functions take a connection handle as their first argument, whereas matching functions in the old mysql interface take it as an optional last argument.

示例 #1 Easy migration from the old mysql extension

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT 'the mysql extension for new developments.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
?>

以上例程会输出:

Please, do not use the mysql extension for new developments.

The object-oriented interface

In addition to the classical procedural interface, users can choose to use the object-oriented interface. The documentation is organized using the object-oriented interface. The object-oriented interface shows functions grouped by their purpose, making it easier to get started. The reference section gives examples for both syntax variants.

There are no significant performance differences between the two interfaces. Users can base their choice on personal preference.

示例 #2 Object-oriented and procedural interface

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $res->fetch_assoc();
echo $row['_msg'];
?>

以上例程会输出:

A world full of choices to please everybody.

The object oriented interface is used for the quickstart because the reference section is organized that way.

Mixing styles

It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons.

示例 #3 Bad coding style

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if (!$res) {
    echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
}

if ($row = $res->fetch_assoc()) {
    echo $row['_msg'];
}
?>

以上例程会输出:

Possible but bad style.

See also

Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead.

示例 #1 Special meaning of localhost

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";
?>

以上例程会输出:

Localhost via UNIX socket
127.0.0.1 via TCP/IP

Connection parameter defaults

Depending on the connection function used, assorted parameters can be omitted. If a parameter is not provided, then the extension attempts to use the default values that are set in the PHP configuration file.

示例 #2 Setting defaults

mysqli.default_host=192.168.2.27
mysqli.default_user=root
mysqli.default_pw=""
mysqli.default_port=3306
mysqli.default_socket=/tmp/mysql.sock

The resulting parameter values are then passed to the client library that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.

Built-in connection library defaults

If the host value is unset or empty, then the client library will default to a Unix socket connection on localhost. If socket is unset or empty, and a Unix socket connection is requested, then a connection to the default socket on /tmp/mysql.sock is attempted.

On Windows systems, the host name . is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipe name. If not given or empty, then the socket (pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.

Connection options

Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.

For setting a connection option, the connect operation has to be performed in three steps: creating a connection handle with mysqli_init, setting the requested options using mysqli_options, and establishing the network connection with mysqli_real_connect.

Connection pooling

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.

Persistent connection

If a unused persistent connection for a given combination of host, username, password, socket, port and default database can not be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note, that the web server may spawn many PHP processes.

A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name persistent may be understood as a promise that the state is persisted.

The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli_change_user to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.

The mysqli_change_user function is an expensive operation. For best performance, users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.

It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.

See also

Executing statements

Statements can be executed with the mysqli_query, mysqli_real_query and mysqli_multi_query functions. The mysqli_query function is the most common, and combines the executing statement with a buffered fetch of its result set, if any, in one call. Calling mysqli_query is identical to calling mysqli_real_query followed by mysqli_store_result.

示例 #1 Connecting to MySQL

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Buffered result sets

After statement execution results can be retrieved at once to be buffered by the client or by read row by row. Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli_query combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

示例 #2 Navigation through buffered results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $res->num_rows - 1; $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    $row = $res->fetch_assoc();
    echo " id = " . $row['id'] . "\n";
}

echo "Result set order...\n";
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
    echo " id = " . $row['id'] . "\n";
}
?>

以上例程会输出:

Reverse order...
 id = 3
 id = 2
 id = 1
Result set order...
 id = 1
 id = 2
 id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

示例 #3 Navigation through unbuffered results

<?php
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();

echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    echo " id = " . $row['id'] . "\n";
}
?>

Result set values data types

The mysqli_query, mysqli_real_query and mysqli_multi_query functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

示例 #4 Text protocol returns strings by default

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

以上例程会输出:

id = 1 (string)
label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

示例 #5 Native data types with mysqlnd and connection option

<?php
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

以上例程会输出:

id = 1 (integer)
label = a (string)

See also

  • mysqli::__construct
  • mysqli::init
  • mysqli::options
  • mysqli::real_connect
  • mysqli::query
  • mysqli::multi_query
  • mysqli::use_result
  • mysqli::store_result
  • mysqli_result::free

Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with ?.

示例 #1 First stage: prepare

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources.

示例 #2 Second stage: bind and execute

<?php
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>

Repeated execution

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

示例 #3 INSERT prepared once, executed multiple times

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

/* Prepared statement: repeated execution, only data transferred from client to server */
for ($id = 2; $id < 5; $id++) {
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
}

/* explicit close recommended */
$stmt->close();

/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
?>

以上例程会输出:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [3]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the SELECT is not run as a prepared statement above.

Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, multi-INSERT requires less round-trips between the server and client than the prepared statement shown above.

示例 #4 Less round trips using multi-INSERT SQL

<?php
if (!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3), (4)")) {
    echo "Multi-INSERT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Result set values data types

The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. The client libraries do not receive strings only. Instead, they will receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL INT column will be provided as PHP integer variables.

示例 #5 Native datatypes

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

以上例程会输出:

id = 1 (integer)
label = a (string)

This behavior differs from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.

Fetching results using bound variables

Results from prepared statements can either be retrieved by binding output variables, or by requesting a mysqli_result object.

Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.

示例 #6 Output variable binding

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$out_id    = NULL;
$out_label = NULL;
if (!$stmt->bind_result($out_id, $out_label)) {
    echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

while ($stmt->fetch()) {
    printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}
?>

以上例程会输出:

id = 1 (integer), label = a (string)

Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by mysqli.

It is also possible to buffer the results of a prepared statement using mysqli_stmt_store_result.

Fetching results using mysqli_result interface

Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt_get_result returns a buffered result set.

示例 #7 Using mysqli_result to fetch results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

var_dump($res->fetch_all());
?>

以上例程会输出:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    string(1) "a"
  }
}

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

示例 #8 Buffered result set for flexible read out

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a'), (2, 'b'), (3, 'c')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    var_dump($res->fetch_assoc());
}
$res->close();
?>

以上例程会输出:

array(2) {
  ["id"]=>
  int(3)
  ["label"]=>
  string(1) "c"
}
array(2) {
  ["id"]=>
  int(2)
  ["label"]=>
  string(1) "b"
}
array(2) {
  ["id"]=>
  int(1)
  ["label"]=>
  string(1) "a"
}

Escaping and SQL injection

Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt_bind_param function for more information.

Such a separation sometimes considered as the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.

Client-side prepared statement emulation

The API does not include emulation for client-side prepared statement emulation.

Quick prepared - non-prepared statement comparison

The table below compares server-side prepared and non-prepared statements.

 Prepared StatementNon-prepared statement
Client-server round trips, SELECT, single execution21
Statement string transferred from client to server11
Client-server round trips, SELECT, repeated (n) execution1 + nn
Statement string transferred from client to server1 template, n times bound parameter, if anyn times together with parameter, if any
Input parameter binding APIYes, automatic input escapingNo, manual input escaping
Output variable binding APIYesNo
Supports use of mysqli_result APIYes, use mysqli_stmt_get_resultYes
Buffered result setsYes, use mysqli_stmt_get_result or binding with mysqli_stmt_store_resultYes, default of mysqli_query
Unbuffered result setsYes, use output binding APIYes, use mysqli_real_query with mysqli_use_result
MySQL Client Server protocol data transfer flavorBinary protocolText protocol
Result set values SQL data typesPreserved when fetchingConverted to string or preserved when fetching
Supports all SQL statementsRecent MySQL versions support most but not allYes

See also

  • mysqli::__construct
  • mysqli::query
  • mysqli::prepare
  • mysqli_stmt::prepare
  • mysqli_stmt::execute
  • mysqli_stmt::bind_param
  • mysqli_stmt::bind_result

Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

示例 #1 Calling a stored procedure

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;")) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("CALL p(1)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT id FROM test"))) {
    echo "SELECT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

var_dump($res->fetch_assoc());
?>

以上例程会输出:

array(1) {
  ["id"]=>
  string(1) "1"
}

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

示例 #2 Using session variables

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}


if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT @msg as _p_out"))) {
    echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$row = $res->fetch_assoc();
echo $row['_p_out'];
?>

以上例程会输出:

Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query. The mysqli_query function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli_real_query or mysqli_multi_query. Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.

示例 #3 Fetching results from stored procedures

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->multi_query("CALL p()")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        printf("---\n");
        var_dump($res->fetch_all());
        $res->free();
    } else {
        if ($mysqli->errno) {
            echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
        }
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

以上例程会输出:

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the CALL SQL statement.

示例 #4 Stored Procedures and Prepared Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {
    if ($res = $stmt->get_result()) {
        printf("---\n");
        var_dump(mysqli_fetch_all($res));
        mysqli_free_result($res);
    } else {
        if ($stmt->errno) {
            echo "Store failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

Of course, use of the bind API for fetching is supported as well.

示例 #5 Stored Procedures and Prepared Statements using bind API

<?php
if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {

    $id_out = NULL;
    if (!$stmt->bind_result($id_out)) {
        echo "Bind failed: (" . $stmt->errno . ") " . $stmt->error;
    }
 
    while ($stmt->fetch()) {
        echo "id = $id_out\n";
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

See also

  • mysqli::query
  • mysqli::multi_query
  • mysqli_result::next-result
  • mysqli_result::more-results

Multiple Statements

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Multiple statements or multi queries must be executed with mysqli_multi_query. The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

示例 #1 Multiple Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

以上例程会输出:

array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}

Security considerations

The API functions mysqli_query and mysqli_real_query do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

示例 #2 SQL Injection

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$res    = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
if (!$res) {
    echo "Error executing query: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

以上例程会输出:

Error executing query: (1064) You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax 
to use near 'DROP TABLE mysql.user' at line 1

Prepared statements

Use of the multiple statement with prepared statements is not supported.

See also

  • mysqli::query
  • mysqli::multi_query
  • mysqli_result::next-result
  • mysqli_result::more-results

API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the auto commit mode and for committing and rolling back transactions.

示例 #1 Setting auto commit mode with SQL and through the API

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);

/* Won't be monitored and recognized by the replication and the load balancing plugin */
if (!$mysqli->query('SET AUTOCOMMIT = 0')) {
    echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode, committing or rolling back a transaction.

示例 #2 Commit and rollback

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);

$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();

$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();
?>

Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.

See also

  • mysqli::autocommit
  • mysqli_result::commit
  • mysqli_result::rollback

Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

示例 #1 Accessing result set meta data

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($res->fetch_fields());
?>

以上例程会输出:

array(2) {
  [0]=>
  object(stdClass)#3 (13) {
    ["name"]=>
    string(4) "_one"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(1)
    ["length"]=>
    int(1)
    ["charsetnr"]=>
    int(63)
    ["flags"]=>
    int(32897)
    ["type"]=>
    int(8)
    ["decimals"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#4 (13) {
    ["name"]=>
    string(4) "_two"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(5)
    ["length"]=>
    int(5)
    ["charsetnr"]=>
    int(8)
    ["flags"]=>
    int(1)
    ["type"]=>
    int(253)
    ["decimals"]=>
    int(31)
  }
}

Prepared statements

Meta data of result sets created using prepared statements are accessed the same way. A suitable mysqli_result handle is returned by mysqli_stmt_result_metadata.

示例 #2 Prepared statements metadata

<?php
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$res = $stmt->result_metadata();
var_dump($res->fetch_fields());
?>

See also

  • mysqli::query
  • mysqli_result::fetch_fields

安装/配置

目录

需求

要使用 mysqli 相关的函数, 你必须以启用 mysqli 扩展的方式编译 PHP。

MySQL 8

使用 PHP 7.1.16 之前的版本或者 PHP 7.2(PHP 7.2.4 之前的版本), 需要将 MySQL 服务器的默认密码插件设置为:mysql_native_password。 否则,当你连接的时候就会看到类似这样的错误: The server requested authentication method unknown to the client [caching_sha2_password]。 即使你未使用 caching_sha2_password 也会这样。

发生这种错误的原因是,MySQL 8 服务器默认会使用 caching_sha2_password 扩展, 老版本的 PHP 驱动(mysqlnd)无法识别这个扩展。 所以需要在 MySQL 的配置文件 my.cnf 中,设置 default_authentication_plugin=mysql_native_password。 在后续的 PHP 发行版本中,会提供对 MySQL caching_sha2_password 扩展的支持。 目前只有 mysql_xdevapi 扩展是 支持 MySQL 的 caching_sha2_password 扩展的。

安装

mysqli扩展在PHP5.0.0中被引入。Mysql Native驱动在PHP5.3.0版本中被引入。

在linux上安装

通用的Unix分发包中会包含PHP可安装的二进制版本。虽然这些二进制版本通常会被构建为支持启用mysql扩展的, 蚕食扩展库自身可能需要依赖其他附加包的安装。因此对包管理的检查会比选择可用的发行版本更重要。

除非你的Unix分发包包含的PHP二进制包的mysqli扩展可用,否则你就需要 从源码构建PHP。如果你希望使用mysql扩展,从PHP源代码构建允许你这样做,并且可以指定每个扩展 使用什么客户端库。

使用Mysql Native Driver 是推荐的选项,会提升性能并且会带来一些Mysql Client Library不允许的访问特性。 什么是Mysql自然驱动器?中对Mysql Native Driver 的优势做了一个简要概述。

/path/to/mysql_config代表了要用来编译mysql客户端/连接mysql服务端的mysql_config程序位置。

PHP 版本默认配置选项: mysqlnd配置选项: libmysql更新日志
5.0.x, 5.1.x, 5.2.xlibmysql不适用--with-mysqli=/path/to/mysql_config 
5.3.xlibmysql--with-mysqli=mysqlnd--with-mysqli=/path/to/mysql_configmysqlnd is now supported
5.4.xmysqlnd--with-mysqli--with-mysqli=/path/to/mysql_configmysqlnd is now the default

请注意Mysql扩展和客户端库是可以自由混合的。比如,可以使用libmysql这个mysql客户端库来启用Mysql扩展,使用 Mysql Native Driver来配置mysqli扩展。所有的扩展和客户端库的顺序都是可能的。

下面的示例使用Mysql Client Library(libmysql)构建了mysql扩展,并且mysqli和 PDO Mysql扩展使用Mysql Native Dirver(作为客户端库):

./configure --with-mysql=/usr/bin/mysql_config  \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd
[other options]

在windows系统安装

在windows上,PHP通常使用二进制安装包进行安装。

PHP 5.0, 5.1, 5.2

当PHP安装后,如果期望使用则可以通过一些配置来开启mysqli并指定客户端库。

mysqli扩展默认并不会开启,因此php.iniphp_mysqli.dll这个DLL 必须开启。为此你需要找到php.ini文件(通常在c:\php),并且你需要确认删除了 [PHP_MYSQLI]部分中的extension=php_mysqli.dll一行行首的注释符号(分号)。

另外,如果你希望使用Mysql client library(libmysql)作为mysqli的驱动器,你需要确保PHP可以访问 客户端库的文件。Mysql Client Library作为文件libmysql.dll包含在windows的PHP分发包中。 这个文件需要在windows系统的PATH环境变量中才可以被成功加载。查看FAQ文档 怎样增加我的PHP目录到Windows的PATH中了解怎样配置环境变量PATH。 把libmysql.dll拷贝到Windows的系统目录(通常是c:\Windows\system)也是适用的, 通常系统目录默认就在系统的PATH环境变量下。然而,我们强烈反对这种做法。

就像开启任何PHP扩展(比如php_mysqli.dll),PHP指令 extension_dir可以被设置为PHP扩展位置的目录路径。 查看windows安装介绍手册。关于此的一个例子是PHP 5中 extension_dir指令的值是c:\php\ext

Note:

如果启动web服务器的时候发生了类似下面这样的错误*"Unable to load dynamic library './php_mysqli.dll'"*, 这就是因为在系统中无法找到php_mysqli.dll或者libmysql.dll

PHP 5.3.0+

在windows上,对于PHP 5.3或更新版本,mysqli扩展默认开启并使用Mysql Native Driver。 这就是说你不需要担心关于访问libmysql.dll的配置。

运行时配置

这些函数的行为受 php.ini 中的设置影响。

名字默认可修改范围更新日志
mysqli.allow_local_infile"1"PHP_INI_SYSTEM自PHP 5.2.4起可用。
mysqli.allow_persistent"1"PHP_INI_SYSTEM自PHP 5.3.0起可用。
mysqli.max_persistent"-1"PHP_INI_SYSTEM自PHP 5.3.0起可用。
mysqli.max_links"-1"PHP_INI_SYSTEM自PHP 5.0.0起可用。
mysqli.default_port"3306"PHP_INI_ALL自PHP 5.0.0起可用。
mysqli.default_socketNULLPHP_INI_ALL自PHP 5.0.0起可用。
mysqli.default_hostNULLPHP_INI_ALL自PHP 5.0.0起可用。
mysqli.default_userNULLPHP_INI_ALL自PHP 5.0.0起可用。
mysqli.default_pwNULLPHP_INI_ALL自PHP 5.0.0起可用。
mysqli.reconnect"0"PHP_INI_SYSTEM自PHP 4.3.5起可用。
mysqli.rollback_on_cached_plinkTRUEPHP_INI_SYSTEM自 PHP 5.6.0 起可用。

关于前面出现的PHP_INI_*系列常量的详细定义,请参阅配置的修改一章。

这是配置指令的简短说明。

mysqli.allow_local_infile integer
允许Mysql的Load Data语句访问PHP角度看的本地文件。

mysqli.allow_persistent integer
开启使用mysqli_connect函数创建持久化连接的能力。

mysqli.max_persistent integer
可以创建的持久化连接的最大数量,设置为0表明不限制。

mysqli.max_links integer
每个进程中Mysql连接的最大数量。

mysqli.default_port integer
当没有指定其他端口号时使用的默认的用于连接数据库服务器的TCP端口号。如果没有设置默认值, 端口号将会按照顺序从环境变量MYSQL_TCP_PORT/etc/services 文件中的mysql-tcp条目或编译期的MYSQL_PORT常量等位置获取。 Win32仅使用MYSQL_PORT常量。

mysqli.default_socket string
当连接到本地数据库服务器时如果没有指定其他socket名称,使用的默认socket名称。

mysqli.default_host string
当连接到数据库服务器时, 如果没有指定其他主机地址,使用的默认服务器主机。不要在 安全模式下使用。

mysqli.default_user string
当连接到数据库服务器时,如果没有指定其他用户名,使用的默认用户名。不要在 安全模式下使用。

mysqli.default_pw string
当连接到数据库服务器时,如果没有指定其他密码,使用的默认密码。不要在 安全模式下使用。

mysqli.reconnect integer
连接丢失时是否自动重新连接。

Note: This php.ini setting is ignored by the mysqlnd driver.

mysqli.rollback_on_cached_plink bool
If this option is enabled, closing a persistent connection will rollback any pending transactions of this connection before it is put back into the persistent connection pool. Otherwise, pending transactions will be rolled back only when the connection is reused, or when it is actually closed.

用户不能通过API调用或运行时配置来设置MYSQL_OPT_READ_TIMEOUT。 注意,如果可能这样做那么libmysql和流对MYSQL_OPT_READ_TIMEOUT 的值将会有不同的解释。

资源类型

此扩展没有定义资源类型。

mysqli 扩展和持久化连接

从 PHP 5.3 mysqli 扩展开始支持持久化连接。 持久化连接已经在 PDO MYSQL 和 ext/mysql 中提供支持。 持久化连接的目的在于重用客户端到服务器之间的连接, 而不是每次在需要的时候都重新建立一个连接。 由于持久化连接可以将已经建立的连接缓存起来,以备后续的使用, 所以省去了建立新的连接的开销, 因此可以带来性能上的提升。

不像 mysql 扩展,mysqli 没有提供一个特殊的方法用于打开持久化连接。 需要打开一个持久化连接时,你必须在 连接时在主机名前增加p:

使用持久化连接也会存在一些风险, 因为在缓存中的连接可能处于一种不可预测的状态。 例如,如果客户端未能正常关闭连接, 可能在这个连接上残留了对库表的锁, 那么当这个连接被其他请求重用的时候,这个连接还是处于 “有锁的状态”。 所以,如果要很好的使用持久化连接,那么要求代码在和数据库进行交互的时候, 确保做好清理工作,保证被缓存的连接是一个干净的,没有残留的状态。

mysqli 扩展的持久化连接提供了内建的清理处理代码。 mysqli 所做的清理工作包括:

  • 回滚处于活动状态的事务

  • 关闭并且删除临时表

  • 对表解锁

  • 重置会话变量

  • 关闭预编译 SQL 语句(在PHP中经常发生)

  • 关闭处理程序

  • 释放通过 GET_LOCK 获得的锁

这确保了将连接返回到连接池的时候, 它处于一种“干净”的状态,可以被其他客户端进程所使用。

mysqli 扩展 通过自动调用 C-API 函数 mysql_change_user() 来完成这个清理工作。

自动清理的特性有优点也有缺点。 优点是程序员不再需要担心附加的清理代码, 因为它们会自动调用。 然而缺点就是 性能 可能会 慢一点, 因为每次从连接池返回一个连接都需要执行这些清理代码。

这个自动清理的代码可以通过在编译 php 时定义 MYSQLI_NO_CHANGE_USER_ON_PCONNECT 来关闭。

Note:

mysqli 扩展在使用 MySQL Native Driver 或 Mysql Client Library(libmysql)时都支持持久化连接。

预定义常量

下列常量由此扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MYSQLI_READ_DEFAULT_GROUP
Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE
Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT
Connect timeout in seconds

MYSQLI_OPT_LOCAL_INFILE
Enables command LOAD LOCAL INFILE

MYSQLI_INIT_COMMAND
Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL
Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library

MYSQLI_CLIENT_COMPRESS
Use compression protocol

MYSQLI_CLIENT_INTERACTIVE
Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.

MYSQLI_CLIENT_IGNORE_SPACE
Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA
Don't allow the db_name.tbl_name.col_name syntax.

MYSQLI_CLIENT_MULTI_QUERIES
Allows multiple semicolon-delimited queries in a single mysqli_query call.

MYSQLI_STORE_RESULT
For using buffered resultsets

MYSQLI_USE_RESULT
For using unbuffered resultsets

MYSQLI_ASSOC
Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM
Columns are returned into the array having an enumerated index.

MYSQLI_BOTH
Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG
Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG
Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG
Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG
Field is part of an index.

MYSQLI_BLOB_FLAG
Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG
Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG
Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG
Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG
Field is defined as TIMESTAMP

MYSQLI_SET_FLAG
Field is defined as SET

MYSQLI_NUM_FLAG
Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG
Field is part of an multi-index

MYSQLI_GROUP_FLAG
Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL
Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL
Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT
Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY
Field is defined as TINYINT

MYSQLI_TYPE_SHORT
Field is defined as SMALLINT

MYSQLI_TYPE_LONG
Field is defined as INT

MYSQLI_TYPE_FLOAT
Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE
Field is defined as DOUBLE

MYSQLI_TYPE_NULL
Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP
Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG
Field is defined as BIGINT

MYSQLI_TYPE_INT24
Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE
Field is defined as DATE

MYSQLI_TYPE_TIME
Field is defined as TIME

MYSQLI_TYPE_DATETIME
Field is defined as DATETIME

MYSQLI_TYPE_YEAR
Field is defined as YEAR

MYSQLI_TYPE_NEWDATE
Field is defined as DATE

MYSQLI_TYPE_INTERVAL
Field is defined as INTERVAL

MYSQLI_TYPE_ENUM
Field is defined as ENUM

MYSQLI_TYPE_SET
Field is defined as SET

MYSQLI_TYPE_TINY_BLOB
Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB
Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB
Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB
Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING
Field is defined as VARCHAR

MYSQLI_TYPE_STRING
Field is defined as STRING

MYSQLI_TYPE_CHAR
Field is defined as CHAR

MYSQLI_TYPE_GEOMETRY
Field is defined as GEOMETRY

MYSQLI_NEED_DATA
More data available for bind variable

MYSQLI_NO_DATA
No more data available for bind variable

MYSQLI_DATA_TRUNCATED
Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

MYSQLI_ENUM_FLAG
Field is defined as ENUM. Available since PHP 5.3.0.

MYSQLI_CURSOR_TYPE_FOR_UPDATE

MYSQLI_CURSOR_TYPE_NO_CURSOR

MYSQLI_CURSOR_TYPE_READ_ONLY

MYSQLI_CURSOR_TYPE_SCROLLABLE

MYSQLI_STMT_ATTR_CURSOR_TYPE

MYSQLI_STMT_ATTR_PREFETCH_ROWS

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH

MYSQLI_SET_CHARSET_NAME

MYSQLI_REPORT_INDEX
Report if no index or bad index was used in a query.

MYSQLI_REPORT_ERROR
Report errors from mysqli function calls.

MYSQLI_REPORT_STRICT
Throw a mysqli_sql_exception for errors instead of warnings.

MYSQLI_REPORT_ALL
Set all options on (report all).

MYSQLI_REPORT_OFF
Turns reporting off.

MYSQLI_DEBUG_TRACE_ENABLED
Is set to 1 if mysqli_debug functionality is enabled.

MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED

MYSQLI_SERVER_QUERY_NO_INDEX_USED

MYSQLI_REFRESH_GRANT
Refreshes the grant tables.

MYSQLI_REFRESH_LOG
Flushes the logs, like executing the FLUSH LOGS SQL statement.

MYSQLI_REFRESH_TABLES
Flushes the table cache, like executing the FLUSH TABLES SQL statement.

MYSQLI_REFRESH_HOSTS
Flushes the host cache, like executing the FLUSH HOSTS SQL statement.

MYSQLI_REFRESH_STATUS
Reset the status variables, like executing the FLUSH STATUS SQL statement.

MYSQLI_REFRESH_THREADS
Flushes the thread cache.

MYSQLI_REFRESH_SLAVE
On a slave replication server: resets the master server information, and restarts the slave. Like executing the RESET SLAVE SQL statement.

MYSQLI_REFRESH_MASTER
On a master replication server: removes the binary log files listed in the binary log index, and truncates the index file. Like executing the RESET MASTER SQL statement.

Notes

Some implementation notes:

  1. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5.3.

  2. Note there are different internal implementations within libmysqlclient and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. Generally speaking, mysqlnd will allocate significantly less memory. For example, if there is a POINT column in a result set, libmysqlclient may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. Memory allocation is much lower, less than 50 bytes, if using mysqlnd.

MySQLi 扩展的功能概述

mysqli 方法的概述

mysqli 类

面向对象接口

面向过程接口

别名 (勿使用)

描述

属性

$mysqli::affected_rows

mysqli_affected_rows

N/A

获取上次 Mysql 操作受影响的行数

$mysqli::client_info

mysqli_get_client_info

N/A

返回 Mysql 客户端版本信息,类型为 string

$mysqli::client_version

mysqli_get_client_version

N/A

返回 Mysql 客户端版本信息,类型为 integer

$mysqli::connect_errno

mysqli_connect_errno

N/A

返回最后一次连接数据库的错误代码

$mysqli::connect_error

mysqli_connect_error

N/A

返回最后一次连接数据库的错误描述,类型为字符串

$mysqli::errno

mysqli_errno

N/A

返回最近一次函数调用所产生的错误代码

$mysqli::error

mysqli_error

N/A

返回最近一次错误代码的描述,类型是字符串

$mysqli::field_count

mysqli_field_count

N/A

返回最近一次查询中,包含的列的数量

$mysqli::host_info

mysqli_get_host_info

N/A

返回字符串,表示数据库连接所使用的类型

$mysqli::protocol_version

mysqli_get_proto_info

N/A

返回使用的 MySQL 协议的版本信息

$mysqli::server_info

mysqli_get_server_info

N/A

返回 MySQL 服务器的版本

$mysqli::server_version

mysqli_get_server_version

N/A

返回 MySQL 服务器的版本,类型为 integer

$mysqli::info

mysqli_info

N/A

获取最近一次数据库查询的信息

$mysqli::insert_id

mysqli_insert_id

N/A

返回上次查询中所使用的自动生成的 ID

$mysqli::sqlstate

mysqli_sqlstate

N/A

返回上次 MySQL 操作的数据库状态错误(SQLSTATE error)

$mysqli::warning_count

mysqli_warning_count

N/A

根据数据库链接,返回最后一次数据库查询内警告的数量

Methods

mysqli::autocommit

mysqli_autocommit

N/A

打开或关闭数据库的自动提交(auto-committing)功能

mysqli::change_user

mysqli_change_user

N/A

更改指定数据库连接所使用的用户

mysqli::character_set_name, mysqli::client_encoding

mysqli_character_set_name

mysqli_client_encoding

返回数据库连接的默认字符集

mysqli::close

mysqli_close

N/A

关闭先前打开的数据库连接

mysqli::commit

mysqli_commit

N/A

提交当前的数据库事务

mysqli::__construct

mysqli_connect

N/A

打开新连接到 MySQL 服务器[注意:静态方法]

mysqli::debug

mysqli_debug

N/A

执行调试操作

mysqli::dump_debug_info

mysqli_dump_debug_info

N/A

将调试信息转储到日志中

mysqli::get_charset

mysqli_get_charset

N/A

返回包含字符集信息的对象

mysqli::get_connection_stats

mysqli_get_connection_stats

N/A

返回客户端连接的统计信息。仅可用于 mysqlnd

mysqli::get_client_info

mysqli_get_client_info

N/A

返回 MySQL 客户端版本的字符串信息

mysqli::get_client_stats

mysqli_get_client_stats

N/A

返回每个客户端进程的统计信息。 仅可用于 mysqlnd

mysqli::get_cache_stats

mysqli_get_cache_stats

N/A

返回客户端的 Zval 缓存统计信息。 仅可用于 mysqlnd

mysqli::get_server_info

mysqli_get_server_info

N/A

返回 MySQLi 连接上的 MySQL 服务器的版本字符串

mysqli::get_warnings

mysqli_get_warnings

N/A

文档暂缺

mysqli::init

mysqli_init

N/A

初始化 MySQLi,返回资源类型的值,可供 mysqli_real_connect 使用。 [不要在对象上调用,它返回了 $mysqli 对象]

mysqli::kill

mysqli_kill

N/A

请求服务器杀死一个 MySQL 线程

mysqli::more_results

mysqli_more_results

N/A

检查多语句查询内是否还有更多查询结果

mysqli::multi_query

mysqli_multi_query

N/A

在数据库内执行多语句查询

mysqli::next_result

mysqli_next_result

N/A

从 multi_query 中准备下一个结果集

mysqli::options

mysqli_options

mysqli_set_opt

设置选项

mysqli::ping

mysqli_ping

N/A

Ping 服务器链接,如果链接已经断开,尝试重连

mysqli::prepare

mysqli_prepare

N/A

准备(prepare)需要执行的 SQL 语句

mysqli::query

mysqli_query

N/A

在数据库内执行查询

mysqli::real_connect

mysqli_real_connect

N/A

打开一个 MySQL 服务端的连接

mysqli::real_escape_string, mysqli::escape_string

mysqli_real_escape_string

mysqli_escape_string

转义特殊字符,用于 SQL 语句,该转换会考虑连接中当前的字符集

mysqli::real_query

mysqli_real_query

N/A

执行 SQL 查询

mysqli::refresh

mysqli_refresh

N/A

刷新表或缓存,或重置复制(replication)服务器信息

mysqli::rollback

mysqli_rollback

N/A

回滚当前事务

mysqli::select_db

mysqli_select_db

N/A

为数据库查询设置默认数据库

mysqli::set_charset

mysqli_set_charset

N/A

设置默认的客户端字符集

mysqli::set_local_infile_default

mysqli_set_local_infile_default

N/A

清除用户设置的 load data local infile 命令的处理程序

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

N/A

设置 LOAD DATA LOCAL INFILE 命令执行的回调函数

mysqli::ssl_set

mysqli_ssl_set

N/A

使用 SSL 建立安全连接

mysqli::stat

mysqli_stat

N/A

获取当前系统状态

mysqli::stmt_init

mysqli_stmt_init

N/A

初始化语句并且返回供 mysqli_stmt_prepare 使用的对象

mysqli::store_result

mysqli_store_result

N/A

传输最后一个查询的结果集

mysqli::thread_id

mysqli_thread_id

N/A

返回当前连接的线程ID

mysqli::thread_safe

mysqli_thread_safe

N/A

返回是否设定了线程安全

mysqli::use_result

mysqli_use_result

N/A

初始化一个结果集的取回

mysqli_stmt 的方法概述

MySQL_STMT

面向对象接口

面向过程接口

别名 (勿使用)

描述

属性

$mysqli_stmt::affected_rows

mysqli_stmt_affected_rows

N/A

返回受上次执行语句影响的总行数:修改、删除或插入

$mysqli_stmt::errno

mysqli_stmt_errno

N/A

返回最近一次语句调用的错误代码

$mysqli_stmt::error

mysqli_stmt_error

N/A

返回最后一条语句错误的字符串描述

$mysqli_stmt::field_count

mysqli_stmt_field_count

N/A

返回语句内的字段数量 - 文档暂缺

$mysqli_stmt::insert_id

mysqli_stmt_insert_id

N/A

获取上次 INSERT 操作生成的ID

$mysqli_stmt::num_rows

mysqli_stmt_num_rows

N/A

返回语句结果集中的行数

$mysqli_stmt::param_count

mysqli_stmt_param_count

mysqli_param_count

返回语句中参数的数量

$mysqli_stmt::sqlstate

mysqli_stmt_sqlstate

N/A

返回上次执行 SQL 语句的 SQLSTATE 错误代码

方法

mysqli_stmt::attr_get

mysqli_stmt_attr_get

N/A

用于获取语句属性的当前值

mysqli_stmt::attr_set

mysqli_stmt_attr_set

N/A

用于修改 prepared 语句的行为

mysqli_stmt::bind_param

mysqli_stmt_bind_param

mysqli_bind_param

绑定变量参数到 prepared 语句

mysqli_stmt::bind_result

mysqli_stmt_bind_result

mysqli_bind_result

绑定变量参数到 prepared 语句,用于结果存储

mysqli_stmt::close

mysqli_stmt_close

N/A

关闭 prepared 语句

mysqli_stmt::data_seek

mysqli_stmt_data_seek

N/A

定位到结果集中的任意行

mysqli_stmt::execute

mysqli_stmt_execute

mysqli_execute

执行 prepared 查询

mysqli_stmt::fetch

mysqli_stmt_fetch

mysqli_fetch

获取 prepared 语句中的结果,到指定变量中

mysqli_stmt::free_result

mysqli_stmt_free_result

N/A

释放给定语句处理存储的结果集所占内存

mysqli_stmt::get_result

mysqli_stmt_get_result

N/A

获取 prepared 语句中的结果。 仅可用于 mysqlnd

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

N/A

暂无文档

mysqli_stmt::more_results

mysqli_stmt_more_results

N/A

检查多语句查询中是否还有更多结果

mysqli_stmt::next_result

mysqli_stmt_next_result

N/A

读取多语句查询中下一条结果

mysqli_stmt::num_rows

mysqli_stmt_num_rows

N/A

参见 $mysqli_stmt::num_rows 中的属性

mysqli_stmt::prepare

mysqli_stmt_prepare

N/A

准备执行 SQL 语句

mysqli_stmt::reset

mysqli_stmt_reset

N/A

重置 prepare 语句

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

mysqli_get_metadata

返回 prepare 语句结果集内的元数据

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

mysqli_send_long_data

以块形式发送数据

mysqli_stmt::store_result

mysqli_stmt_store_result

N/A

从 prepare 语句中传输储存结果集

mysqli_result 方法概述

mysqli_result

面向对象接口

面向过程接口

别名 (勿使用)

描述

属性

$mysqli_result::current_field

mysqli_field_tell

N/A

获取当前字段在结果集指针中的开始位置

$mysqli_result::field_count

mysqli_num_fields

N/A

获取结果中字段数量

$mysqli_result::lengths

mysqli_fetch_lengths

N/A

返回结果集中当前行的列长度

$mysqli_result::num_rows

mysqli_num_rows

N/A

获取结果中行的数量

方法

mysqli_result::data_seek

mysqli_data_seek

N/A

将结果中的结果指针调整到任意行

mysqli_result::fetch_all

mysqli_fetch_all

N/A

抓取所有的结果行并且以关联数据,数值索引数组,或者两者皆有的方式返回结果集。 仅可用于 mysqlnd

mysqli_result::fetch_array

mysqli_fetch_array

N/A

以一个关联数组,数值索引数组,或者两者皆有的方式抓取一行结果

mysqli_result::fetch_assoc

mysqli_fetch_assoc

N/A

以一个关联数组方式抓取一行结果

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

N/A

抓取一个单字段的元数据

mysqli_result::fetch_field

mysqli_fetch_field

N/A

返回结果集中的下一个字段

mysqli_result::fetch_fields

mysqli_fetch_fields

N/A

返回一个代表结果集字段的对象数组

mysqli_result::fetch_object

mysqli_fetch_object

N/A

以一个对象的方式返回一个结果集中的当前行

mysqli_result::fetch_row

mysqli_fetch_row

N/A

以一个枚举数组方式返回一行结果

mysqli_result::field_seek

mysqli_field_seek

N/A

设置结果指针到特定的字段开始位置

mysqli_result::free, mysqli_result::close, mysqli_result::free_result

mysqli_free_result

N/A

释放与一个结果集相关的内存

mysqli_driver 的方法概述

MySQL_Driver

面向对象接口

面向过程接口

别名 (勿使用)

描述

属性

N/A

方法

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

N/A

文档暂缺

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

N/A

文档暂缺

Note:

提供函数的别名,目的仅为向下兼容。不要在新项目中使用!

简介

代表PHP和Mysql数据库之间的一个连接。

类摘要

mysqli

class mysqli {

/* 属性 */

int$mysqli->affected_rows;

int$mysqli->connect_errno;

string$mysqli->connect_error;

int$errno;

array$mysqli->error_list;

string$mysqli->error;

int$mysqli->field_count;

string$mysqli->client_info;

int$mysqli->client_version;

string$mysqli->host_info;

string$mysqli->protocol_version;

string$mysqli->server_info;

int$mysqli->server_version;

string$mysqli->info;

mixed$mysqli->insert_id;

string$mysqli->sqlstate;

int$mysqli->thread_id;

int$mysqli->warning_count;

/* 方法 */

int mysqli_affected_rows ( mysqli $link )

bool autocommit ( bool $mode )

public bool begin_transaction ([ int $flags = 0 [, string $name ]] )

bool change_user ( string $user , string $password , string $database )

string character_set_name ( void )

bool close ( void )

bool commit ( void )

int mysqli_connect_errno ( void )

string mysqli_connect_error ( void )

void connect ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )

bool debug ( string $message )

bool dump_debug_info ( void )

int mysqli_errno ( mysqli $link )

array mysqli_error_list ( mysqli $link )

string mysqli_error ( mysqli $link )

int mysqli_field_count ( mysqli $link )

object get_charset ( void )

string get_client_info ( void )

int mysqli_get_client_version ( mysqli $link )

bool get_connection_stats ( void )

string mysqli_get_host_info ( mysqli $link )

int mysqli_get_proto_info ( mysqli $link )

string mysqli_get_server_info ( mysqli $link )

int mysqli_get_server_version ( mysqli $link )

mysqli_warning get_warnings ( void )

string mysqli_info ( mysqli $link )

mysqli init ( void )

mixed mysqli_insert_id ( mysqli $link )

bool kill ( int $processid )

bool more_results ( void )

bool multi_query ( string $query )

bool next_result ( void )

bool options ( int $option , mixed $value )

bool ping ( void )

public static int poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] )

mysqli_stmt prepare ( string $query )

mixed query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

bool real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

string escape_string ( string $escapestr )

bool real_query ( string $query )

public mysqli_result reap_async_query ( void )

public bool refresh ( int $options )

public bool release_savepoint ( string $name )

bool rollback ( void )

int rpl_query_type ( string $query )

public bool savepoint ( string $name )

bool select_db ( string $dbname )

bool send_query ( string $query )

bool set_charset ( string $charset )

void mysqli_set_local_infile_default ( mysqli $link )

bool set_local_infile_handler ( mysqli $link , callable $read_func )

string mysqli_sqlstate ( mysqli $link )

bool ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

string stat ( void )

mysqli_stmt stmt_init ( void )

mysqli_result store_result ([ int $option ] )

int mysqli_thread_id ( mysqli $link )

bool mysqli_thread_safe ( void )

mysqli_result use_result ( void )

int mysqli_warning_count ( mysqli $link )

}

mysqli::$affected_rows

mysqli_affected_rows

Gets the number of affected rows in a previous MySQL operation

说明

面向对象风格

int$mysqli->affected_rows;

过程化风格

int mysqli_affected_rows ( mysqli $link )

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

For SELECT statements mysqli_affected_rows works like mysqli_num_rows.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Note:

If the number of affected rows is greater than the maximum integer value(PHP_INT_MAX), the number of affected rows will be returned as a string.

范例

示例 #1 $mysqli->affected_rows example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

参见

  • mysqli_num_rows
  • mysqli_info

mysqli::autocommit

mysqli_autocommit

打开或关闭本次数据库连接的自动命令提交事务模式

说明

面向对象风格

bool mysqli::autocommit ( bool $mode )

过程化风格

bool mysqli_autocommit ( mysqli $link , bool $mode )

打开或关闭本次数据库连接的自动命令提交事务模式。

如需要确认当前连接的自动事务提交状态,可执行这个SQL请求SELECT @@autocommit.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

mode
Whether to turn on auto-commit or not.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

注释

Note:

这个方法不会在不支持事务处理的表单查询中生效,如MyISAM或 ISAM。

范例

示例 #1 mysqli::autocommit example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Autocommit is 1

参见

  • mysqli_commit
  • mysqli_rollback

mysqli::begin_transaction

mysqli_begin_transaction

Starts a transaction

说明

面向对象风格 (method):

public bool mysqli::begin_transaction ([ int $flags = 0 [, string $name ]] )

过程化风格:

bool mysqli_begin_transaction ( mysqli $link [, int $flags = 0 [, string $name ]] )

Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see » http://dev.mysql.com/doc/mysql/en/commit.html.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

flags
Valid flags are:

  • MYSQLI_TRANS_START_READ_ONLY: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_READ_WRITE: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

name
Savepoint name for the transaction.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 $mysqli->begin_transaction example

面向对象风格

<?php
$mysqli = new mysqli("127.0.0.1", "my_user", "my_password", "sakila");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);

$mysqli->query("SELECT first_name, last_name FROM actor");
$mysqli->commit();

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_ONLY);

mysqli_query($link, "SELECT first_name, last_name FROM actor LIMIT 1");
mysqli_commit($link);

mysqli_close($link);
?>

参见

  • mysqli_autocommit
  • mysqli_commit
  • mysqli_rollback

mysqli::change_user

mysqli_change_user

Changes the user of the specified database connection

说明

面向对象风格

bool mysqli::change_user ( string $user , string $password , string $database )

过程化风格

bool mysqli_change_user ( mysqli $link , string $user , string $password , string $database )

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

user
The MySQL user name.

password
The MySQL password.

database
The database to change to.

If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db function.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

注释

Note:

Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

范例

示例 #1 mysqli::change_user example

面向对象风格

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Default database: world
Value of variable a is NULL

参见

  • mysqli_connect
  • mysqli_select_db

mysqli::character_set_name

mysqli_character_set_name

返回当前数据库连接的默认字符编码

说明

面向对象风格

string mysqli::character_set_name ( void )

过程化风格

string mysqli_character_set_name ( mysqli $link )

返回当前数据库连接的默认字符编码。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

The default character set for the current connection

范例

示例 #1 mysqli::character_set_name example

面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = $mysqli->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Current character set is latin1_swedish_ci

参见

  • mysqli_set_charset
  • mysqli_client_encoding
  • mysqli_real_escape_string

mysqli::close

mysqli_close

关闭先前打开的数据库连接

说明

面向对象风格

bool mysqli::close ( void )

过程化风格

bool mysqli_close ( mysqli $link )

关闭先前打开的数据库连接

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

See mysqli_connect.

参见

  • mysqli::__construct
  • mysqli_init
  • mysqli_real_connect

mysqli::commit

mysqli_commit

提交一个事务

说明

面向对象风格

bool mysqli::commit ( void )

过程化风格

bool mysqli_commit ( mysqli $link )

提交数据库连接的当前事务

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::commit example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
$mysqli->commit();

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?>

参见

  • mysqli_autocommit
  • mysqli_rollback

mysqli::$connect_errno

mysqli_connect_errno

Returns the error code from last connect call

说明

面向对象风格

int$mysqli->connect_errno;

过程化风格

int mysqli_connect_errno ( void )

Returns the last error code number from the last call to mysqli_connect.

Note:

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

返回值

An error code value for the last call to mysqli_connect, if it failed. zero means no error occurred.

范例

示例 #1 $mysqli->connect_errno example

面向对象风格

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

过程化风格

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

以上例程会输出:

Connect Error: 1045

参见

  • mysqli_connect
  • mysqli_connect_error
  • mysqli_errno
  • mysqli_error
  • mysqli_sqlstate

mysqli::$connect_error

mysqli_connect_error

Returns a string description of the last connect error

说明

面向对象风格

string$mysqli->connect_error;

过程化风格

string mysqli_connect_error ( void )

Returns the last error message string from the last call to mysqli_connect.

返回值

A string that describes the error. NULL is returned if no error occurred.

范例

示例 #1 $mysqli->connect_error example

面向对象风格

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

过程化风格

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

以上例程会输出:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

注释

Warning

The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error function if compatibility with earlier PHP versions is required.

参见

  • mysqli_connect
  • mysqli_connect_errno
  • mysqli_errno
  • mysqli_error
  • mysqli_sqlstate

mysqli::__construct

mysqli::connect

mysqli_connect

Open a new connection to the MySQL server

说明

面向对象风格

mysqli::__construct ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )

void mysqli::connect ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )

过程化风格

mysqli mysqli_connect ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )

Opens a connection to the MySQL Server.

参数

host
Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Prepending host by p: opens a persistent connection. mysqli_change_user is automatically called on connections opened from the connection pool.

username
The MySQL user name.

passwd
If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password is provided or not).

dbname
If provided will specify the default database to be used when performing queries.

port
Specifies the port number to attempt to connect to the MySQL server.

socket
Specifies the socket or named pipe that should be used.

Note:

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

返回值

Returns an object which represents the connection to a MySQL Server, 或者在失败时返回 FALSE.

更新日志

版本说明
5.3.0Added the ability of persistent connections.

范例

示例 #1 mysqli::__construct example

面向对象风格

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

面向对象风格 when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

过程化风格

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

以上例程会输出:

Success... MySQL host info: localhost via TCP/IP

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手/认证时发送,并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 class="function">mysqli_init 之后,class="function">mysqli_real_connect 之前先调用 class="function">mysqli_options 来指定。

Note:

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the class="function">mysqli_connect_error function or the mysqli->connect_error property as in the preceding examples.

Note:

If it is necessary to set options, such as the connection timeout, mysqli_real_connect must be used instead.

Note:

Calling the constructor with no parameters is the same as calling mysqli_init.

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

参见

  • mysqli_real_connect
  • mysqli_options
  • mysqli_connect_errno
  • mysqli_connect_error
  • mysqli_close

mysqli::debug

mysqli_debug

Performs debugging operations

说明

面向对象风格

bool mysqli::debug ( string $message )

过程化风格

bool mysqli_debug ( string $message )

Performs debugging operations using the Fred Fish debugging library.

参数

message
A string representing the debugging operation to perform

返回值

Returns TRUE.

注释

Note:

To use the mysqli_debug function you must compile the MySQL client library to support debugging.

范例

示例 #1 Generating a Trace File

<?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");

?>

参见

  • mysqli_dump_debug_info
  • mysqli_report

mysqli::dump_debug_info

mysqli_dump_debug_info

将调试信息输出到日志

说明

面向对象风格

bool mysqli::dump_debug_info ( void )

过程化风格

bool mysqli_dump_debug_info ( mysqli $link )

这个函数设计用于超级权限用户执行将调试信息输出到连接相关的MySQL服务端日志

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_debug

mysqli::errno

mysqli_errno

返回最近函数调用的错误代码

说明

面向对象风格

mysqli

int$errno;

过程化风格

int mysqli_errno ( mysqli $link )

返回最近的mysqli函数调用产生的错误代码.

客户端错误在Mysqlerrmsg.h头文件中列出, 服务端错误好在mysqld_error.h中列出. 在mysql源码分发包中的Docs/mysqld_error.txt你可以发现一个完整的错误消息和错误号.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

最后一次调用产生的错误代码, 返回0代表没有错误发生.

范例

示例 #1 mysqli->errno example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errorcode: %d\n", mysqli_errno($link));
}

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

Errorcode: 1193

参见

  • mysqli_connect_errno
  • mysqli_connect_error
  • mysqli_error
  • mysqli_sqlstate

mysqli::$error_list

mysqli_error_list

Returns a list of errors from the last command executed

说明

面向对象风格

array$mysqli->error_list;

过程化风格

array mysqli_error_list ( mysqli $link )

Returns a array of errors for the most recent MySQLi function call that can succeed or fail.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

A list of errors, each as an associative array containing the errno, error, and sqlstate.

范例

示例 #1 $mysqli->error_list example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "nobody", "");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    print_r($mysqli->error_list);
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    print_r(mysqli_error_list($link));
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Array
(
    [0] => Array
        (
            [errno] => 1193
            [sqlstate] => HY000
            [error] => Unknown system variable 'a'
        )

)

参见

  • mysqli_connect_errno
  • mysqli_connect_error
  • mysqli_error
  • mysqli_sqlstate

mysqli::$error

mysqli_error

Returns a string description of the last error

说明

面向对象风格

string$mysqli->error;

过程化风格

string mysqli_error ( mysqli $link )

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

A string that describes the error. An empty string if no error occurred.

范例

示例 #1 $mysqli->error example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Error message: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Error message: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Error message: Unknown system variable 'a'

参见

  • mysqli_connect_errno
  • mysqli_connect_error
  • mysqli_errno
  • mysqli_sqlstate

mysqli::$field_count

mysqli_field_count

Returns the number of columns for the most recent query

说明

面向对象风格

int$mysqli->field_count;

过程化风格

int mysqli_field_count ( mysqli $link )

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

An integer representing the number of fields in a result set.

范例

示例 #1 $mysqli->field_count example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");


$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();

    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

mysqli::get_charset

mysqli_get_charset

Returns a character set object

说明

面向对象风格

object mysqli::get_charset ( void )

过程化风格

object mysqli_get_charset ( mysqli $link )

Returns a character set object providing several properties of the current active character set.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

The function returns a character set object with the following properties:

charset
Character set name

collation
Collation name

dir
Directory the charset description was fetched from (?) or "" for built-in character sets

min_length
Minimum character length in bytes

max_length
Maximum character length in bytes

number
Internal character set number

state
Character set status (?)

范例

示例 #1 mysqli::get_charset example

面向对象风格

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

过程化风格

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  var_dump(mysqli_get_charset($db));
?>

以上例程会输出:

object(stdClass)#2 (7) {
  ["charset"]=>
  string(6) "latin1"
  ["collation"]=>
  string(17) "latin1_swedish_ci"
  ["dir"]=>
  string(0) ""
  ["min_length"]=>
  int(1)
  ["max_length"]=>
  int(1)
  ["number"]=>
  int(8)
  ["state"]=>
  int(801)
}

参见

  • mysqli_character_set_name
  • mysqli_set_charset

mysqli::$client_info

mysqli::get_client_info

mysqli_get_client_info

获取 MySQL 客户端信息

说明

面向对象风格

string$mysqli->client_info;

string mysqli::get_client_info ( void )

过程化风格

string mysqli_get_client_info ( mysqli $link )

返回 MySQL 客户端库的版本信息。

返回值

返回 MySQL 客户端库的版本信息。

范例

示例 #1 mysqli_get_client_info

<?php

/* 获取客户端版本新的时候,
   无需建立到数据库的连接 */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

参见

  • mysqli_get_client_version
  • mysqli_get_server_info
  • mysqli_get_server_version

mysqli_get_client_version

mysqli::$client_version

作为一个整数返回MySQL客户端的版本

说明

面向对象风格

int$mysqli->client_version;

过程化风格

int mysqli_get_client_version ( mysqli $link )

作为一个整数返回客户端版本号.

返回值

一个表述MySQL客户端库版本的数字的格式: main_version*10000 + minor_version *100 + sub_version. 举个例子: 4.1.0 将返回 40100.

这有助于快速确定客户端库的版本来辨别是否有某些特性存在.

范例

示例 #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

参见

  • mysqli_get_client_info
  • mysqli_get_server_info
  • mysqli_get_server_version

mysqli::get_connection_stats

mysqli_get_connection_stats

返回客户端连接的统计数据

说明

面向对象风格

bool mysqli::get_connection_stats ( void )

过程化风格

array mysqli_get_connection_stats ( mysqli $link )

返回客户端连接的统计数据, 仅可用于 mysqlnd。。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

返回一个数组,包含客户端连接的统计数据,否则 FALSE

范例

示例 #1 A mysqli_get_connection_stats 例程

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

以上例程的输出类似于:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

参见

mysqli::$host_info

mysqli_get_host_info

返回一个表述使用的连接类型的字符串

说明

面向对象风格

string$mysqli->host_info;

过程化风格

string mysqli_get_host_info ( mysqli $link )

返回一个字符串,描述被link 参数所表述的连接 (包括服务器主机名).

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

一个特征字符串,表述服务器主机名和连接类型.

范例

示例 #1 $mysqli->host_info example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Host info: Localhost via UNIX socket

参见

  • mysqli_get_proto_info

mysqli::$protocol_version

mysqli_get_proto_info

返回MySQL使用的协议版本号

说明

面向对象风格

string$mysqli->protocol_version;

过程化风格

int mysqli_get_proto_info ( mysqli $link )

返回一个整数,表述 被link参数所表述的连接 所使用的MySQL协议的版本号.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

返回一个整数来表述协议的版本号.

范例

示例 #1 $mysqli->protocol_version example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Protocol version: 10

参见

  • mysqli_get_host_info

mysqli::$server_info

mysqli_get_server_info

返回MySQL服务器的版本号

说明

面向对象风格

string$mysqli->server_info;

过程化风格

string mysqli_get_server_info ( mysqli $link )

返回一个字符串,表述MySQLi扩展连接的MySQL服务器的版本号.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

一个特征字符串,表述服务器的版本.

范例

示例 #1 $mysqli->server_info example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Server version: 4.1.2-alpha-debug

参见

  • mysqli_get_client_info
  • mysqli_get_client_version
  • mysqli_get_server_version

mysqli::$server_version

mysqli_get_server_version

作为一个整数返回MySQL服务器的版本

说明

面向对象风格

int$mysqli->server_version;

过程化风格

int mysqli_get_server_version ( mysqli $link )

mysqli_get_server_version函数以整数的形式返回被连接的link参数所表述的服务器的版本.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

一个整数表述的服务器版本.

版本号的格式是 main_version * 10000 + minor_version * 100 + sub_version (例如: 版本 4.1.0 是 40100).

范例

示例 #1 $mysqli->server_version example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Server version: 40102

参见

  • mysqli_get_client_info
  • mysqli_get_client_version
  • mysqli_get_server_info

mysqli::get_warnings

mysqli_get_warnings

Get result of SHOW WARNINGS

说明

面向对象风格

mysqli_warning mysqli::get_warnings ( void )

过程化风格

mysqli_warning mysqli_get_warnings ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

mysqli::$info

mysqli_info

返回最近执行的 SQL 语句的信息

说明

面向对象风格

string$mysqli->info;

过程化风格

string mysqli_info ( mysqli $link )

mysqli_info 函数返回一个包含 最近执行的 SQL 语句信息的字符串。 下面有一些参考样例:

SQL 语句类型返回结果字符串示例
INSERT INTO...SELECT...Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...)Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ...Records: 3 Duplicates: 0 Warnings: 0
UPDATE ...Rows matched: 40 Changed: 40 Warnings: 0

Note:

如果所执行的 SQL 语句不是上面列出来的这几种类型的, class="function">mysqli_info 函数会返回一个空字符串。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

最近执行的 SQL 语句的相关信息。

范例

示例 #1 $mysqli->info 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

Records: 150  Duplicates: 0  Warnings: 0

参见

  • mysqli_affected_rows
  • mysqli_warning_count
  • mysqli_num_rows

mysqli::init

mysqli_init

初始化 MySQLi 并返回一个资源类型的值,这个值可以作为 mysqli_real_connect() 函数的传入参数

说明

面向对象风格

mysqli mysqli::init ( void )

过程化风格

mysqli mysqli_init ( void )

分配,或者初始化一个 MYSQL 对象,可以作为 mysqli_optionsmysqli_real_connect 函数的传入参数使用。

Note:

在调用 mysqli_real_connect 函数之前调用其他的 mysqli 函数可能会调用失败。 (class="function">mysqli_options 函数除外)。

返回值

返回一个对象。

范例

参见 mysqli_real_connect.

参见

  • mysqli_options
  • mysqli_close
  • mysqli_real_connect
  • mysqli_connect

mysqli::$insert_id

mysqli_insert_id

返回最后一条插入语句产生的自增 ID

说明

面向对象风格

mixed$mysqli->insert_id;

过程化风格

mixed mysqli_insert_id ( mysqli $link )

mysqli_insert_id 函数返回最后一个 SQL 语句(通常是 INSERT 语句) 所操作的表中设置为 AUTO_INCREMENT 的列的值。 如果最后一个 SQL 语句不是 INSERT 或者 UPDATE 语句, 或者所操作的表中没有设置为 AUTO_INCREMENT 的列, 返回值为 0。

Note:

如果在所执行的 INSERT 或者 UPDATE 语句中使用了数据库函数 LAST_INSERT_ID()。 有可能会影响 class="function">mysqli_insert_id 函数的返回值。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

最后一条 SQL(INSERT 或者 UPDATE)所操作的表中设置为 AUTO_INCREMENT 属性的列的值。 如果指定的连接上尚未执行 SQL 语句,或者最后一条 SQL 语句所操作的表中没有设为 AUTO_INCREMENT 的列,返回 0。

Note:

如果返回值超出了 php 允许的最大整数值, class="function">mysqli_insert_id 函数会以字符串形式返回这个值。

范例

示例 #1 $mysqli->insert_id 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* 删除表 */
$mysqli->query("DROP TABLE myCity");

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* 删除表 */
mysqli_query($link, "DROP TABLE myCity");

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

New Record has id 1.

mysqli::kill

mysqli_kill

让服务器杀掉一个 MySQL 线程

说明

面向对象风格

bool mysqli::kill ( int $processid )

过程化风格

bool mysqli_kill ( mysqli $link , int $processid )

本函数可以用来让服务器杀掉 processid 参数指定的 线程 ID。数据库连接对应的线程 ID 可以通过 调用 mysqli_thread_id 函数得到。

如果仅仅想中止某个查询,请使用这个 SQL 语句: KILL QUERY processid

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::kill 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 获得连接对应的线程 ID */
$thread_id = $mysqli->thread_id;

/* 杀掉连接 */
$mysqli->kill($thread_id);

/* 下面的代码应该会发生错误 */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 获得连接对应的线程 ID */
$thread_id = mysqli_thread_id($link);

/* 杀掉连接 */
mysqli_kill($link, $thread_id);

/* 下面的代码应该会发生错误 */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

Error: MySQL server has gone away

参见

  • mysqli_thread_id

mysqli::more_results

mysqli_more_results

检查批量查询中是否还有查询结果

说明

面向对象风格

bool mysqli::more_results ( void )

过程化风格

bool mysqli_more_results ( mysqli $link )

检查上一次调用 mysqli_multi_query 函数之后, 是否还有更多的查询结果集。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

如果上一次调用 mysqli_multi_query 函数之后, 还有更多的结果集可以读取,返回 TRUE,否则返回 FALSE

范例

参见 mysqli_multi_query

参见

  • mysqli_multi_query
  • mysqli_next_result
  • mysqli_store_result
  • mysqli_use_result

mysqli::multi_query

mysqli_multi_query

执行查询

说明

面向对象风格

bool mysqli::multi_query ( string $query )

过程化风格

bool mysqli_multi_query ( mysqli $link , string $query )

执行一个 SQL 语句,或者多个使用分号分隔的 SQL 语句。

要获得执行结果中的第一个结果集,请使用 mysqli_use_resultmysqli_store_result 函数。 要读取后续的结果集, 请使用 mysqli_more_resultsmysqli_next_result 函数。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

query
查询语句。

查询语句中的数据一定要正确的进行 转义

返回值

如果第一个 SQL 语句就失败了,返回 FALSE。 如果是批量执行 SQL 语句, 必须首先调用 mysqli_next_result 函数,才可以获取后续语句的错误信息。

范例

示例 #1 mysqli::multi_query 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* 批量执行查询 */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* 批量执行查询 */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* 关闭连接 */
mysqli_close($link);
?>

以上例程的输出类似于:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

参见

  • mysqli_query
  • mysqli_use_result
  • mysqli_store_result
  • mysqli_next_result
  • mysqli_more_results

mysqli::next_result

mysqli_next_result

为读取 multi_query 执行之后的下一个结果集做准备

说明

面向对象风格

bool mysqli::next_result ( void )

过程化风格

bool mysqli_next_result ( mysqli $link )

mysqli_multi_query 函数执行之后, 为读取下一个结果集做准备, 然后可以使用 mysqli_store_resultmysqli_use_result 函数读取下一个结果集。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

See mysqli_multi_query.

参见

  • mysqli_multi_query
  • mysqli_more_results
  • mysqli_store_result
  • mysqli_use_result

mysqli::options

mysqli_options

设置选项

说明

面向对象风格

bool mysqli::options ( int $option , mixed $value )

过程化风格

bool mysqli_options ( mysqli $link , int $option , mixed $value )

设置一个连接的扩展选项,这些选项可以改变这个连接的行为。

如果要对多个选项进行设置,可以多次调用此函数来。

mysqli_options 需要在 mysqli_init 函数之后、 mysqli_real_connect 函数之前被调用。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

option
要进行设置的选项,可以是下列中的某一项:

名称描述
MYSQLI_OPT_CONNECT_TIMEOUT连接超时设置,以秒为单位(在 Windows 平台上,PHP 5.3.1 之后才支持此选项)。
MYSQLI_OPT_LOCAL_INFILE启用或禁用 LOAD LOCAL INFILE 语句
MYSQLI_INIT_COMMAND成功建立 MySQL 连接之后要执行的 SQL 语句
MYSQLI_READ_DEFAULT_FILE从指定的文件中读取选项,而不是使用 my.cnf 中的选项
MYSQLI_READ_DEFAULT_GROUPmy.cnf 或者 MYSQL_READ_DEFAULT_FILE 指定的文件中 读取指定的组中的选项。
MYSQLI_SERVER_PUBLIC_KEYSHA-256 认证模式下,要使用的 RSA 公钥文件。
MYSQLI_OPT_NET_CMD_BUFFER_SIZE内部命令/网络缓冲大小, 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_NET_READ_BUFFER_SIZE以字节为单位,读取 MySQL 命令报文时候的块大小, 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_INT_AND_FLOAT_NATIVE将整数和浮点数类型的列转换成 PHP 的数值类型, 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT

value
选项值。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

更新日志

版本说明
5.5.0新增 MYSQLI_SERVER_PUBLIC_KEYMYSQLI_SERVER_PUBLIC_KEY 选项。
5.3.0新增 MYSQLI_OPT_INT_AND_FLOAT_NATIVEMYSQLI_OPT_NET_CMD_BUFFER_SIZEMYSQLI_OPT_NET_READ_BUFFER_SIZEMYSQLI_OPT_SSL_VERIFY_SERVER_CERT 选项。

范例

参见 mysqli_real_connect

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手/认证时发送,并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 class="function">mysqli_init 之后,class="function">mysqli_real_connect 之前先调用 class="function">mysqli_options 来指定。

参见

  • mysqli_init
  • mysqli_real_connect

mysqli::ping

mysqli_ping

ping 一个连接,或者如果连接处于断开状态,重新连接

说明

面向对象风格

bool mysqli::ping ( void )

过程化风格

bool mysqli_ping ( mysqli $link )

检查到服务器的连接是否还正常。 在启用 mysqli.reconnect 选项的前提下, 如果连接已经断开, ping 操作会尝试重新建立连接。

Note: mysqlnd 驱动会忽略 php.ini 中的 mysqli.reconnect 选项, 所以它不会自动重连。

客户端建立连接之后,长时间处于闲置状态, 可以用此函数来检查服务器是否关闭了这个连接, 如有必要,将会自动重新建立到服务器的连接。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::ping 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* 检查连接是否还活跃 */
if ($mysqli->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 检查连接是否还活跃 */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", mysqli_error($link));
}

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

Our connection is ok!

mysqli::poll

mysqli_poll

轮询连接

说明

面向对象风格

public static int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] )

过程化风格

int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] )

轮询连接。 仅可用于 mysqlnd。 此方法是 static 的。

参数

read
要检测是否存在可以读取的结果集的连接的数组。

error
发生错误的,例如:SQL 语句执行失败或者已经断开的 连接的数组。

reject
没有可以读取的结果集的连接 的数组。

sec
秒为单位的最大等待时间,不可以为负数。

usec
微秒为单位的最大等待时间,不可以为负数。

返回值

成功执行则返回存在可以读取结果集的连接数量, 否则 FALSE

范例

示例 #1 A mysqli_poll 例程

<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }
} while ($processed < count($all_links));
?>

以上例程会输出:

Array
(
    [0] => test
)

参见

  • mysqli_query
  • mysqli_reap_async_query

mysqli::prepare

mysqli_prepare

准备执行一个 SQL 语句

说明

面向对象风格

mysqli_stmt mysqli::prepare ( string $query )

过程化风格

mysqli_stmt mysqli_prepare ( mysqli $link , string $query )

做好执行 SQL 语句的准备,返回一个语句句柄,可以对这个句柄进行后续的操作。 这里仅仅支持单一的 SQL 语句,不支持多 SQL 语句。

在执行语句之前,需要使用 mysqli_stmt_bind_param 函数 对占位符参数进行绑定。 同样,在获取结果之前,必须使用 mysqli_stmt_bind_result 函数对返回的列值进行绑定。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

query
SQL 语句。

Note:

不需要在语句末尾增加分号(;) 或者 \g 结束符。

SQL 语句中可以包含一个或者多个问号(?) 表示语句的参数。

Note:

SQL 语句中,仅允许在特定的位置出现问号参数占位符。 例如,在 INSERT 语句中的 VALUES() 子句中可以使用参数占位符,来表示对应列的值。 也可以在 WHERE 字句中使用参数来表示 要进行比较的值。

但是,并不是所有的地方都允许使用参数占位符, 例如对于表名、列名这样的 SQL 语句中的标识位置, 就不可以使用参数占位。 SELECT 语句中的列名就不可以使用参数。 另外,对于 = 这样的逻辑比较操作也不可以在两侧都使用参数, 否则服务器在解析 SQL 的时候就不知道该如何检测参数类型了。 也不可以在 NULL 条件中使用问号, 也就是说不可以写成:? IS NULL。 一般而言,参数也只能用在数据操作(DML)语句中, 不可以用在数据定义(DDL)语句中。

返回值

mysqli_prepare 返回一个 statement 对象,如果发生错误则返回 FALSE

范例

示例 #1 mysqli::prepare 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* 创建一个预编译 SQL 语句 */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* 对于参数占位符进行参数值绑定 */
    $stmt->bind_param("s", $city);

    /* 执行查询 */
    $stmt->execute();

    /* 将查询结果绑定到变量 */
    $stmt->bind_result($district);

    /* 获取查询结果值 */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* 关于语句对象 */
    $stmt->close();
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* 创建一个预编译 SQL 语句 */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {

    /* 对于参数占位符进行参数值绑定 */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* 执行查询 */
    mysqli_stmt_execute($stmt);

    /* 将查询结果绑定到变量 */
    mysqli_stmt_bind_result($stmt, $district);

    /* 获取查询结果值 */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* 关闭语句句柄 */
    mysqli_stmt_close($stmt);
}

/* 关闭连接 */
mysqli_close($link);
?>

以上例程会输出:

Amersfoort is in district Utrecht

参见

  • mysqli_stmt_execute
  • mysqli_stmt_fetch
  • mysqli_stmt_bind_param
  • mysqli_stmt_bind_result
  • mysqli_stmt_close

mysqli::query

mysqli_query

对数据库执行一次查询

说明

面向对象风格

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

过程化风格

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Performs a query against the database.

For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling mysqli_real_query followed by either mysqli_use_result or mysqli_store_result.

Note:

In the case where you pass a statement to class="function">mysqli_query that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means “got a packet bigger than max_allowed_packet bytes”.

  • mysqlnd on Windows returns an error code 2006. This error message means “server has gone away”.

  • libmysqlclient on all platforms returns an error code 2006. This error message means “server has gone away”.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

query
The query string.

Data inside the query should be properly escaped.

resultmode
Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll is then used to get results from such queries.

返回值

失败时返回 FALSE,通过mysqli_query 成功执行SELECT, SHOW, DESCRIBEEXPLAIN查询会返回一个mysqli_result 对象,其他查询则返回**TRUE**。

更新日志

版本说明
5.3.0Added the ability of async queries.

范例

示例 #1 mysqli::query example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?>

以上例程会输出:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

参见

  • mysqli_real_query
  • mysqli_multi_query
  • mysqli_free_result

mysqli::real_connect

mysqli_real_connect

建立一个 MySQL 服务器连接

说明

面向对象风格

bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

过程化风格

bool mysqli_real_connect ( mysqli $link [, string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

建立一个到 MySQL 服务器的链接。

mysqli_connect 的不同点:

  • mysqli_real_connect 需要一个有效的对象,这个对象由 mysqli_init 创建。

  • 可以使用 mysqli_options 设置各种连接设置。

  • 提供 flags 参数。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

host
可以使用域名、IP 地址。如果传送 NULL 或者字符串 "localhost" 那么会使用 通道替代 TCP/IP 连接本地服务器。

username
MySQL 登录用户名

passwd
如果设置 NULL,那么会使用没有密码验证的方式尝试登录。这样可以为一个用户 提供不同的权限,基于他是否提供了密码。

dbname
设置执行查询语句的默认数据库。

port
指定 MySQL 服务器的端口

socket
指定使用的 socket 或者命名通道。

Note:

指定 socket 参数并不能说明要采用何种方式连接数据库。 连接数据的方式由 host 设定。

flags
这里可以设置连接参数:

NameDescription
MYSQLI_CLIENT_COMPRESS使用压缩协议
MYSQLI_CLIENT_FOUND_ROWS返回语句匹配的行数,而不是影响的行数
MYSQLI_CLIENT_IGNORE_SPACE允许函数名称后有空格,这将使所有的函数名称成为保留字。
MYSQLI_CLIENT_INTERACTIVE在关闭连接之前允许等待 interactive_timeout 秒, 他替代 wait_timeout 设定。
MYSQLI_CLIENT_SSL使用 SSL 加密

Note:

从安全角度考虑,在 PHP 中不可以使用 MULTI_STATEMENT, 若要执行多查询语句,请使用 class="function">mysqli_multi_query

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::real_connect 例子

面向对象风格

<?php

$mysqli = mysqli_init();
if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

面向对象风格 when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::init();

        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
            die('Setting MYSQLI_INIT_COMMAND failed');
        }

        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
        }

        if (!parent::real_connect($host, $user, $pass, $db)) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

过程化风格

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

以上例程会输出:

Success... MySQL host info: localhost via TCP/IP

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手/认证时发送,并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 class="function">mysqli_init 之后,class="function">mysqli_real_connect 之前先调用 class="function">mysqli_options 来指定。

参见

  • mysqli_connect
  • mysqli_init
  • mysqli_options
  • mysqli_ssl_set
  • mysqli_close

mysqli::real_escape_string

mysqli::escape_string

mysqli_real_escape_string

根据当前连接的字符集,对于 SQL 语句中的特殊字符进行转义

说明

面向对象风格

string mysqli::escape_string ( string $escapestr )

string mysqli::real_escape_string ( string $escapestr )

过程化风格

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

此函数用来对字符串中的特殊字符进行转义, 以使得这个字符串是一个合法的 SQL 语句。 传入的字符串会根据当前连接的字符集进行转义,得到一个编码后的合法的 SQL 语句。

Caution

在调用 mysqli_real_escape_string 函数之前, 必须先通过调用 mysqli_set_charset 函数或者在 MySQL 服务器端设置字符集。 更多信息请参考 字符集

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

escapestr
需要进行转义的字符串。

会被进行转义的字符包括: NUL (ASCII 0),\n,\r,\,'," 和 Control-Z.

返回值

转义后的字符串。

错误/异常

在无效的连接上调用此函数会返回 NULL 并发出一个 E_WARNING 级别的错误。

范例

示例 #1 mysqli::real_escape_string 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* 由于未对 $city 进行转义,此次查询会失败 */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* 对 $city 进行转义之后,查询可以正常执行 */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* 由于未对 $city 进行转义,此次查询会失败 */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* 对 $city 进行转义之后,查询可以正常执行 */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

以上例程会输出:

Error: 42000
1 Row inserted.

注释

Note:

如果你之前都是使用 class="function">mysql_real_escape_string 函数来转义 SQL 语句的, 那么需要注意的是 class="function">mysqli_real_escape_stringclass="function">mysql_real_escape_string 两个函数的参数顺序不同。 class="function">mysqli_real_escape_string 中, link 是第一个参数, 而在 class="function">mysql_real_escape_string 函数中,要转义的字符串是第一个参数。

参见

  • mysqli_set_charset
  • mysqli_character_set_name

mysqli::real_query

mysqli_real_query

执行一个mysql查询

说明

面向对象风格

bool mysqli::real_query ( string $query )

过程化风格

bool mysqli_real_query ( mysqli $link , string $query )

执行一个单条数据库查询, 其结果可以使用mysqli_store_resultmysqli_use_result检索或存储.

为了确定给定的查询是否真的返回一个结果集, 可以查看mysqli_field_count.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

query
查询字符串

查询中的数据可以进行属性转义.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_query
  • mysqli_store_result
  • mysqli_use_result

mysqli::reap_async_query

mysqli_reap_async_query

获取异步查询的结果

说明

面向对象风格

public mysqli_result mysqli::reap_async_query ( void )

过程化风格

mysqli_result mysqli_reap_async_query ( mysqli $link )

获取异步查询的结果, 仅可用于 mysqlnd。。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

如果成功则返回 mysqli_result,否则返回 FALSE

参见

  • mysqli_poll

mysqli::refresh

mysqli_refresh

刷新

说明

面向对象风格

public bool mysqli::refresh ( int $options )

过程化风格

bool mysqli_refresh ( resource $link , int $options )

刷新表或者缓存,或者重置主从服务器信息。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

options
使用 MySQLi 常量 中的 MYSQLI_REFRESH_* 常量作为刷新选项。

参见 MySQL 官方文档: » MySQL Refresh

返回值

成功返回 TRUE,否则返回 FALSE

参见

  • mysqli_poll

mysqli::release_savepoint

mysqli_release_savepoint

从当前事务的保存点中移除一个命名保存点

说明

面向对象风格 (method):

public bool mysqli::release_savepoint ( string $name )

过程化风格:

bool mysqli_release_savepoint ( mysqli $link , string $name )

Warning

本函数还未编写文档,仅有参数列表。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

name

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_rollback

mysqli::rollback

mysqli_rollback

回退当前事务

说明

面向对象风格

bool mysqli::rollback ( void )

过程化风格

bool mysqli_rollback ( mysqli $link )

回退当前数据库的事务。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::rollback example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>

以上例程会输出:

0 rows in table myCity.
50 rows in table myCity (after rollback).

参见

  • mysqli_commit
  • mysqli_autocommit

mysqli::rpl_query_type

mysqli_rpl_query_type

返回 RPL 查询类型

说明

面向对象风格

int mysqli::rpl_query_type ( string $query )

过程化风格

int mysqli_rpl_query_type ( mysqli $link , string $query )

返回 MYSQLI_RPL_MASTERMYSQLI_RPL_SLAVEMYSQLI_RPL_ADMIN,具体的返回值取决于查询的类型。 INSERTUPDATE 以及类似的操作属于 主机 查询,SELECT 属于 从机查询,FLUSHREPAIR 以及类似的操作属于 管理 查询。

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli::savepoint

mysqli_savepoint

在当前事务中增加一个命名保存点

说明

面向对象风格 (method):

public bool mysqli::savepoint ( string $name )

过程化风格:

bool mysqli_savepoint ( mysqli $link , string $name )

Warning

本函数还未编写文档,仅有参数列表。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

name

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_commit

mysqli::select_db

mysqli_select_db

选择用于数据库查询的默认数据库

说明

面向对象风格

bool mysqli::select_db ( string $dbname )

过程化风格

bool mysqli_select_db ( mysqli $link , string $dbname )

针对本次数据库连接用于数据库查询的默认数据库。

Note:

本函数应该只被用在改变本次链接的数据库,你也能在class="function">mysqli_connect第四个参数确认默认数据库。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

dbname
数据库名称

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::select_db example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

以上例程会输出:

Default database is test.
Default database is world.

参见

  • mysqli_connect
  • mysqli_real_connect

mysqli::send_query

mysqli_send_query

发送请求并返回结果

说明

面向对象风格

bool mysqli::send_query ( string $query )

过程化风格

bool mysqli_send_query ( mysqli $link , string $query )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli::set_charset

mysqli_set_charset

设置默认字符编码

说明

面向对象风格

bool mysqli::set_charset ( string $charset )

过程化风格

bool mysqli_set_charset ( mysqli $link , string $charset )

设置在数据库间传输字符时所用的默认字符编码。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

charset
被设为默认的字符编码名。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

注释

Note:

如果在Windows平台上使用该方法,需要4.1.11版或以上的MySQL客户端库,且MySQL版本为5.0.6以上。

Note:

这应该是首选的用于改变字符编码的方法,不建议使用class="function">mysqli_query执行SQL请求的SET NAMES ...(如 SET NAMES utf8)。 详见MySQL字符集的概念

范例

示例 #1 mysqli::set_charset example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

以上例程会输出:

Current character set: utf8

参见

mysqli::set_local_infile_default

mysqli_set_local_infile_default

取消用户指定的回调函数

说明

void mysqli_set_local_infile_default ( mysqli $link )

使之前通过 mysqli_set_local_infile_handler 设置的 LOAD DATA INFILE LOCAL 回调函数失效。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

没有返回值。

范例

参见 mysqli_set_local_infile_handler 例程

参见

  • mysqli_set_local_infile_handler

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

设置 LOAD DATA LOCAL INFILE 命令的回调函数

说明

面向对象风格

bool mysqli::set_local_infile_handler ( mysqli $link , callable $read_func )

过程化风格

bool mysqli_set_local_infile_handler ( mysqli $link , callable $read_func )

设置 LOAD DATA LOCAL INFILE 命令的回调函数

回调函数的作用是读取 LOAD DATA LOCAL INFILE 命令指定的文件, 并且将其重新格式化。 所用的格式必须是 LOAD DATA INFILE 命令可以识别的格式。

返回的数据需要和 LOAD DATA 命令指定的格式匹配。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

read_func
一个回调函数,或者对象的方法,它需要接收以下参数:

stream
和 SQL 命令中的 INFILE 关联的 PHP 流

&buffer
用来保存输入数据重写之后数据的字符串缓冲区

buflen
缓冲区中存储的最大的字符数量

&errormsg
如果发生错误,可以用这个变量存储一些错误信息

如果处理成功,则回调函数需要返回 buffer 中存储的字符数量, 如果处理失败, 返回一个负数。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 mysqli::set_local_infile_handler 例程

面向对象风格

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // 将字符串替换成大写,并且将 "," 分隔符替换成 [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }


  echo "Input:\n";

  $db->set_local_infile_handler("callme");
  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  $db->set_local_infile_default();

  $res = $db->query("SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = $res->fetch_assoc()) {
    echo join(",", $row)."\n";
  }
?>

过程化风格

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // 将字符串替换成大写,并且将 "," 分隔符替换成 [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }


  echo "Input:\n";

  mysqli_set_local_infile_handler($db, "callme");
  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  mysqli_set_local_infile_default($db);

  $res = mysqli_query($db, "SELECT * FROM t1");


  echo "\nResult:\n";
  while ($row = mysqli_fetch_assoc($res)) {
    echo join(",", $row)."\n";
  }
?>

以上例程会输出:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

参见

  • mysqli_set_local_infile_default

mysqli::$sqlstate

mysqli_sqlstate

返回上一次 SQL 操作的 SQLSTATE 错误信息

说明

面向对象风格

string$mysqli->sqlstate;

过程化风格

string mysqli_sqlstate ( mysqli $link )

返回一个包含 SQLSTATE 错误码的字符串,表示上一次 SQL 操作的错误。 错误码是由 5 个字符构成,'00000' 表示没有发生错误。 错误码是由 ANSI SQL 和 ODBC 定义的, 详细的清单请参见:» http://dev.mysql.com/doc/mysql/en/error-handling.html

Note:

需要注意的是,并不是所有的 MySQL 错误都映射到 SQLSTATE 了, 未映射的错误消息使用 HY000(综合错误)表示。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

返回一个包含 SQLSTATE 错误码的字符串,表示上一次 SQL 操作的错误。 错误码是由 5 个字符构成,'00000' 表示没有发生错误。

范例

示例 #1 $mysqli->sqlstate 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* City 表已经存在,所以我们会遇到一个错误 */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* City 表已经存在,所以我们会遇到一个错误 */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($link);
?>

以上例程会输出:

Error - SQLSTATE 42S01.

参见

  • mysqli_errno
  • mysqli_error

mysqli::ssl_set

mysqli_ssl_set

使用 SSL 建立到数据库之间的安全连接

说明

面向对象风格

bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

过程化风格

bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )

使用 SSL 建立到数据库之间的安全连接, 必须在调用 mysqli_real_connect 函数之前调用此函数。 除非启用 OpenSSL 支持,否则此函数无任何作用。

需要注意的是,在 PHP 5.3.3 之前的版本中, MySQL 原生驱动不支持建立 SSL 连接, 所以,在使用 MySQL 原生驱动的时候,调用此函数会产生错误。 从 PHP 5.3 开始,在 Windows 平台上,默认是启用 MySQL 原生驱动的。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

key
密钥文件的路径

cert
证书文件的路径

ca
签发机构的证书文件路径

capath
指向一个目录的路径, 该目录下存放的是受信任的 CA 机构证书 PEM 格式的文件。

cipher
SSL 加密允许使用的算法清单

任何未使用的 SSL 参数,可以设置为 NULL

返回值

此函数永远会返回 TRUE。 如果 SSL 的设置有误,那么在调用 mysqli_real_connect 函数建立连接的时候才会报错。

参见

  • mysqli_options
  • mysqli_real_connect

mysqli::stat

mysqli_stat

获取当前系统状态信息

说明

面向对象风格

string mysqli::stat ( void )

过程化风格

string mysqli_stat ( mysqli $link )

mysqli_stat 函数返回一个表示系统状态信息的字符串, 字符串中的内容和 'mysqladmin status' 命令的输出结果类似, 包含以秒为单位的运行时间、运行中的线程数、问题数、重新加载数以及打开的表数量等信息。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

成功则返回表示系统状态信息的字符串,失败则返回 FALSE

范例

示例 #1 mysqli::stat 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli->stat());

$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($link);
?>

以上例程会输出:

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
Memory in use: 8496K  Max memory used: 8560K

参见

  • mysqli_get_server_info

mysqli::stmt_init

mysqli_stmt_init

初始化一条语句并返回一个用于mysqli_stmt_prepare(调用)的对象

说明

面向对象风格

mysqli_stmt mysqli::stmt_init ( void )

过程化风格

mysqli_stmt mysqli_stmt_init ( mysqli $link )

分配并初始化一个语句对象用于mysqli_stmt_prepare.

Note:

任何其后调用的mysqli_stmt函数都会失败直到class="function">mysqli_stmt_prepare被调用.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

Returns an object.

参见

  • mysqli_stmt_prepare

mysqli::store_result

mysqli_store_result

转移上一次查询返回的结果集

说明

面向对象风格

mysqli_result mysqli::store_result ([ int $option ] )

过程化风格

mysqli_result mysqli_store_result ( mysqli $link [, int $option ] )

迁移 link 参数所指定的连接上的上一次查询返回的结果集, 迁移之后的结果集可以 在 mysqli_data_seek 函数中使用。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

option
指定的选项,可以是下列中的某一值:

NameDescription
MYSQLI_STORE_RESULT_COPY_DATA将结果集从 mysqlnd 的内部缓冲区复制到 PHP 变量中。 默认情况下,mysqlnd 采取一种引用策略尽量避免在内容中复制多份同样的结果集。 例如,对于一个包含了很多行的结果集,每个行中的内容又不是很大,那么复制结果集的过程会导致内存使用率下降, 因为用来保存结果集数据的 PHP 变量可能提前被释放掉。 (此选项仅在使用 mysqlnd 驱动且 PHP 5.6.0 之后可用)。

返回值

成功则返回一个缓冲的结果集对象,失败则返回 FALSE

Note:

如果上一查询并不产生结果集(例如,执行了一个 INSERT 语句), 那么 mysqli_store_result 会返回 FALSE。 如果读取结果集失败了,也会返回 FALSE。 如何区分是上面哪种情况导致此函数的调用返回了 FALSE? 你可以通过下面的方法来检测: class="function">mysqli_error 返回了非空的字符串, class="function">mysqli_errno 返回了非零值, 或者 class="function">mysqli_field_count 返回了非零值, 都表示发生错误了。 还有一种可能的情况会导致此函数的调用返回 FALSE:上一次查询 mysqli_query 本身是成功的, 但是由于返回的结果集太大,无法为其分配足够的内存来进行结果集转移。 如果 mysqli_field_count 函数返回了一个非零值,那么表示 SQL 语句产生了一个非空的结果集。

注释

Note:

执行查询之后, 使用 mysqli_free_result 函数来释放结果集所占用的内存, 是一个很有用的实战经验。 尤其是当使用 mysqli_store_result 函数来转移数量较大的结果集的时候, 释放结果集内存的操作尤为重要。

范例

See mysqli_multi_query.

参见

  • mysqli_real_query
  • mysqli_use_result

mysqli::$thread_id

mysqli_thread_id

返回当前连接的线程 ID

说明

面向对象风格

int$mysqli->thread_id;

过程化风格

int mysqli_thread_id ( mysqli $link )

mysqli_thread_id 函数返回当前连接的线程 ID, 这个线程 ID 可以在 mysqli_kill 函数中使用。 如果 PHP 到数据库的连接中断了, 然后使用 mysqli_ping 函数重新建立连接的话, 新的连接的线程 ID 会发生改变。所以,仅在需要的时候,调用本函数获取连接的线程 ID。

Note:

线程 ID 是每次连接都重新分配的,也就是说它和连接是紧密相关的, 如果某个连接异常断开了,然后重新建立了到数据库的连接, 这个线程 ID 就不再是原来的那个了,它会发生变化。

可以通过执行 SQL 语句:KILL QUERY processid 来杀掉对应连接上正在执行的 SQL 语句。

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

返回当前连接的线程 ID

范例

示例 #1 $mysqli->thread_id 例程

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 获取连接的线程 ID */
$thread_id = $mysqli->thread_id;

/* 杀掉这个连接 */
$mysqli->kill($thread_id);

/* 这句代码应该会报错 */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 获取连接的线程 ID */
$thread_id = mysqli_thread_id($link);

/* 杀掉这个连接 */
mysqli_kill($link, $thread_id);

/* 这句代码应该会报错 */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Error: MySQL server has gone away

参见

  • mysqli_kill

mysqli::thread_safe

mysqli_thread_safe

返回是否是线程安全的

说明

过程化风格

bool mysqli_thread_safe ( void )

告知本数据库客户端库是否编译为线程安全的。 Tells whether the client library is compiled as thread-safe.

返回值

如果是的话,返回**TRUE,否则返回FALSE**。

mysqli::use_result

mysqli_use_result

Initiate a result set retrieval

说明

面向对象风格

mysqli_result mysqli::use_result ( void )

过程化风格

mysqli_result mysqli_use_result ( mysqli $link )

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query function on the database connection.

Either this or the mysqli_store_result function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Note:

The mysqli_use_result function does not transfer the entire result set from the database and hence cannot be used functions such as class="function">mysqli_data_seek to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result. One should not use mysqli_use_result if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

返回值

Returns an unbuffered result object or FALSE if an error occurred.

范例

示例 #1 mysqli::use_result example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->use_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_use_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

参见

  • mysqli_real_query
  • mysqli_store_result

mysqli::$warning_count

mysqli_warning_count

Returns the number of warnings from the last query for the given link

说明

面向对象风格

int$mysqli->warning_count;

过程化风格

int mysqli_warning_count ( mysqli $link )

Returns the number of warnings from the last query in the connection.

Note:

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

返回值

Number of warnings or zero if there are no warnings.

范例

示例 #1 $mysqli->warning_count example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Warning (1264): Data truncated for column 'Name' at row 1

参见

  • mysqli_errno
  • mysqli_error
  • mysqli_sqlstate

简介

代表一个预编译 SQL 语句。

类摘要

mysqli_stmt

class mysqli_stmt {

/* 属性 */

int$mysqli_stmt->affected_rows;

int$mysqli_stmt->errno;

array$mysqli_stmt->error_list;

string$mysqli_stmt->error;

int$mysqli_stmt->field_count;

int$mysqli_stmt->insert_id;

int$mysqli_stmt->num_rows;

int$mysqli_stmt->param_count;

string$mysqli_stmt->sqlstate;

/* 方法 */

int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )

int attr_get ( int $attr )

bool attr_set ( int $attr , int $mode )

bool bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

bool bind_result ( mixed &$var1 [, mixed &$... ] )

bool close ( void )

void data_seek ( int $offset )

int mysqli_stmt_errno ( mysqli_stmt $stmt )

array mysqli_stmt_error_list ( mysqli_stmt $stmt )

string mysqli_stmt_error ( mysqli_stmt $stmt )

bool execute ( void )

bool fetch ( void )

int mysqli_stmt_field_count ( mysqli_stmt $stmt )

void free_result ( void )

mysqli_result get_result ( void )

object get_warnings ( void )

mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )

public bool more_results ( void )

public bool next_result ( void )

int num_rows ( void )

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

mixed prepare ( string $query )

bool reset ( void )

mysqli_result result_metadata ( void )

bool send_long_data ( int $param_nr , string $data )

string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )

bool store_result ( void )

}

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

Returns the total number of rows changed, deleted, or inserted by the last executed statement

说明

面向对象风格

int$mysqli_stmt->affected_rows;

过程化风格

int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )

Returns the number of rows affected by INSERT, UPDATE, or DELETE query.

This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows instead.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error. NULL indicates an invalid argument was supplied to the function.

Note:

If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt->bind_param("s", $code);

    /* execute statement */
    $stmt->execute();

    printf("rows inserted: %d\n", $stmt->affected_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = mysqli_prepare($link, $query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    mysqli_stmt_bind_param($stmt, "s", $code);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

rows inserted: 17

参见

  • mysqli_stmt_num_rows
  • mysqli_prepare

mysqli_stmt::attr_get

mysqli_stmt_attr_get

Used to get the current value of a statement attribute

说明

面向对象风格

int mysqli_stmt::attr_get ( int $attr )

过程化风格

int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )

Gets the current value of a statement attribute.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

attr
The attribute that you want to get.

返回值

Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.

mysqli_stmt::attr_set

mysqli_stmt_attr_set

Used to modify the behavior of a prepared statement

说明

面向对象风格

bool mysqli_stmt::attr_set ( int $attr , int $mode )

过程化风格

bool mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode )

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

attr
The attribute that you want to set. It can have one of the following values:

CharacterDescription
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTHSetting to TRUE causes mysqli_stmt_store_result to update the metadata MYSQL_FIELD->max_length value.
MYSQLI_STMT_ATTR_CURSOR_TYPEType of cursor to open for statement when mysqli_stmt_execute is invoked. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY.
MYSQLI_STMT_ATTR_PREFETCH_ROWSNumber of rows to fetch from server at a time when using a cursor. mode can be in the range from 1 to the maximum value of unsigned long. The default is 1.

If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute. If there is already an open cursor from a previous mysqli_stmt_execute call, it closes the cursor before opening a new one. mysqli_stmt_reset also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result closes any open cursor.

If you open a cursor for a prepared statement, mysqli_stmt_store_result is unnecessary.

mode
The value to assign to the attribute.

参见

mysqli_stmt::bind_param

mysqli_stmt_bind_param

Binds variables to a prepared statement as parameters

说明

面向对象风格

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

过程化风格

bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare.

Note:

If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data to send the data in packets.

Note:

Care must be taken when using class="function">mysqli_stmt_bind_param in conjunction with call_user_func_array. Note that class="function">mysqli_stmt_bind_param requires parameters to be passed by reference, whereas class="function">call_user_func_array can accept as a parameter a list of variables that can represent references or values.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

types
A string that contains one or more characters which specify the types for the corresponding bind variables:

CharacterDescription
icorresponding variable has type integer
dcorresponding variable has type double
scorresponding variable has type string
bcorresponding variable is a blob and will be sent in packets

var1
The number of variables and length of string types must match the parameters in the statement.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

1 Row inserted.
1 Row deleted.

参见

  • mysqli_stmt_bind_result
  • mysqli_stmt_execute
  • mysqli_stmt_fetch
  • mysqli_prepare
  • mysqli_stmt_send_long_data
  • mysqli_stmt_errno
  • mysqli_stmt_error

mysqli_stmt::bind_result

mysqli_stmt_bind_result

Binds variables to a prepared statement for result storage

说明

面向对象风格

bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

过程化风格

bool mysqli_stmt_bind_result ( mysqli_stmt $stmt , mixed &$var1 [, mixed &$... ] )

Binds columns in the result set to variables.

When mysqli_stmt_fetch is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....

Note:

Note that all columns must be bound after class="function">mysqli_stmt_execute and prior to calling mysqli_stmt_fetch. Depending on column types bound variables can silently change to the corresponding PHP type.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch is called.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

var1
The variable to be bound.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    mysqli_stmt_execute($stmt);

    /* bind variables to prepared statement */
    mysqli_stmt_bind_result($stmt, $col1, $col2);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

参见

  • mysqli_stmt_get_result
  • mysqli_stmt_bind_param
  • mysqli_stmt_execute
  • mysqli_stmt_fetch
  • mysqli_prepare
  • mysqli_stmt_prepare
  • mysqli_stmt_init
  • mysqli_stmt_errno
  • mysqli_stmt_error

mysqli_stmt::close

mysqli_stmt_close

Closes a prepared statement

说明

面向对象风格

bool mysqli_stmt::close ( void )

过程化风格

bool mysqli_stmt_close ( mysqli_stmt $stmt )

Closes a prepared statement. mysqli_stmt_close also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_prepare

mysqli_stmt::__construct

Constructs a new mysqli_stmt object

说明

mysqli_stmt::__construct ( mysqli $link [, string $query ] )

This method constructs a new mysqli_stmt object.

Note:

In general, you should use either class="function">mysqli_prepare or class="function">mysqli_stmt_init to create a class="classname">mysqli_stmt object, rather than directly instantiating the object with new mysqli_stmt. This method (and the ability to directly instantiate class="classname">mysqli_stmt objects) may be deprecated and removed in the future.

参数

link
仅以过程化样式:由mysqli_connectmysqli_init 返回的链接标识。

query
The query, as a string. If this parameter is omitted, then the constructor behaves identically to mysqli_stmt_init, if provided, then it behaves as per mysqli_prepare.

参见

  • mysqli_prepare
  • mysqli_stmt_init

mysqli_stmt::data_seek

mysqli_stmt_data_seek

Seeks to an arbitrary row in statement result set

说明

面向对象风格

void mysqli_stmt::data_seek ( int $offset )

过程化风格

void mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset )

Seeks to an arbitrary result pointer in the statement result set.

mysqli_stmt_store_result must be called prior to mysqli_stmt_data_seek.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

offset
Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows - 1).

返回值

没有返回值。

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

City: Benin City  Countrycode: NGA

参见

  • mysqli_prepare

mysqli_stmt::$errno

mysqli_stmt_errno

Returns the error code for the most recent statement call

说明

面向对象风格

int$mysqli_stmt->errno;

过程化风格

int mysqli_stmt_errno ( mysqli_stmt $stmt )

Returns the error code for the most recently invoked statement function that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

An error code value. Zero means no error occurred.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %d.\n", $stmt->errno);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %d.\n", mysqli_stmt_errno($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Error: 1146.

参见

  • mysqli_stmt_error
  • mysqli_stmt_sqlstate

mysqli_stmt::$error_list

mysqli_stmt_error_list

Returns a list of errors from the last statement executed

说明

面向对象风格

array$mysqli_stmt->error_list;

过程化风格

array mysqli_stmt_error_list ( mysqli_stmt $stmt )

Returns an array of errors for the most recently invoked statement function that can succeed or fail.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

A list of errors, each as an associative array containing the errno, error, and sqlstate.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();
    
    echo "Error:\n";
    print_r($stmt->error_list);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);
    
    echo "Error:\n";
    print_r(mysql_stmt_error_list($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Array
(
    [0] => Array
        (
            [errno] => 1146
            [sqlstate] => 42S02
            [error] => Table 'world.myCountry' doesn't exist
        )

)

参见

  • mysqli_stmt_error
  • mysqli_stmt_errno
  • mysqli_stmt_sqlstate

mysqli_stmt::$error

mysqli_stmt_error

Returns a string description for last statement error

说明

面向对象风格

string$mysqli_stmt->error;

过程化风格

string mysqli_stmt_error ( mysqli_stmt $stmt )

Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

A string that describes the error. An empty string if no error occurred.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->error);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_error($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Error: Table 'world.myCountry' doesn't exist.

参见

  • mysqli_stmt_errno
  • mysqli_stmt_sqlstate

mysqli_stmt::execute

mysqli_stmt_execute

Executes a prepared Query

说明

面向对象风格

bool mysqli_stmt::execute ( void )

过程化风格

bool mysqli_stmt_execute ( mysqli_stmt $stmt )

Executes a query that has been previously prepared using the mysqli_prepare function. When executed any parameter markers which exist will automatically be replaced with the appropriate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows function. Likewise, if the query yields a result set the mysqli_stmt_fetch function is used.

Note:

When using mysqli_stmt_execute, the mysqli_stmt_fetch function must be used to fetch the data prior to performing any additional queries.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
mysqli_stmt_execute($stmt);

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

参见

  • mysqli_prepare
  • mysqli_stmt_bind_param
  • mysqli_stmt_get_result

mysqli_stmt::fetch

mysqli_stmt_fetch

Fetch results from a prepared statement into the bound variables

说明

面向对象风格

bool mysqli_stmt::fetch ( void )

过程化风格

bool mysqli_stmt_fetch ( mysqli_stmt $stmt )

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result.

Note:

Note that all columns must be bound by the application before calling mysqli_stmt_fetch.

Note:

Data are transferred unbuffered without calling class="function">mysqli_stmt_store_result which can decrease performance (but reduces memory cost).

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

ValueDescription
TRUESuccess. Data has been fetched
FALSEError occurred
NULLNo more rows/data exists or data truncation occurred

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

参见

  • mysqli_prepare
  • mysqli_stmt_errno
  • mysqli_stmt_error
  • mysqli_stmt_bind_result

mysqli_stmt::$field_count

mysqli_stmt_field_count

Returns the number of field in the given statement

说明

面向对象风格

int$mysqli_stmt->field_count;

过程化风格

int mysqli_stmt_field_count ( mysqli_stmt $stmt )

Warning

本函数还未编写文档,仅有参数列表。

mysqli_stmt::free_result

mysqli_stmt_free_result

Frees stored result memory for the given statement handle

说明

面向对象风格

void mysqli_stmt::free_result ( void )

过程化风格

void mysqli_stmt_free_result ( mysqli_stmt $stmt )

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

没有返回值。

参见

  • mysqli_stmt_store_result

mysqli_stmt::get_result

mysqli_stmt_get_result

Gets a result set from a prepared statement

说明

面向对象风格

mysqli_result mysqli_stmt::get_result ( void )

过程化风格

mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )

Call to return a result set from a prepared statement query.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

Returns a resultset for successful SELECT queries, or FALSE for other DML queries or on failure. The mysqli_errno function can be used to distinguish between the two types of failure.

仅 MySQL 原生驱动

仅可用于 mysqlnd

范例

示例 #1 面向对象风格

<?php 

$mysqli = new mysqli("127.0.0.1", "user", "password", "world"); 

if($mysqli->connect_error)
{
    die("$mysqli->connect_errno: $mysqli->connect_error");
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
    print "Failed to prepare statement\n";
}
else
{
    $stmt->bind_param("s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_array(MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}

$stmt->close();
$mysqli->close();
?>

示例 #2 过程化风格

<?php 

$link = mysqli_connect("127.0.0.1", "user", "password", "world"); 

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query))
{
    print "Failed to prepare statement\n";
}
else
{
    mysqli_stmt_bind_param($stmt, "s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

以上例程会输出:

Albania 3401200 Europe 
Algeria 31471000 Africa 
Afghanistan 22720000 Asia 
Anguilla 8000 North America 

参见

  • mysqli_prepare
  • mysqli_stmt_result_metadata
  • mysqli_stmt_fetch
  • mysqli_fetch_array
  • mysqli_stmt_store_result
  • mysqli_errno

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

Get result of SHOW WARNINGS

说明

面向对象风格

object mysqli_stmt::get_warnings ( void )

过程化风格

object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )

Warning

本函数还未编写文档,仅有参数列表。

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

Get the ID generated from the previous INSERT operation

说明

面向对象风格

int$mysqli_stmt->insert_id;

过程化风格

mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )

Warning

本函数还未编写文档,仅有参数列表。

mysqli_stmt::more_results

mysqli_stmt_more_results

Check if there are more query results from a multiple query

说明

面向对象风格 (method):

public bool mysqli_stmt::more_results ( void )

过程化风格:

bool mysqli_stmt_more_results ( mysql_stmt $stmt )

Checks if there are more query results from a multiple query.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

Returns TRUE if more results exist, otherwise FALSE.

仅 MySQL 原生驱动

仅可用于 mysqlnd

参见

  • mysqli_stmt::next_result
  • mysqli::multi_query

mysqli_stmt::next_result

mysqli_stmt_next_result

Reads the next result from a multiple query

说明

面向对象风格 (method):

public bool mysqli_stmt::next_result ( void )

过程化风格:

bool mysqli_stmt_next_result ( mysql_stmt $stmt )

Reads the next result from a multiple query.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Emits an E_STRICT level error if a result set does not exist, and suggests using mysqli_stmt::more_results in these cases, before calling mysqli_stmt::next_result.

仅 MySQL 原生驱动

仅可用于 mysqlnd

参见

  • mysqli_stmt::more_results
  • mysqli::multi_query

mysqli_stmt::$num_rows

mysqli_stmt::num_rows

mysqli_stmt_num_rows

Return the number of rows in statements result set

说明

面向对象风格

int$mysqli_stmt->num_rows;

int mysqli_stmt::num_rows ( void )

过程化风格

int mysqli_stmt_num_rows ( mysqli_stmt $stmt )

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows depends on whether or not you used mysqli_stmt_store_result to buffer the entire result set in the statement handle.

If you use mysqli_stmt_store_result, mysqli_stmt_num_rows may be called immediately.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

An integer representing the number of rows in result set.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Number of rows: 20.

参见

  • mysqli_stmt_affected_rows
  • mysqli_prepare
  • mysqli_stmt_store_result

mysqli_stmt::$param_count

mysqli_stmt_param_count

Returns the number of parameter for the given statement

说明

面向对象风格

int$mysqli_stmt->param_count;

过程化风格

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

Returns the number of parameter markers present in the prepared statement.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

Returns an integer representing the number of parameters.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt->param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = mysqli_stmt_param_count($stmt);
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Statement has 2 markers.

参见

  • mysqli_prepare

mysqli_stmt::prepare

mysqli_stmt_prepare

Prepare an SQL statement for execution

说明

面向对象风格

mixed mysqli_stmt::prepare ( string $query )

过程化风格

bool mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query )

Prepares the SQL query pointed to by the null-terminated string query.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param and/or mysqli_stmt_bind_result before executing the statement or fetching rows.

Note:

In the case where you pass a statement to class="function">mysqli_stmt_prepare that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means “got a packet bigger than max_allowed_packet bytes”.

  • mysqlnd on Windows returns an error code 2006. This error message means “server has gone away”.

  • libmysqlclient on all platforms returns an error code 2006. This error message means “server has gone away”.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

query
The query, as a string. It must consist of a single SQL statement.

You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note:

You should not add a terminating semicolon or \g to the statement.

Note:

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Amersfoort is in district Utrecht

参见

  • mysqli_stmt_init
  • mysqli_stmt_execute
  • mysqli_stmt_fetch
  • mysqli_stmt_bind_param
  • mysqli_stmt_bind_result
  • mysqli_stmt_get_result
  • mysqli_stmt_close

mysqli_stmt::reset

mysqli_stmt_reset

Resets a prepared statement

说明

面向对象风格

bool mysqli_stmt::reset ( void )

过程化风格

bool mysqli_stmt_reset ( mysqli_stmt $stmt )

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data, unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • mysqli_prepare

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

Returns result set metadata from a prepared statement

说明

面向对象风格

mysqli_result mysqli_stmt::result_metadata ( void )

过程化风格

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt $stmt )

If a statement passed to mysqli_prepare is one that produces a result set, mysqli_stmt_result_metadata returns the result object that can be used to process the meta information such as total number of fields and individual field information.

Note:

This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • mysqli_num_fields

  • mysqli_fetch_field

  • mysqli_fetch_field_direct

  • mysqli_fetch_fields

  • mysqli_field_count

  • mysqli_field_seek

  • mysqli_field_tell

  • mysqli_free_result

The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result

Note:

The result set returned by class="function">mysqli_stmt_result_metadata contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with class="function">mysqli_stmt_fetch.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

Returns a result object or FALSE if an error occurred.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

参见

  • mysqli_prepare
  • mysqli_free_result

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

Send data in blocks

说明

面向对象风格

bool mysqli_stmt::send_long_data ( int $param_nr , string $data )

过程化风格

bool mysqli_stmt_send_long_data ( mysqli_stmt $stmt , int $param_nr , string $data )

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

param_nr
Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

data
A string containing data to be sent.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>

参见

  • mysqli_prepare
  • mysqli_stmt_bind_param

mysqli_stmt::$sqlstate

mysqli_stmt_sqlstate

Returns SQLSTATE error from previous statement operation

说明

面向对象风格

string$mysqli_stmt->sqlstate;

过程化风格

string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

注释

Note:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->sqlstate);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Error: 42S02.

参见

  • mysqli_stmt_errno
  • mysqli_stmt_error

mysqli_stmt::store_result

mysqli_stmt_store_result

Transfers a result set from a prepared statement

说明

面向对象风格

bool mysqli_stmt::store_result ( void )

过程化风格

bool mysqli_stmt_store_result ( mysqli_stmt $stmt )

You must call mysqli_stmt_store_result for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), if and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch call returns buffered data.

Note:

It is unnecessary to call class="function">mysqli_stmt_store_result for other queries, but if you do, it will not harm or cause any notable performance loss in all cases. You can detect whether the query produced a result set by checking if class="function">mysqli_stmt_result_metadata returns FALSE.

参数

stmt
仅以过程化样式:由 mysqli_stmt_init 返回的 statement 标识。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Number of rows: 20.

参见

  • mysqli_prepare
  • mysqli_stmt_result_metadata
  • mysqli_stmt_fetch

简介

代表从一个数据库查询中获取的结果集。

更新日志

版本说明
5.4.0Iterator support was added, as mysqli_result now implements Traversable.

类摘要

mysqli_result

class mysqli_result {

/* 属性 */

int$mysqli_result->current_field ;

int$mysqli_result->field_count;

array$mysqli_result->lengths;

int$mysqli_result->num_rows;

/* 方法 */

int mysqli_field_tell ( mysqli_result $result )

bool data_seek ( int $offset )

mixed fetch_all ([ int $resulttype = MYSQLI_NUM ] )

mixed fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

array fetch_assoc ( void )

object fetch_field_direct ( int $fieldnr )

object fetch_field ( void )

array fetch_fields ( void )

object fetch_object ([ string $class_name = "stdClass" [, array $params ]] )

mixed fetch_row ( void )

int mysqli_num_fields ( mysqli_result $result )

bool field_seek ( int $fieldnr )

void free ( void )

array mysqli_fetch_lengths ( mysqli_result $result )

int mysqli_num_rows ( mysqli_result $result )

}

mysqli_result::$current_field

mysqli_field_tell

Get current field offset of a result pointer

说明

面向对象风格

int$mysqli_result->current_field ;

过程化风格

int mysqli_field_tell ( mysqli_result $result )

Returns the position of the field cursor used for the last mysqli_fetch_field call. This value can be used as an argument to mysqli_field_seek.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

Returns current offset of field cursor.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result->current_field;

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Column 1:
Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Column 2:
Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_fetch_field
  • mysqli_field_seek

mysqli_result::data_seek

mysqli_data_seek

Adjusts the result pointer to an arbitrary row in the result

说明

面向对象风格

bool mysqli_result::data_seek ( int $offset )

过程化风格

bool mysqli_data_seek ( mysqli_result $result , int $offset )

The mysqli_data_seek function seeks to an arbitrary result pointer specified by the offset in the result set.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

offset
The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows - 1).

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

注释

Note:

This function can only be used with buffered results attained from the use of the mysqli_store_result or mysqli_query functions.

范例

示例 #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli->query($query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

City: Benin City  Countrycode: NGA

参见

  • mysqli_store_result
  • mysqli_fetch_row
  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_query
  • mysqli_num_rows

mysqli_result::fetch_all

mysqli_fetch_all

Fetches all result rows as an associative array, a numeric array, or both

说明

面向对象风格

mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )

过程化风格

mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] )

mysqli_fetch_all fetches all result rows and returns the result set as an associative array, a numeric array, or both.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

resulttype
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

返回值

Returns an array of associative or numeric arrays holding result rows.

仅 MySQL 原生驱动

仅可用于 mysqlnd

As mysqli_fetch_all returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array, which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all should only be used in those situations where the fetched result set will be sent to another layer for processing.

参见

  • mysqli_fetch_array
  • mysqli_query

mysqli_result::fetch_array

mysqli_fetch_array

Fetch a result row as an associative, a numeric array, or both

说明

面向对象风格

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

过程化风格

mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array is an extended version of the mysqli_fetch_row function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array function can also store the data in associative indices, using the field names of the result set as keys.

Note: class="simpara">此函数返回的字段名大小写敏感

Note: 此函数将 NULL 字段设置为 PHP NULL 值。

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

resulttype
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc, while MYSQLI_NUM will behave identically to the mysqli_fetch_row function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

返回值

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
$result->free();

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

参见

  • mysqli_fetch_assoc
  • mysqli_fetch_row
  • mysqli_fetch_object
  • mysqli_query
  • mysqli_data_seek

mysqli_result::fetch_assoc

mysqli_fetch_assoc

Fetch a result row as an associative array

说明

面向对象风格

array mysqli_result::fetch_assoc ( void )

过程化风格

array mysqli_fetch_assoc ( mysqli_result $result )

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Note: class="simpara">此函数返回的字段名大小写敏感

Note: 此函数将 NULL 字段设置为 PHP NULL 值。

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row or add alias names.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

示例 #3 A mysqli_result example comparing iterator usage

<?php
$c = mysqli_connect('127.0.0.1','user', 'pass');

// Using iterators (support was added with PHP 5.4)
foreach ( $c->query('SELECT user,host FROM mysql.user') as $row ) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

echo "\n==================\n";

// Not using iterators
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

?>

以上例程的输出类似于:

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

==================

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

参见

  • mysqli_fetch_array
  • mysqli_fetch_row
  • mysqli_fetch_object
  • mysqli_query
  • mysqli_data_seek

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

Fetch meta-data for a single field

说明

面向对象风格

object mysqli_result::fetch_field_direct ( int $fieldnr )

过程化风格

object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )

Returns an object which contains field definition information from the specified result set.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

fieldnr
The field number. This value must be in the range from 0 to number of fields - 1.

返回值

Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.

AttributeDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defThe default value for this field, represented as a string
max_lengthThe maximum width of the field for the result set.
lengthThe width of the field, as specified in the table definition.
charsetnrThe character set number for the field.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for numeric fields)

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result->fetch_field_direct(1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_num_fields
  • mysqli_fetch_field
  • mysqli_fetch_fields

mysqli_result::fetch_field

mysqli_fetch_field

Returns the next field in the result set

说明

面向对象风格

object mysqli_result::fetch_field ( void )

过程化风格

object mysqli_fetch_field ( mysqli_result $result )

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

Returns an object which contains field definition information or FALSE if no field information is available.

PropertyDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defReserved for default value, currently always ""
dbDatabase (since PHP 5.3.6)
catalogThe catalog name, always "def" (since PHP 5.3.6)
max_lengthThe maximum width of the field for the result set.
lengthThe width of the field, as specified in the table definition.
charsetnrThe character set number for the field.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_num_fields
  • mysqli_fetch_field_direct
  • mysqli_fetch_fields
  • mysqli_field_seek

mysqli_result::fetch_fields

mysqli_fetch_fields

Returns an array of objects representing the fields in a result set

说明

面向对象风格

array mysqli_result::fetch_fields ( void )

过程化风格

array mysqli_fetch_fields ( mysqli_result $result )

This function serves an identical purpose to the mysqli_fetch_field function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

Returns an array of objects which contains field definition information or FALSE if no field information is available.

PropertyDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
max_lengthThe maximum width of the field for the result set.
lengthThe width of the field, in bytes, as specified in the table definition. Note that this number (bytes) might differ from your table definition value (characters), depending on the character set you use. For example, the character set utf8 has 3 bytes per character, so varchar(10) will return a length of 30 for utf8 (10*3), but return 10 for latin1 (10*1).
charsetnrThe character set number (id) for the field.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

foreach (array('latin1', 'utf8') as $charset) {

    // Set character set, to show its impact on some values (e.g., length in bytes)
    $mysqli->set_charset($charset);

    $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

    echo "======================\n";
    echo "Character Set: $charset\n";
    echo "======================\n";
    
    if ($result = $mysqli->query($query)) {

        /* Get field information for all columns */
        $finfo = $result->fetch_fields();

        foreach ($finfo as $val) {
            printf("Name:      %s\n",   $val->name);
            printf("Table:     %s\n",   $val->table);
            printf("Max. Len:  %d\n",   $val->max_length);
            printf("Length:    %d\n",   $val->length);
            printf("charsetnr: %d\n",   $val->charsetnr);
            printf("Flags:     %d\n",   $val->flags);
            printf("Type:      %d\n\n", $val->type);
        }
        $result->free();
    }
}
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

foreach (array('latin1', 'utf8') as $charset) {

    // Set character set, to show its impact on some values (e.g., length in bytes)
    mysqli_set_charset($link, $charset);

    $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

    echo "======================\n";
    echo "Character Set: $charset\n";
    echo "======================\n";

    if ($result = mysqli_query($link, $query)) {

        /* Get field information for all columns */
        $finfo = mysqli_fetch_fields($result);

        foreach ($finfo as $val) {
            printf("Name:      %s\n",   $val->name);
            printf("Table:     %s\n",   $val->table);
            printf("Max. Len:  %d\n",   $val->max_length);
            printf("Length:    %d\n",   $val->length);
            printf("charsetnr: %d\n",   $val->charsetnr);
            printf("Flags:     %d\n",   $val->flags);
            printf("Type:      %d\n\n", $val->type);
        }
        mysqli_free_result($result);
    }
}

mysqli_close($link);
?>

以上例程会输出:

======================
Character Set: latin1
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    45
charsetnr: 8
Flags:     20489
Type:      253

======================
Character Set: utf8
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    135
charsetnr: 33
Flags:     20489

参见

  • mysqli_num_fields
  • mysqli_fetch_field_direct
  • mysqli_fetch_field

mysqli_result::fetch_object

mysqli_fetch_object

Returns the current row of a result set as an object

说明

面向对象风格

object mysqli_result::fetch_object ([ string $class_name = "stdClass" [, array $params ]] )

过程化风格

object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )

The mysqli_fetch_object will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

Note that mysqli_fetch_object sets the properties of the object before calling the object constructor.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

class_name
The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params
An optional array of parameters to pass to the constructor for class_name objects.

返回值

Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: class="simpara">此函数返回的字段名大小写敏感

Note: 此函数将 NULL 字段设置为 PHP NULL 值。

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

参见

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_row
  • mysqli_query
  • mysqli_data_seek

mysqli_result::fetch_row

mysqli_fetch_row

Get a result row as an enumerated array

说明

面向对象风格

mixed mysqli_result::fetch_row ( void )

过程化风格

mixed mysqli_fetch_row ( mysqli_result $result )

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

mysqli_fetch_row returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: 此函数将 NULL 字段设置为 PHP NULL 值。

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

参见

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_query
  • mysqli_data_seek

mysqli_result::$field_count

mysqli_num_fields

Get the number of fields in a result

说明

面向对象风格

int$mysqli_result->field_count;

过程化风格

int mysqli_num_fields ( mysqli_result $result )

Returns the number of fields from specified result set.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

The number of fields from a result set.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Result set has 5 fields.

参见

  • mysqli_fetch_field

mysqli_result::field_seek

mysqli_field_seek

Set result pointer to a specified field offset

说明

面向对象风格

bool mysqli_result::field_seek ( int $fieldnr )

过程化风格

bool mysqli_field_seek ( mysqli_result $result , int $fieldnr )

Sets the field cursor to the given offset. The next call to mysqli_fetch_field will retrieve the field definition of the column associated with that offset.

Note:

To seek to the beginning of a row, pass an offset value of zero.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

fieldnr
The field number. This value must be in the range from 0 to number of fields - 1.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for 2nd column */
    $result->field_seek(1);
    $finfo = $result->fetch_field();

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_fetch_field

mysqli_result::free

mysqli_result::close

mysqli_result::free_result

mysqli_free_result

Frees the memory associated with a result

说明

面向对象风格

void mysqli_result::free ( void )

void mysqli_result::close ( void )

void mysqli_result::free_result ( void )

过程化风格

void mysqli_free_result ( mysqli_result $result )

Frees the memory associated with the result.

Note:

You should always free your result with class="function">mysqli_free_result, when your result object is not needed anymore.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

没有返回值。

参见

  • mysqli_query
  • mysqli_stmt_store_result
  • mysqli_store_result
  • mysqli_use_result

mysqli_result::$lengths

mysqli_fetch_lengths

Returns the lengths of the columns of the current row in the result set

说明

面向对象风格

array$mysqli_result->lengths;

过程化风格

array mysqli_fetch_lengths ( mysqli_result $result )

The mysqli_fetch_lengths function returns an array containing the lengths of every column of the current row within the result set.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

mysqli_fetch_lengths is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

    $row = $result->fetch_row();

    /* display column lengths */
    foreach ($result->lengths as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Field  1 has Length  3
Field  2 has Length  5
Field  3 has Length 13
Field  4 has Length  9
Field  5 has Length  6
Field  6 has Length  1
Field  7 has Length  6
Field  8 has Length  4
Field  9 has Length  6
Field 10 has Length  6
Field 11 has Length  5
Field 12 has Length 44
Field 13 has Length  7
Field 14 has Length  3
Field 15 has Length  2

mysqli_result::$num_rows

mysqli_num_rows

Gets the number of rows in a result

说明

面向对象风格

int$mysqli_result->num_rows;

过程化风格

int mysqli_num_rows ( mysqli_result $result )

Returns the number of rows in the result set.

The behaviour of mysqli_num_rows depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows will not return the correct number of rows until all the rows in the result have been retrieved.

参数

result
仅以过程化样式:由 mysqli_querymysqli_store_resultmysqli_use_result返回的结果集标识。

返回值

Returns number of rows in the result set.

Note:

If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.

范例

示例 #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

示例 #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上例程会输出:

Result set has 239 rows.

参见

  • mysqli_affected_rows
  • mysqli_store_result
  • mysqli_use_result
  • mysqli_query

简介

MySQLi 驱动.

类摘要

MySQLi_Driver

class MySQLi_Driver {

/* 属性 */

public readonly string $client_info ;

public readonly string $client_version ;

public readonly string $driver_version ;

public readonly string $embedded ;

public bool $reconnect ;

public int $report_mode ;

/* 方法 */

void mysqli_driver::embedded_server_end ( void )

bool mysqli_driver::embedded_server_start ( int $start , array $arguments , array $groups )

bool mysqli_report ( int $flags )

}

属性

client_info
客户端API头版本(比如:(string)"5.1.49")

client_version
客户端版本(比如:(int)50149)

driver_version
Mysqli驱动版本(比如:(int)101009)

embedded
是否开启了MySQLi嵌入式支持。

reconnect
允许或阻止重连接(查看INI指令中的mysqli.reconnect)

report_mode
设置为**MYSQLI_REPORT_OFF**, **MYSQLI_REPORT_ALL**或者 MYSQLI_REPORT_STRICT (为错误抛出异常,译注:需要和MYSQLI_REPORT_ERROR联合使用), MYSQLI_REPORT_ERROR (报告MYSQL错误)和 MYSQLI_REPORT_INDEX (报告索引相关的错误)的任意组合。 参阅mysqli_report.

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

Stop embedded server

说明

面向对象风格

void mysqli_driver::embedded_server_end ( void )

过程化风格

void mysqli_embedded_server_end ( void )

Warning

本函数还未编写文档,仅有参数列表。

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

Initialize and start embedded server

说明

面向对象风格

bool mysqli_driver::embedded_server_start ( int $start , array $arguments , array $groups )

过程化风格

bool mysqli_embedded_server_start ( int $start , array $arguments , array $groups )

Warning

本函数还未编写文档,仅有参数列表。

mysqli_driver::$report_mode

mysqli_report

Enables or disables internal report functions

说明

面向对象风格

int$mysqli_driver->report_mode ;

过程化风格

bool mysqli_report ( int $flags )

A function helpful in improving queries during code development and testing. Depending on the flags, it reports errors from mysqli function calls or queries that don't use an index (or use a bad index).

参数

flags
| Name | Description | |----------------------------|--------------------------------------------------------------------------------------------| | MYSQLI_REPORT_OFF | Turns reporting off | | MYSQLI_REPORT_ERROR | Report errors from mysqli function calls | | MYSQLI_REPORT_STRICT | Throw mysqli_sql_exception for errors instead of warnings | | MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query | | MYSQLI_REPORT_ALL | Set all options (report all) |

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

更新日志

版本说明
5.3.4Changing the reporting mode is now be per-request, rather than per-process.
5.2.15Changing the reporting mode is now be per-request, rather than per-process.

范例

示例 #1 面向对象风格

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

try {

    /* this query should report an error */
    $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

    /* this query should report a bad index */
    $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");

    $result->close();

    $mysqli->close();

} catch (mysqli_sql_exception $e) {

    echo $e->__toString();
}
?>

示例 #2 过程化风格

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = mysqli_query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index */
$result = mysqli_query("SELECT Name FROM City WHERE population > 50000");

mysqli_free_result($result);

mysqli_close($link);
?>

参见

  • mysqli_debug
  • mysqli_dump_debug_info
  • mysqli_sql_exception
  • set_exception_handler
  • error_reporting

简介

表示一个 MySQL 警告。

类摘要

mysqli_warning

class mysqli_warning {

/* 属性 */

public $message ;

public $sqlstate ;

public $errno ;

/* 方法 */

protected __construct ( void )

public bool next ( void )

}

属性

message
消息字符串

sqlstate
SQL状态

errno
错误编号

mysqli_warning::__construct

The __construct purpose

说明

protected mysqli_warning::__construct ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

mysqli_warning::next

Fetch next warning

说明

public bool mysqli_warning::next ( void )

Change warning information to the next warning if possible.

Once the warning has been set to the next warning, new values of properties message, sqlstate and errno of mysqli_warning are available.

参数

此函数没有参数。

返回值

Returns TRUE if next warning was fetched successfully. If there are no more warnings, it will return FALSE

简介

mysqli异常类

类摘要

mysqli_sql_exception

class mysqli_sql_exception extends RuntimeException {

/* 属性 */

protected string $sqlstate ;

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

}

属性

sqlstate
出现错误的sql状态

mysqli_bind_param

mysqli_stmt_bind_param 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_bind_param 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_bind_param

mysqli_bind_result

mysqli_stmt_bind_result 的别名

说明

此函数是该函数的别名: 此函数是 mysqli_stmt_bind_result 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_bind_result

mysqli_client_encoding

mysqli_character_set_name 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_character_set_name 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_real_escape_string

mysqli_connect

别名 mysqli::__construct

说明

此函数是该函数的别名: mysqli::__construct

虽然说在 mysqli::__construct 的文档 对 mysqli_connect 函数也进行了详细的说明, 这里依然给出一个简单的示例:

范例

示例 #1 mysqli_connect 例程

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>

以上例程的输出类似于:

Success: A proper connection to MySQL was made! The my_db database is great.
Host information: localhost via TCP/IP

mysqli::disable_reads_from_master

mysqli_disable_reads_from_master

在主从服务器结构中,禁用从主机读取数据

说明

面向对象风格

void mysqli::disable_reads_from_master ( void )

过程化风格

bool mysqli_disable_reads_from_master ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_disable_rpl_parse

禁用RPL解析

说明

bool mysqli_disable_rpl_parse ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_enable_reads_from_master

开启从主机读取

说明

bool mysqli_enable_reads_from_master ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_enable_rpl_parse

开启RPL解析

说明

bool mysqli_enable_rpl_parse ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_escape_string

别名 mysqli_real_escape_string

说明

此函数是该函数的别名: mysqli_real_escape_string.

mysqli_execute

mysqli_stmt_execute 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_execute 的一个别名。

注释

Note:

mysqli_execute 已经被废弃并且将会被移除。

参见

  • mysqli_stmt_execute

mysqli_fetch

mysqli_stmt_fetch 的别名。

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_fetch 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_fetch

mysqli_get_cache_stats

返回客户端Zval缓存统计信息

Warning

从 PHP 5.4.0 开始,此函数被 移除

说明

array mysqli_get_cache_stats ( void )

Warning

本函数还未编写文档,仅有参数列表。

返回一个空数组。 仅可用于 mysqlnd

参数

返回值

如果成功返回一个空数组,其他情况下返回 FALSE

更新日志

版本说明
5.4.0The mysqli_get_cache_stats 被移除。
5.3.0加入 mysqli_get_cache_stats

mysqli_get_client_stats

返回客户端进程统计信息

说明

array mysqli_get_client_stats ( void )

返回客户端进程统计信息 仅可用于 mysqlnd

参数

返回值

如果成功,则返回一个数组包含客户端进程的统计信息,否则返回 FALSE

范例

示例 #1 A mysqli_get_client_stats 例程

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

以上例程的输出类似于:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

参见

mysqli_get_links_stats

返回打开和缓存的链接相关信息

说明

array mysqli_get_links_stats ( void )

mysqli_get_links_stats 返回已经打开和缓存的MySQL链接的相关信息。

参数

此函数没有参数。

返回值

mysqli_get_links_stats 返回一个有三个元素的关联数组, 键如下:

total
类型 integer 所有状态链接的总数

active_plinks
类型 integer 不活跃的持久链接数

cached_plinks
类型 integer 不活跃的持久链接数

mysqli_get_metadata

mysqli_stmt_result_metadata 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_result_metadata 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_result_metadata

mysqli_master_query

在主/从机制中强制在主机中执行一个查询

说明

bool mysqli_master_query ( mysqli $link , string $query )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_param_count

mysqli_stmt_param_count 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_param_count 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_param_count

mysqli_report

别名 mysqli_driver->report_mode

说明

此函数是该函数的别名: mysqli_driver->report_mode

mysqli_rpl_parse_enabled

检查是否开启了 RPL 解析

说明

int mysqli_rpl_parse_enabled ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_rpl_probe

RPL 探测

说明

bool mysqli_rpl_probe ( mysqli $link )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

mysqli_send_long_data

mysqli_stmt_send_long_data 的别名

说明

此函数是该函数的别名: 这个函数是 mysqli_stmt_send_long_data 的一个别名。

Warning

本函数已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

参见

  • mysqli_stmt_send_long_data

mysqli::set_opt

mysqli_set_opt

Alias of mysqli_options

说明

此函数是该函数的别名: 这个函数是 mysqli_options 的一个别名。

mysqli_slave_query

在主/从机制中强制在从机上执行一个查询

说明

bool mysqli_slave_query ( mysqli $link , string $query )

Warning

本函数还未编写文档,仅有参数列表。

Warning

自 PHP 5.3.0 起,已经废弃移除此函数。

目录

Mysql_xdevapi

目录

This extension provides access to the MySQL Document Store via the X DevAPI. The X DevAPI is a common API provided by multiple MySQL Connectors providing easy access to relational tables as well as collections of documents, which are represented in JSON, from a API with CRUD-style operations.

The X DevAPI uses the X Protocol, the new generation client-server protocol of the MySQL 8.0 server.

For general information about the MySQL Document Store, please refer to the » MySQL Document Store chapter in the MySQL manual.

安装/配置

目录

需求

This extension requires a MySQL 8+ server with the X plugin enabled (default).

Prerequisite libraries for compiling this extension are: Boost (1.53.0 or higher), OpenSSL, and Protobuf.

安装

» PECL 扩展未与 PHP 捆绑。

An example installation procedure on Ubuntu 18.04 with PHP 7.2:

// Dependencies
$ apt install build-essential libprotobuf-dev libboost-dev openssl protobuf-compiler

// PHP with the desired extensions; php7.2-dev is required to compile
$ apt install php7.2-cli php7.2-dev php7.2-mysql php7.2-pdo php7.2-xml

// Compile the extension
$ pecl install mysql_xdevapi

The pecl install command does not enable PHP extensions (by default) and enabling PHP extensions can be done in several ways. Another PHP 7.2 on Ubuntu 18.04 example:

// Create its own ini file
$ echo "extension=mysql_xdevapi.so" > /etc/php/7.2/mods-available/mysql_xdevapi.ini

// Use the 'phpenmod' command (note: it's Debian/Ubuntu specific)
$ phpenmod -v 7.2 -s ALL mysql_xdevapi

// A 'phpenmod' alternative is to manually symlink it
// $ ln -s /etc/php/7.2/mods-available/mysql_xdevapi.ini /etc/php/7.2/cli/conf.d/20-mysql_xdevapi.ini

// Let's see which MySQL extensions are enabled now
$ php -m |grep mysql

mysql_xdevapi
mysqli
mysqlnd
pdo_mysql

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等,都在此处: » https://pecl.php.net/package/mysql_xdevapi.

运行时配置

这些函数的行为受 php.ini 中的设置影响。

名字默认可修改范围更新日志
xmysqlnd.collect_memory_statistics0PHP_INI_SYSTEM
xmysqlnd.collect_statistics1PHP_INI_ALL
xmysqlnd.debug PHP_INI_SYSTEM
xmysqlnd.mempool_default_size16000PHP_INI_ALL
xmysqlnd.net_read_timeout31536000PHP_INI_SYSTEM
xmysqlnd.trace_alloc PHP_INI_SYSTEM

这是配置指令的简短说明。

xmysqlnd.collect_memory_statistics integer

xmysqlnd.collect_statistics integer

xmysqlnd.debug string

xmysqlnd.mempool_default_size integer

xmysqlnd.net_read_timeout integer

xmysqlnd.trace_alloc string

Building / Compiling From Source

Considerations for compiling this extension from source.

  • The extension name is 'mysql_xdevapi', so use --enable-mysql-xdevapi.

  • Boost: required, optionally use the --with-boost=DIR configure option or set the MYSQL_XDEVAPI_BOOST_ROOT environment variable. Only the boost header files are required; not the binaries.

  • Google Protocol Buffers (protobuf): required, optionally use the --with-protobuf=DIR configure option or set the MYSQL_XDEVAPI_PROTOBUF_ROOT environment variable.

    Optionally use make protobufs to generate protobuf files (*.pb.cc/.h), and make clean-protobufs to delete generate protobuf files.

    Windows specific protobuf note: depending on your environment, the static library with a multi-threaded DLL runtime may be needed. To prepare, use the following options: -Dprotobuf_MSVC_STATIC_RUNTIME=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF

  • Google Protocol Buffers / protocol compiler (protoc): required, ensure that proper 'protoc' is available in the PATH while building. It is especially important as Windows PHP SDK batch scripts may overwrite the environment.

  • Bison: required, and available from the PATH.

    Windows specific bison note: we strongly recommended that bison delivered with the chosen PHP SDKis used else an error similar to "zend_globals_macros.h(39): error C2375: 'zendparse': redefinition; different linkage Zend/zend_language_parser.h(214): note: see declaration of 'zendparse'" may be the result. Also, Windows PHP SDK batch scripts may overwrite the environment.

  • Windows Specific Notes: To prepare the environment, see the official Windows build documentation for either » the original SDK (older, PHP-7.1 only) or » the current SDK (PHP-7.1 or newer).

    We recommend using the backslash '\\' instead of a slash '/' for all paths.

预定义常量

下列常量由此扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MYSQLX_CLIENT_SSL (integer)

MYSQLX_TYPE_DECIMAL (integer)

MYSQLX_TYPE_TINY (integer)

MYSQLX_TYPE_SHORT (integer)

MYSQLX_TYPE_SMALLINT (integer)

MYSQLX_TYPE_MEDIUMINT (integer)

MYSQLX_TYPE_INT (integer)

MYSQLX_TYPE_BIGINT (integer)

MYSQLX_TYPE_LONG (integer)

MYSQLX_TYPE_FLOAT (integer)

MYSQLX_TYPE_DOUBLE (integer)

MYSQLX_TYPE_NULL (integer)

MYSQLX_TYPE_TIMESTAMP (integer)

MYSQLX_TYPE_LONGLONG (integer)

MYSQLX_TYPE_INT24 (integer)

MYSQLX_TYPE_DATE (integer)

MYSQLX_TYPE_TIME (integer)

MYSQLX_TYPE_DATETIME (integer)

MYSQLX_TYPE_YEAR (integer)

MYSQLX_TYPE_NEWDATE (integer)

MYSQLX_TYPE_ENUM (integer)

MYSQLX_TYPE_SET (integer)

MYSQLX_TYPE_TINY_BLOB (integer)

MYSQLX_TYPE_MEDIUM_BLOB (integer)

MYSQLX_TYPE_LONG_BLOB (integer)

MYSQLX_TYPE_BLOB (integer)

MYSQLX_TYPE_VAR_STRING (integer)

MYSQLX_TYPE_STRING (integer)

MYSQLX_TYPE_CHAR (integer)

MYSQLX_TYPE_BYTES (integer)

MYSQLX_TYPE_INTERVAL (integer)

MYSQLX_TYPE_GEOMETRY (integer)

MYSQLX_TYPE_JSON (integer)

MYSQLX_TYPE_NEWDECIMAL (integer)

MYSQLX_TYPE_BIT (integer)

MYSQLX_LOCK_DEFAULT (integer)

MYSQLX_LOCK_NOWAIT (integer)

MYSQLX_LOCK_SKIP_LOCKED (integer)

范例

The central entry point to the X DevAPI is the mysql_xdevapi\getSession function, which receives a URI to a MySQL 8.0 Server and returns a mysql_xdevap\Session object.

示例 #1 Connecting to a MySQL Server

<?php
try {
    $session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
    die("Connection could not be established: " . $e->getMessage());
}
 
// ... use $session
?>

The session provides full access to the API. For a new MySQL Server installation, the first step is to create a database schema with a collection to store data:

示例 #2 Creating a Schema and Collection on the MySQL Server

<?php
$schema = $session->createSchema("test");
$collection = $schema->createCollection("example");
?>

When storing data, typically json_encode is used to encode the data into JSON, which can then be stored inside a collection.

The following example stores data into the collection we created earlier, and then retrieve parts of it again.

示例 #3 Storing and Retrieving Data

<?php
$marco = [
  "name" => "Marco",
  "age"  => 19,
  "job"  => "Programmer"
];
$mike = [
  "name" => "Mike",
  "age"  => 39,
  "job"  => "Manager"
];

$schema = $session->getSchema("test");
$collection = $schema->getCollection("example");

$collection->add($marco, $mike)->execute();

var_dump($collection->find("name = 'Mike'")->execute()->fetchOne());
?>

以上例程的输出类似于:

array(4) {
  ["_id"]=>
  string(28) "00005ad66aaf0000000000000003"
  ["age"]=>
  int(39)
  ["job"]=>
  string(7) "Manager"
  ["name"]=>
  string(4) "Mike"
}

The example demonstrates that the MySQL Server adds an extra field named _id, which serves as primary key to the document.

The example also demonstrates that retrieved data is sorted alphabetically. That specific order comes from the efficient binary storage inside the MySQL server, but it should not be relied upon. Refer to the MySQL JSON datatype documentation for details.

Optionally use PHP's iterators fetch multiple documents:

示例 #4 Fetching and Iterating Multiple Documents

<?php
$result = $collection->find()->execute();
foreach ($result as $doc) {
  echo "${doc["name"]} is a ${doc["job"]}.\n";
}
?>

以上例程的输出类似于:

Marco is a Programmer.
Mike is a Manager.

expression

Bind prepared statement variables as parameters

说明

object mysql_xdevapi\expression ( string $expression )

Warning

本函数还未编写文档,仅有参数列表。

参数

expression

返回值

范例

示例 #1 mysql_xdevapi\Expression example

<?php
$expression = mysql_xdevapi\Expression("[age,job]");

$res  = $coll->find("age > 30")->fields($expression)->limit(3)->execute();
$data = $res->fetchAll();

print_r($data);
?>

以上例程的输出类似于:

<?php

getSession

Connect to a MySQL server

说明

mysql_xdevapi\Session mysql_xdevapi\getSession ( string $uri )

Connects to the MySQL server.

参数

uri
The URI to the MySQL server, such as mysqlx://user:password@host.

URI format:

scheme://[user[:[password]]@]target[:port][?attribute1=value1&attribute2=value2...

  • scheme: required, the connection protocol

    In mysql_xdevapi it is always 'mysqlx' (for X Protocol)

  • user: optional, the MySQL user account for authentication

  • password: optional, the MySQL user's password for authentication

  • target: required, the server instance the connection refers to:

    * TCP connection (host name, IPv4 address, or IPv6 address)

    * Unix socket path (local file path)

    * Windows named-pipe (local file path)

  • port: optional, network port of MySQL server.

    by default port for X Protocol is 33060

  • ?attribute=value: this element is optional and specifies a data dictionary that contains different options, including:

    • The auth (authentication mechanism) attribute as it relates to encrypted connections. For additional information, see » Command Options for Encrypted Connections. The following 'auth' values are supported: plain, mysql41, external, and sha256_mem.

    • The connect-timeout attribute affects the connection and not subsequent operations. It is set per connection whether on a single or multiple hosts.

      Pass in a positive integer to define the connection timeout in seconds, or pass in 0 (zero) to disable the timeout (infinite). Not defining connect-timeout uses the default value of 10.

      Related, the MYSQLX_CONNECTION_TIMEOUT (timeout in seconds) and MYSQLX_TEST_CONNECTION_TIMEOUT (used while running tests) environment variables can be set and used instead of connect-timeout in the URI. The connect-timeout URI option has precedence over these environment variables.

    • The optional compression attribute accepts these values: preferred (client negotiates with server to find a supported algorithm; connection is uncompressed if a mutually supported algorithm is not found), required (like "preferred", but connection is terminated if a mutually supported algorithm is not found), or disabled (connection is uncompressed). Defaults to preferred.

      This option was added in version 8.0.20.

示例 #1 URI examples

mysqlx://foobar
mysqlx://root@localhost?socket=%2Ftmp%2Fmysqld.sock%2F
mysqlx://foo:bar@localhost:33060
mysqlx://foo:bar@localhost:33160?ssl-mode=disabled
mysqlx://foo:bar@localhost:33260?ssl-mode=required
mysqlx://foo:bar@localhost:33360?ssl-mode=required&auth=mysql41
mysqlx://foo:bar@(/path/to/socket)
mysqlx://foo:bar@(/path/to/socket)?auth=sha256_mem
mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]
mysqlx://foobar?ssl-ca=(/path/to/ca.pem)&ssl-crl=(/path/to/crl.pem)
mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]?ssl-mode=disabled
mysqlx://foo:bar@localhost:33160/?connect-timeout=0
mysqlx://foo:bar@localhost:33160/?connect-timeout=10&compression=required

For related information, see MySQL Shell's » Connecting using a URI String.

返回值

A Session object.

错误/异常

A connection failure throws an Exception.

范例

示例 #2 mysql_xdevapi\getSession example

<?php
try {
    $session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
    die("Connection could not be established: " . $e->getMessage());
}

$schemas = $session->getSchemas();
print_r($schemas);

$mysql_version = $session->getServerVersion();
print_r($mysql_version);

var_dump($collection->find("name = 'Alfred'")->execute()->fetchOne());
?>

以上例程的输出类似于:

Array
(
    [0] => mysql_xdevapi\Schema Object
        (
            [name] => helloworld
        )
    [1] => mysql_xdevapi\Schema Object
        (
            [name] => information_schema
        )
    [2] => mysql_xdevapi\Schema Object
        (
            [name] => mysql
        )
    [3] => mysql_xdevapi\Schema Object
        (
            [name] => performance_schema
        )
    [4] => mysql_xdevapi\Schema Object
        (
            [name] => sys
        )
)

80012

array(4) {
  ["_id"]=>
  string(28) "00005ad66abf0001000400000003"
  ["age"]=>
  int(42)
  ["job"]=>
  string(7) "Butler"
  ["name"]=>
  string(4) "Alfred"
}

目录

  • expression — Bind prepared statement variables as parameters
  • getSession — Connect to a MySQL server

简介

类摘要

mysql_xdevapi\BaseResult

class mysql_xdevapi\BaseResult {

/* 方法 */

abstract public array getWarnings ( void )

abstract public integer getWarningsCount ( void )

}

BaseResult::getWarnings

Fetch warnings from last operation

说明

abstract public array mysql_xdevapi\BaseResult::getWarnings ( void )

Fetches warnings generated by MySQL server's last operation.

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

范例

示例 #1 mysql_xdevapi\RowResult::getWarnings example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table  = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();

print_r($warnings);
?>

以上例程的输出类似于:

Array
(
    [0] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
    [1] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
)

BaseResult::getWarningsCount

Fetch warning count from last operation

说明

abstract public integer mysql_xdevapi\BaseResult::getWarningsCount ( void )

Returns the number of warnings raised by the last operation. Specifically, these warnings are raised by the MySQL server.

参数

此函数没有参数。

返回值

The number of warnings from the last operation.

范例

示例 #1 mysql_xdevapi\RowResult::getWarningsCount example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table  = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();

echo $res->getWarningsCount();
?>

以上例程的输出类似于:

2

简介

Provides access to the connection pool.

类摘要

mysql_xdevapi\Client

class mysql_xdevapi\Client {

/* 方法 */

public bool close ( void )

public mysql_xdevapi\Session getSession ( void )

}

mysql_xdevapi\Client::close

Close client

说明

public bool mysql_xdevapi\Client::close ( void )

Close all client connections with the server.

参数

此函数没有参数。

返回值

TRUE if connections are closed.

Client::__construct

Client constructor

说明

private mysql_xdevapi\Client::__construct ( void )

Construct a client object.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\Client::__construct example

<?php
$pooling_options = '{
  "enabled": true,
    "maxSize": 10,
    "maxIdleTime": 3600,
    "queueTimeOut": 1000
}';
$client = mysql_xdevapi\getClient($connection_uri, $pooling_options);
$session = $client->getSession();

Client::getClient

Get client session

说明

public mysql_xdevapi\Session mysql_xdevapi\Client::getSession ( void )

Get session associated with the client.

参数

此函数没有参数。

返回值

A Session object.

简介

类摘要

mysql_xdevapi\Collection

class mysql_xdevapi\Collection implements mysql_xdevapi\SchemaObject {

/* 属性 */

public $name ;

/* 方法 */

public mysql_xdevapi\CollectionAdd add ( mixed $document )

public mysql_xdevapi\Result addOrReplaceOne ( string $id , string $doc )

public integer count ( void )

public void createIndex ( string $index_name , string $index_desc_json )

public bool dropIndex ( string $index_name )

public bool existsInDatabase ( void )

public mysql_xdevapi\CollectionFind find ([ string $search_condition ] )

public string getName ( void )

public Document getOne ( string $id )

public Schema Object getSchema ( void )

public Session getSession ( void )

public mysql_xdevapi\CollectionModify modify ( string $search_condition )

public mysql_xdevapi\CollectionRemove remove ( string $search_condition )

public mysql_xdevapi\Result removeOne ( string $id )

public mysql_xdevapi\Result replaceOne ( string $id , string $doc )

}

属性

name

Collection::add

Add collection document

说明

public mysql_xdevapi\CollectionAdd mysql_xdevapi\Collection::add ( mixed $document )

Triggers the insertion of the given document(s) into the collection, and multiple variants of this method are supported. Options include:

  1. Add a single document as a JSON string.

  2. Add a single document as an array as: [ 'field' => 'value', 'field2' => 'value2' ... ]

  3. A mix of both, and multiple documents can be added in the same operation.

参数

document
One or multiple documents, and this can be either JSON or an array of fields with their associated values. This cannot be an empty array.

The MySQL server automatically generates unique _id values for each document (recommended), although this can be manually added as well. This value must be unique as otherwise the add operation will fail.

返回值

A CollectionAdd object. Use execute() to return a Result that can be used to query the number of affected items, the number warnings generated by the operation, or to fetch a list of generated IDs for the inserted documents.

范例

示例 #1 mysql_xdevapi\Collection::add example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection->add('{"name": "Fred",  "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

// Add two documents using a single JSON object
$result = $collection->add(
  '{"name": "Bernie",
    "jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
    "hobbies": ["Sports","Making cupcakes"]}',
  '{"name": "Jane",
    "jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
    "hobbies": ["Walking","Making pies"]}')->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>

以上例程的输出类似于:

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

注释

Note:

A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

Collection::addOrReplaceOne

Add or replace collection document

说明

public mysql_xdevapi\Result mysql_xdevapi\Collection::addOrReplaceOne ( string $id , string $doc )

Add a new document, or replace a document if it already exists.

Here are several scenarios for this method:

  • If neither the id or any unique key values conflict with any document in the collection, then the document is added.

  • If the id does not match any document but one or more unique key values conflict with a document in the collection, then an error is raised.

  • If id matches an existing document and no unique keys are defined for the collection, then the document is replaced.

  • If id matches an existing document, and either all unique keys in the replacement document match that same document or they don't conflict with any other documents in the collection, then the document is replaced.

  • If id matches an existing document and one or more unique keys match a different document from the collection, then an error is raised.

参数

id
This is the filter id. If this id or any other field that has a unique index already exists in the collection, then it will update the matching document instead.

By default, this id is automatically generated by MySQL Server when the record was added, and is referenced as a field named '_id'.

doc
This is the document to add or replace, which is a JSON string.

返回值

A Result object.

范例

示例 #1 mysql_xdevapi\Collection::addOrReplaceOne example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Using add()
$result = $collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

// Using addOrReplaceOne()
// Note: we're passing in a known _id value here
$result = $collection->addOrReplaceOne('00005b6b53610000000000000056', '{"name": "Fred",  "age": 21, "job": "Construction"}');

?>

Collection::__construct

Collection constructor

说明

private mysql_xdevapi\Collection::__construct ( void )

Construct a Collection object.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\Collection::getOne example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();

// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids        = $result->getGeneratedIds();
$alfreds_id = $ids[0];

// ...

print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>

以上例程的输出类似于:

00005b6b536100000000000000b1

Array
(
    [_id] => 00005b6b536100000000000000b1
    [age] => 42
    [job] => Butler
    [name] => Alfred
)

Collection::count

Get document count

说明

public integer mysql_xdevapi\Collection::count ( void )

This functionality is similar to a SELECT COUNT(*) SQL operation against the MySQL server for the current schema and collection. In other words, it counts the number of documents in the collection.

参数

此函数没有参数。

返回值

The number of documents in the collection.

范例

示例 #1 mysql_xdevapi\Collection::count example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

$result = $collection
  ->add(
  '{"name": "Bernie",
    "jobs": [
      {"title":"Cat Herder","Salary":42000}, 
      {"title":"Father","Salary":0}
    ],
    "hobbies": ["Sports","Making cupcakes"]}',
  '{"name": "Jane",
    "jobs": [
      {"title":"Scientist","Salary":18000}, 
      {"title":"Mother","Salary":0}
    ],
    "hobbies": ["Walking","Making pies"]}')
  ->execute();

var_dump($collection->count());
?>

以上例程会输出:

int(2)

Collection::createIndex

Create collection index

说明

public void mysql_xdevapi\Collection::createIndex ( string $index_name , string $index_desc_json )

Creates an index on the collection.

An exception is thrown if an index with the same name already exists, or if index definition is not correctly formed.

参数

index_name
The name of the index that to create. This name must be a valid index name as accepted by the CREATE INDEX SQL query.

index_desc_json
Definition of the index to create. It contains an array of IndexField objects, and each object describes a single document member to include in the index, and an optional string for the type of index that might be INDEX (default) or SPATIAL.

A single IndexField description consists of the following fields:

  • field: string, the full document path to the document member or field to be indexed.

  • type: string, one of the supported SQL column types to map the field into. For numeric types, the optional UNSIGNED keyword may follow. For the TEXT type, the length to consider for indexing may be added.

  • required: bool, (optional) true if the field is required to exist in the document. Defaults to FALSE, except for GEOJSON where it defaults to TRUE.

  • options: integer, (optional) special option flags for use when decoding GEOJSON data.

  • srid: integer, (optional) srid value for use when decoding GEOJSON data.

It is an error to include other fields not described above in IndexDefinition or IndexField documents.

返回值

范例

示例 #1 mysql_xdevapi\Collection::createIndex example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

// Creating a text index
$collection->createIndex(
  'myindex1', 
  '{"fields": [{
    "field": "$.name", 
    "type": "TEXT(25)", 
    "required": true}], 
    "unique": false}'
);

// A spatial index
$collection->createIndex(
  'myindex2', 
  '{"fields": [{
    "field": "$.home", 
    "type": "GEOJSON", 
    "required": true}], 
    "type": "SPATIAL"}'
);

// Index with multiple fields
$collection->createIndex(
  'myindex3', 
  '{"fields": [
    {
      "field": "$.name",
      "type": "TEXT(20)",
      "required": true
    },
    {
      "field": "$.age",
      "type": "INTEGER"
    },
    {
      "field": "$.job",
      "type": "TEXT(30)",
      "required": false
    }
  ],
  "unique": true
  }'
);

Collection::dropIndex

Drop collection index

说明

public bool mysql_xdevapi\Collection::dropIndex ( string $index_name )

Drop a collection index.

This operation does not yield an error if the index does not exist, but FALSE is returned in that case.

参数

index_name
Name of collection index to drop.

返回值

TRUE if the DROP INDEX operation succeeded, otherwise FALSE.

范例

示例 #1 mysql_xdevapi\Collection::dropIndex example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

// ...

$collection = $schema->getCollection("people");

$collection->createIndex(
  'myindex', 
  '{"fields": [{"field": "$.name", "type": "TEXT(25)", "required": true}], "unique": false}'
);

// ...

if ($collection->dropIndex('myindex')) {
    echo 'An index named 'myindex' was found, and dropped.';
}
?>

以上例程会输出:

An index named 'myindex' was found, and dropped.

Collection::existsInDatabase

Check if collection exists in database

说明

public bool mysql_xdevapi\Collection::existsInDatabase ( void )

Checks if the Collection object refers to a collection in the database (schema).

参数

此函数没有参数。

返回值

Returns TRUE if collection exists in the database, else FALSE if it does not.

范例

示例 #1 mysql_xdevapi\Collection::existsInDatabase example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

// ...

$collection = $schema->getCollection("people");

// ...

if (!$collection->existsInDatabase()) {
    echo "The collection no longer exists in the database named addressbook. What happened?";
}
?>

Collection::find

Search for document

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\Collection::find ([ string $search_condition ] )

Search a database collection for a document or set of documents. The found documents are returned as a CollectionFind object is to further modify or fetch results from.

参数

search_condition
Although optional, normally a condition is defined to limit the results to a subset of documents.

Multiple elements might build the condition and the syntax supports parameter binding. The expression used as search condition must be a valid SQL expression. If no search condition is provided (field empty) then find('true') is assumed.

返回值

A CollectionFind object to verify the operation, or fetch the found documents.

范例

示例 #1 mysql_xdevapi\Collection::find example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred",     "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob",        "age": 19, "job": "Swimmer"}')->execute();
$collection->add('{"name": "Fred",       "age": 20, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma",      "age": 21, "job": "Teacher"}')->execute();
$collection->add('{"name": "Suki",       "age": 22, "job": "Teacher"}')->execute();

$find   = $collection->find('job LIKE :job AND age > :age');
$result = $find
  ->bind(['job' => 'Teacher', 'age' => 20])
  ->sort('age DESC')
  ->limit(2)            
  ->execute();

print_r($result->fetchAll());
?>

以上例程会输出:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b536100000000000000a8
            [age] => 22
            [job] => Teacher
            [name] => Suki
        )
    [1] => Array
        (
            [_id] => 00005b6b536100000000000000a7
            [age] => 21
            [job] => Teacher
            [name] => Wilma
        )
)

Collection::getName

Get collection name

说明

public string mysql_xdevapi\Collection::getName ( void )

Retrieve the collection's name.

参数

此函数没有参数。

返回值

The collection name, as a string.

范例

示例 #1 mysql_xdevapi\Collection::getName example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");


// ...

var_dump($collection->getName());
?>

以上例程的输出类似于:

string(6) "people"

Collection::getOne

Get one document

说明

public Document mysql_xdevapi\Collection::getOne ( string $id )

Fetches one document from the collection.

This is a shortcut for: Collection.find("_id = :id").bind("id", id).execute().fetchOne();

参数

id
The document _id in the collection.

返回值

The collection object, or NULL if the _id does not match a document.

范例

示例 #1 mysql_xdevapi\Collection::getOne example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();

// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids        = $result->getGeneratedIds();
$alfreds_id = $ids[0];

// ...

print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>

以上例程的输出类似于:

00005b6b536100000000000000b1

Array
(
    [_id] => 00005b6b536100000000000000b1
    [age] => 42
    [job] => Butler
    [name] => Alfred
)

Collection::getSchema

Get schema object

说明

public Schema Object mysql_xdevapi\Collection::getSchema ( void )

Retrieve the schema object that contains the collection.

参数

此函数没有参数。

返回值

The schema object on success, or NULL if the object cannot be retrieved for the given collection.

范例

示例 #1 mysql_xdevapi\Collection::getSchema example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

var_dump($collection->getSchema());
?>

以上例程的输出类似于:

object(mysql_xdevapi\Schema)#9 (1) {
  ["name"]=>
  string(11) "addressbook"
}

Collection::getSession

Get session object

说明

public Session mysql_xdevapi\Collection::getSession ( void )

Get a new Session object from the Collection object.

参数

此函数没有参数。

返回值

A Session object.

范例

示例 #1 mysql_xdevapi\Collection::getSession example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

// ...

$newsession = $collection->getSession();

var_dump($session);
var_dump($newsession);
?>

以上例程的输出类似于:

object(mysql_xdevapi\Session)#1 (0) {
}
object(mysql_xdevapi\Session)#4 (0) {
}

Collection::modify

Modify collection documents

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\Collection::modify ( string $search_condition )

Modify collections that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

参数

search_condition
Must be a valid SQL expression used to match the documents to modify. This expression might be as simple as TRUE, which matches all documents, or it might use functions and operators such as 'CAST(_id AS SIGNED) >= 10', 'age MOD 2 = 0 OR age MOD 3 = 0', or '_id IN ["2","5","7","10"]'.

返回值

If the operation is not executed, then the function will return a Modify object that can be used to add additional modify operations.

If the modify operation is executed, then the returned object will contain the result of the operation.

范例

示例 #1 mysql_xdevapi\Collection::modify example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob",    "age": 19, "job": "Painter"}')->execute();

// Add two new jobs for all Painters: Artist and Crafter
$collection
  ->modify("job in ('Butler', 'Painter')")
  ->arrayAppend('job', 'Artist')
  ->arrayAppend('job', 'Crafter')
  ->execute();

// Remove the 'beer' field from all documents with the age 21
$collection
  ->modify('age < 21')
  ->unset(['beer'])
  ->execute();
?>

Collection::remove

Remove collection documents

说明

public mysql_xdevapi\CollectionRemove mysql_xdevapi\Collection::remove ( string $search_condition )

Remove collections that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

参数

search_condition
Must be a valid SQL expression used to match the documents to modify. This expression might be as simple as TRUE, which matches all documents, or it might use functions and operators such as 'CAST(_id AS SIGNED) >= 10', 'age MOD 2 = 0 OR age MOD 3 = 0', or '_id IN ["2","5","7","10"]'.

返回值

If the operation is not executed, then the function will return a Remove object that can be used to add additional remove operations.

If the remove operation is executed, then the returned object will contain the result of the operation.

范例

示例 #1 mysql_xdevapi\Collection::remove example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob",    "age": 19, "job": "Painter"}')->execute();

// Remove all painters
$collection
  ->remove("job in ('Painter')")
  ->execute();

// Remove the oldest butler
$collection
  ->remove("job in ('Butler')")
  ->sort('age desc')
  ->limit(1)
  ->execute();

// Remove record with lowest age
$collection
  ->remove('true')
  ->sort('age desc')
  ->limit(1)
  ->execute();
?>

Collection::removeOne

Remove one collection document

说明

public mysql_xdevapi\Result mysql_xdevapi\Collection::removeOne ( string $id )

Remove one document from the collection with the correspending ID. This is a shortcut for Collection.remove("_id = :id").bind("id", id).execute().

参数

id
The ID of the collection document to remove. Typically this is the _id that was generated by MySQL Server when the record was added.

返回值

A Result object that can be used to query the number of affected items or the number warnings generated by the operation.

范例

示例 #1 mysql_xdevapi\Collection::removeOne example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();

// Normally the _id is known by other means, 
// but for this example let's fetch the generated id and use it
$ids       = $result->getGeneratedIds();
$alfred_id = $ids[0];

$result = $collection->removeOne($alfred_id);

if(!$result->getAffectedItemsCount()) {
    echo "Alfred with id $alfred_id was not removed.";
} else {
    echo "Goodbye, Alfred, you can take _id $alfred_id with you.";
}
?>

以上例程的输出类似于:

Goodbye, Alfred, you can take _id 00005b6b536100000000000000cb with you.

Collection::replaceOne

Replace one collection document

说明

public mysql_xdevapi\Result mysql_xdevapi\Collection::replaceOne ( string $id , string $doc )

Updates (or replaces) the document identified by ID, if it exists.

参数

id
ID of the document to replace or update. Typically this is the _id that was generated by MySQL Server when the record was added.

doc
Collection document to update or replace the document matching the id parameter.

This document can be either a document object or a valid JSON string describing the new document.

返回值

A Result object that can be used to query the number of affected items and the number warnings generated by the operation.

范例

示例 #1 mysql_xdevapi\Collection::replaceOne example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();

// Normally the _id is known by other means, 
// but for this example let's fetch the generated id and use it
$ids       = $result->getGeneratedIds();
$alfred_id = $ids[0];

// ...

$alfred = $collection->getOne($alfred_id);
$alfred['age'] = 81;
$alfred['job'] = 'Guru';

$collection->replaceOne($alfred_id, $alfred);

?>

简介

类摘要

mysql_xdevapi\CollectionAdd

class mysql_xdevapi\CollectionAdd implements mysql_xdevapi\Executable {

/* 方法 */

public mysql_xdevapi\Result execute ( void )

}

CollectionAdd::__construct

CollectionAdd constructor

说明

private mysql_xdevapi\CollectionAdd::__construct ( void )

Use to add a document to a collection; called from a Collection object.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\CollectionAdd::__construct example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection
  ->add('{"name": "Fred",  "age": 21, "job": "Construction"}')
  ->execute();

$collection
  ->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
  ->execute();

// Add two documents using a single JSON object
$result = $collection
  ->add(
    '{"name": "Bernie",
      "jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
      "hobbies": ["Sports","Making cupcakes"]}',
    '{"name": "Jane",
      "jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
      "hobbies": ["Walking","Making pies"]}')
  ->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);

?>

以上例程的输出类似于:

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

注释

Note:

A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

CollectionAdd::execute

Execute the statement

说明

public mysql_xdevapi\Result mysql_xdevapi\CollectionAdd::execute ( void )

The execute method is required to send the CRUD operation request to the MySQL server.

参数

此函数没有参数。

返回值

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

范例

示例 #1 mysql_xdevapi\CollectionAdd::execute example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection
  ->add('{"name": "Fred",  "age": 21, "job": "Construction"}')
  ->execute();

$collection
  ->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
  ->execute();

// Add two documents using a single JSON object
$result = $collection
  ->add(
    '{"name": "Bernie",
      "jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
      "hobbies": ["Sports","Making cupcakes"]}',
    '{"name": "Jane",
      "jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
      "hobbies": ["Walking","Making pies"]}')
  ->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>

以上例程的输出类似于:

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

简介

类摘要

mysql_xdevapi\CollectionFind

class mysql_xdevapi\CollectionFind implements mysql_xdevapi\Executable , mysql_xdevapi\CrudOperationBindable , mysql_xdevapi\CrudOperationLimitable , mysql_xdevapi\CrudOperationSortable {

/* 方法 */

public mysql_xdevapi\CollectionFind bind ( array $placeholder_values )

public mysql_xdevapi\DocResult execute ( void )

public mysql_xdevapi\CollectionFind fields ( string $projection )

public mysql_xdevapi\CollectionFind groupBy ( string $sort_expr )

public mysql_xdevapi\CollectionFind having ( string $sort_expr )

public mysql_xdevapi\CollectionFind limit ( integer $rows )

public mysql_xdevapi\CollectionFind lockExclusive ([ integer $lock_waiting_option ] )

public mysql_xdevapi\CollectionFind lockShared ([ integer $lock_waiting_option ] )

public mysql_xdevapi\CollectionFind offset ( integer $position )

public mysql_xdevapi\CollectionFind sort ( string $sort_expr )

}

CollectionFind::bind

Bind value to query placeholder

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::bind ( array $placeholder_values )

It allows the user to bind a parameter to the placeholder in the search condition of the find operation. The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME, NAME is the actual name of the placeholder. The bind function accepts a list of placeholders if multiple entities have to be substituted in the search condition.

参数

placeholder_values
Values to substitute in the search condition; multiple values are allowed and are passed as an array where "PLACEHOLDER_NAME => PLACEHOLDER_VALUE".

返回值

A CollectionFind object, or chain with execute() to return a Result object.

范例

示例 #1 mysql_xdevapi\CollectionFind::bind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find('job like :job and age > :age')
  ->bind(['job' => 'Butler', 'age' => 16])
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

CollectionFind::__construct

CollectionFind constructor

说明

private mysql_xdevapi\CollectionFind::__construct ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

范例

示例 #1 CollectionFind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find('job like :job and age > :age')
  ->bind(['job' => 'Butler', 'age' => 16])
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

CollectionFind::execute

Execute the statement

说明

public mysql_xdevapi\DocResult mysql_xdevapi\CollectionFind::execute ( void )

Execute the find operation; this functionality allows for method chaining.

参数

此函数没有参数。

返回值

A DocResult object that to either fetch results from, or to query the status of the operation.

范例

示例 #1 CollectionFind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find('job like :job and age > :age')
  ->bind(['job' => 'Butler', 'age' => 16])
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

CollectionFind::fields

Set document field filter

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::fields ( string $projection )

Defined the columns for the query to return. If not defined then all columns are used.

参数

projection
Can either be a single string or an array of string, those strings are identifying the columns that have to be returned for each document that match the search condition.

返回值

A CollectionFind object that can be used for further processing.

范例

示例 #1 mysql_xdevapi\CollectionFind::fields example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find('job like :job and age > :age')
  ->bind(['job' => 'Butler', 'age' => 16])
  ->fields('name')
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(6) "Alfred"
  }
}

CollectionFind::groupBy

Set grouping criteria

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::groupBy ( string $sort_expr )

This function can be used to group the result-set by one more columns, frequently this is used with aggregate functions like COUNT,MAX,MIN,SUM etc.

参数

sort_expr
The columns or columns that have to be used for the group operation, this can either be a single string or an array of string arguments, one for each column.

返回值

A CollectionFind that can be used for further processing

范例

示例 #1 mysql_xdevapi\CollectionFind::groupBy example

<?php

//Assuming $coll is a valid Collection object

//Extract all the documents from the Collection and group the results by the 'name' field
$res = $coll->find()->groupBy('name')->execute();

?>

CollectionFind::having

Set condition for aggregate functions

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::having ( string $sort_expr )

This function can be used after the 'field' operation in order to make a selection on the documents to extract.

参数

sort_expr
This must be a valid SQL expression, the use of aggreate functions is allowed

返回值

CollectionFind object that can be used for further processing

范例

示例 #1 mysql_xdevapi\CollectionFind::having example

<?php

//Assuming $coll is a valid Collection object

//Find all the documents for which the 'age' is greather than 40,
//Only the columns 'name' and 'age' are returned in the Result object
$res = $coll->find()->fields(['name','age'])->having('age > 40')->execute();

?>

CollectionFind::limit

Limit number of returned documents

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::limit ( integer $rows )

Set the maximum number of documents to return.

参数

rows
Maximum number of documents.

返回值

A CollectionFind object that can be used for additional processing; chain with the execute() method to return a DocResult object.

范例

示例 #1 mysql_xdevapi\CollectionFind::limit example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();
$create
  ->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
  ->execute();


// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find('job like :job and age > :age')
  ->bind(['job' => 'Butler', 'age' => 16])
  ->sort('age desc')
  ->limit(1)
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000f3"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

CollectionFind::lockExclusive

Execute operation with EXCLUSIVE LOCK

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::lockExclusive ([ integer $lock_waiting_option ] )

Lock exclusively the document, other transactions are blocked from updating the document until the document is locked While the document is locked, other transactions are blocked from updating those docs, from doing SELECT ... LOCK IN SHARE MODE, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view.

This feature is directly useful with the modify() command, to avoid concurrency problems. Basically, it serializes access to a row through row locking

参数

lock_waiting_option
Optional waiting option. By default it is MYSQLX_LOCK_DEFAULT. Valid values are these constants:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

Returns a CollectionFind object that can be used for further processing

范例

示例 #1 mysql_xdevapi\CollectionFind::lockExclusive example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$session->startTransaction();

$result = $collection
  ->find("age > 50")
  ->lockExclusive()
  ->execute();

// ... do an operation on the object

// Complete the transaction and unlock the document
$session->commit();
?>

CollectionFind::lockShared

Execute operation with SHARED LOCK

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::lockShared ([ integer $lock_waiting_option ] )

Allows to share the documents between multiple transactions which are locking in shared mode.

Other sessions can read the rows, but cannot modify them until your transaction commits.

If any of these rows were changed by another transaction that has not yet committed,

your query waits until that transaction ends and then uses the latest values.

参数

lock_waiting_option
Optional waiting option. By default it is MYSQLX_LOCK_DEFAULT. Valid values are these constants:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

A CollectionFind object that can be used for further processing

范例

示例 #1 mysql_xdevapi\CollectionFind::lockShared example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$session->startTransaction();

$result = $collection
  ->find("age > 50")
  ->lockShared()
  ->execute();

// ... read the object in shared mode

// Complete the transaction and unlock the document
$session->commit();
?>

CollectionFind::offset

Skip given number of elements to be returned

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::offset ( integer $position )

Skip (offset) these number of elements that otherwise would be returned by the find operation. Use with the limit() method.

Defining an offset larger than the result set size results in an empty set.

参数

position
Number of elements to skip for the limit() operation.

返回值

A CollectionFind object that can be used for additional processing.

范例

示例 #1 mysql_xdevapi\CollectionFind::offset example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();
$create
  ->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find()
  ->sort('age asc')
  ->offset(1)
  ->limit(1)
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000f3"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

CollectionFind::sort

Set the sorting criteria

说明

public mysql_xdevapi\CollectionFind mysql_xdevapi\CollectionFind::sort ( string $sort_expr )

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

参数

sort_expr
One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CollectionFind object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionFind::sort example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
  ->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
  ->execute();
$create
  ->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
  ->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
  ->find()
  ->sort('job desc', 'age asc')
  ->execute();

var_dump($result->fetchAll());
?>

以上例程的输出类似于:

array(2) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000106"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
  [1]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000107"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

简介

类摘要

mysql_xdevapi\CollectionModify

class mysql_xdevapi\CollectionModify implements mysql_xdevapi\Executable , mysql_xdevapi\CrudOperationBindable , mysql_xdevapi\CrudOperationLimitable , mysql_xdevapi\CrudOperationSkippable , mysql_xdevapi\CrudOperationSortable {

/* 方法 */

public mysql_xdevapi\CollectionModify arrayAppend ( string $collection_field , string $expression_or_literal )

public mysql_xdevapi\CollectionModify arrayInsert ( string $collection_field , string $expression_or_literal )

public mysql_xdevapi\CollectionModify bind ( array $placeholder_values )

public mysql_xdevapi\Result execute ( void )

public mysql_xdevapi\CollectionModify limit ( integer $rows )

public mysql_xdevapi\CollectionModify patch ( string $document )

public mysql_xdevapi\CollectionModify replace ( string $collection_field , string $expression_or_literal )

public mysql_xdevapi\CollectionModify set ( string $collection_field , string $expression_or_literal )

public mysql_xdevapi\CollectionModify skip ( integer $position )

public mysql_xdevapi\CollectionModify sort ( string $sort_expr )

public mysql_xdevapi\CollectionModify unset ( array $fields )

}

CollectionModify::arrayAppend

Append element to an array field

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::arrayAppend ( string $collection_field , string $expression_or_literal )

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayInsert(), arrayAppend() always appends the new element at the end of the array, whereas arrayInsert() can define the location.

参数

collection_field
The identifier of the field where the new element is inserted.

expression_or_literal
The new element to insert at the end of the document field array.

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionModify::arrayAppend example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name in ('Bernie', 'Jane')")
  ->arrayAppend('traits', 'Happy')
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010c
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

CollectionModify::arrayInsert

Insert element into an array field

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::arrayInsert ( string $collection_field , string $expression_or_literal )

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayAppend(), arrayInsert() allows you to specify where the new element is inserted by defining which item it is after, whereas arrayAppend() always appends the new element at the end of the array.

参数

collection_field
Identify the item in the array that the new element is inserted after. The format of this parameter is FIELD_NAME[ INDEX ] where FIELD_NAME is the name of the document field to remove the element from, and INDEX is the INDEX of the element within the field.

The INDEX field is zero based, so the leftmost item from the array has an index of 0.

expression_or_literal
The new element to insert after FIELD_NAME[ INDEX ]

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations

范例

示例 #1 mysql_xdevapi\CollectionModify::arrayInsert example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name in ('Bernie', 'Jane')")
  ->arrayInsert('traits[1]', 'Happy')
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010d
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Happy
                    [2] => Brother
                    [3] => Human
                )
        )
)

CollectionModify::bind

Bind value to query placeholder

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::bind ( array $placeholder_values )

Bind a parameter to the placeholder in the search condition of the modify operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the modify operation.

参数

placeholder_values
Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionModify::bind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name = :name")
  ->bind(['name' => 'Bernie'])
  ->arrayAppend('traits', 'Happy')
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000110
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

CollectionModify::__construct

CollectionModify constructor

说明

private mysql_xdevapi\CollectionModify::__construct ( void )

Modify (update) a collection, and is instantiated by the Collection::modify() method.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\CollectionModify::__construct example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name in ('Bernie', 'Jane')")
  ->arrayAppend('traits', 'Happy')
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010c
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

CollectionModify::execute

Execute modify operation

说明

public mysql_xdevapi\Result mysql_xdevapi\CollectionModify::execute ( void )

The execute method is required to send the CRUD operation request to the MySQL server.

参数

此函数没有参数。

返回值

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

范例

示例 #1 mysql_xdevapi\CollectionModify::execute example

<?php

/* ... */

?>

CollectionModify::limit

Limit number of modified documents

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::limit ( integer $rows )

Limit the number of documents modified by this operation. Optionally combine with skip() to define an offset value.

参数

rows
The maximum number of documents to modify.

返回值

A CollectionModify object.

范例

示例 #1 mysql_xdevapi\CollectionModify::limit example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Fred",  "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
$collection->add('{"name": "Betty", "age": 24, "job": "Teacher"}')->execute();

$collection
  ->modify("job = :job")
  ->bind(['job' => 'Teacher'])
  ->set('job', 'Principal')
  ->limit(1)
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000118
            [age] => 21
            [job] => Construction
            [name] => Fred
        )
    [1] => Array
        (
            [_id] => 00005b6b53610000000000000119
            [age] => 23
            [job] => Principal
            [name] => Wilma
        )
    [2] => Array
        (
            [_id] => 00005b6b5361000000000000011a
            [age] => 24
            [job] => Teacher
            [name] => Betty
        )
)

CollectionModify::patch

Patch document

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::patch ( string $document )

Takes a patch object and applies it on one or more documents, and can update multiple document properties.

Warning

本函数还未编写文档,仅有参数列表。

参数

document
A document with the properties to apply to the matching documents.

返回值

A CollectionModify object.

范例

示例 #1 mysql_xdevapi\CollectionModify::patch example

<?php

$res = $coll->modify('"Programmatore" IN job')->patch('{"Hobby" : "Programmare"}')->execute();

?>

CollectionModify::replace

Replace document field

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::replace ( string $collection_field , string $expression_or_literal )

Replace (update) a given field value with a new one.

参数

collection_field
The document path of the item to set.

expression_or_literal
The value to set on the specified attribute.

返回值

A CollectionModify object.

范例

示例 #1 mysql_xdevapi\CollectionModify::replace example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name = :name")
  ->bind(['name' => 'Bernie'])
  ->replace("name", "Bern")
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000011b
            [name] => Bern
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                )
        )
)

CollectionModify::set

Set document attribute

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::set ( string $collection_field , string $expression_or_literal )

Sets or updates attributes on documents in a collection.

参数

collection_field
The document path (name) of the item to set.

expression_or_literal
The value to set it to.

返回值

A CollectionModify object.

范例

示例 #1 mysql_xdevapi\CollectionModify::set example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name = :name")
  ->bind(['name' => 'Bernie'])
  ->set("name", "Bern")
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

以上例程的输出类似于:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000111
            [name] => Bern
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                )
        )
)

CollectionModify::skip

Skip elements

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::skip ( integer $position )

Skip the first N elements that would otherwise be returned by a find operation. If the number of elements skipped is larger than the size of the result set, then the find operation returns an empty set.

Warning

本函数还未编写文档,仅有参数列表。

参数

position
Number of elements to skip.

返回值

A CollectionModify object to use for further processing.

范例

示例 #1 mysql_xdevapi\CollectionModify::skip example

<?php

$coll->modify('age > :age')->sort('age desc')->unset(['age'])->bind(['age' => 20])->limit(4)->skip(1)->execute();

?>

CollectionModify::sort

Set the sorting criteria

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::sort ( string $sort_expr )

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档,仅有参数列表。

参数

sort_expr
One or more sorting expression can be provided, the evaluation of these will be from the leftmost to the rightmost, each expression must be separated by a comma.

返回值

CollectionModify object that can be used for further processing.

范例

示例 #1 mysql_xdevapi\CollectionModify::sort example

<?php

$res = $coll->modify('true')->sort('name desc', 'age asc')->limit(4)->set('Married', 'NO')->execute();

?>

CollectionModify::unset

Unset the value of document fields

说明

public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::unset ( array $fields )

Removes attributes from documents in a collection.

Warning

本函数还未编写文档,仅有参数列表。

参数

fields
The attributes to remove from documents in a collection.

返回值

CollectionModify object that can be used for further processing.

范例

示例 #1 mysql_xdevapi\CollectionModify::unset example

<?php

$res = $coll->modify('job like :job_name')->unset(["age", "name"])->bind(['job_name' => 'Plumber'])->execute();

?>

简介

类摘要

mysql_xdevapi\CollectionRemove

class mysql_xdevapi\CollectionRemove implements mysql_xdevapi\Executable , mysql_xdevapi\CrudOperationBindable , mysql_xdevapi\CrudOperationLimitable , mysql_xdevapi\CrudOperationSortable {

/* 方法 */

public mysql_xdevapi\CollectionRemove bind ( array $placeholder_values )

public mysql_xdevapi\Result execute ( void )

public mysql_xdevapi\CollectionRemove limit ( integer $rows )

public mysql_xdevapi\CollectionRemove sort ( string $sort_expr )

}

CollectionRemove::bind

Bind value to placeholder

说明

public mysql_xdevapi\CollectionRemove mysql_xdevapi\CollectionRemove::bind ( array $placeholder_values )

Bind a parameter to the placeholder in the search condition of the remove operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the remove operation.

Warning

本函数还未编写文档,仅有参数列表。

参数

placeholder_values
Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

返回值

A CollectionRemove object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionRemove::bind example

<?php

$res = $coll->remove('age > :age_from and age < :age_to')->bind(['age_from' => 20, 'age_to' => 50])->limit(7)->execute();

?>

CollectionRemove::__construct

CollectionRemove constructor

说明

private mysql_xdevapi\CollectionRemove::__construct ( void )

Remove collection documents, and is instantiated by the Collection::remove() method.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\Collection::remove example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob",    "age": 19, "job": "Painter"}')->execute();

// Remove all painters
$collection
  ->remove("job in ('Painter')")
  ->execute();

// Remove the oldest butler
$collection
  ->remove("job in ('Butler')")
  ->sort('age desc')
  ->limit(1)
  ->execute();

// Remove record with lowest age
$collection
  ->remove('true')
  ->sort('age desc')
  ->limit(1)
  ->execute();
?>

CollectionRemove::execute

Execute remove operation

说明

public mysql_xdevapi\Result mysql_xdevapi\CollectionRemove::execute ( void )

The execute function needs to be invoked in order to trigger the client to send the CRUD operation request to the server.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

Result object.

范例

示例 #1 mysql_xdevapi\CollectionRemove::execute example

<?php

$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();

?>

CollectionRemove::limit

Limit number of documents to remove

说明

public mysql_xdevapi\CollectionRemove mysql_xdevapi\CollectionRemove::limit ( integer $rows )

Sets the maximum number of documents to remove.

Warning

本函数还未编写文档,仅有参数列表。

参数

rows
The maximum number of documents to remove.

返回值

Returns a CollectionRemove object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionRemove::limit example

<?php

$res = $coll->remove('job in (\'Barista\', \'Programmatore\', \'Ballerino\', \'Programmatrice\')')->limit(5)->sort(['age desc', 'name asc'])->execute();

?>

CollectionRemove::sort

Set the sorting criteria

说明

public mysql_xdevapi\CollectionRemove mysql_xdevapi\CollectionRemove::sort ( string $sort_expr )

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档,仅有参数列表。

参数

sort_expr
One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CollectionRemove object that can be used to execute the command, or to add additional operations.

范例

示例 #1 mysql_xdevapi\CollectionRemove::sort example

<?php

$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();

?>

简介

类摘要

mysql_xdevapi\ColumnResult

class mysql_xdevapi\ColumnResult {

/* 方法 */

public string getCharacterSetName ( void )

public string getCollationName ( void )

public string getColumnLabel ( void )

public string getColumnName ( void )

public integer getFractionalDigits ( void )

public integer getLength ( void )

public string getSchemaName ( void )

public string getTableLabel ( void )

public string getTableName ( void )

public integer getType ( void )

public integer isNumberSigned ( void )

public integer isPadded ( void )

}

ColumnResult::__construct

ColumnResult constructor

说明

private mysql_xdevapi\ColumnResult::__construct ( void )

Retrieve column metadata, such as its character set; this is instantiated by the RowResult::getColumns() method.

参数

此函数没有参数。

范例

示例 #1 mysql_xdevapi\ColumnResult::__construct example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS nonsense")->execute();
$session->sql("CREATE DATABASE nonsense")->execute();
$session->sql("CREATE TABLE nonsense.numbers (hello int, world float unsigned)")->execute();
$session->sql("INSERT INTO  nonsense.numbers values (42, 42)")->execute();

$schema = $session->getSchema("nonsense");
$table  = $schema->getTable("numbers");

$result1 = $table->select('hello','world')->execute();

// Returns an array of ColumnResult objects
$columns = $result1->getColumns(); 

foreach ($columns as $column) {
    echo "\nColumn label " , $column->getColumnLabel();
    echo " is type "       , $column->getType();
    echo " and is ", ($column->isNumberSigned() === 0) ? "Unsigned." : "Signed.";
}

// Alternatively
$result2 = $session->sql("SELECT * FROM nonsense.numbers")->execute();

// Returns an array of FieldMetadata objects
print_r($result2->getColumns());

以上例程的输出类似于:

Column label hello is type 19 and is Signed.
Column label world is type 4  and is Unsigned.

Array
(
    [0] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 1
            [type_name] => SINT
            [name] => hello
            [original_name] => hello
            [table] => numbers
            [original_table] => numbers
            [schema] => nonsense
            [catalog] => def
            [collation] => 0
            [fractional_digits] => 0
            [length] => 11
            [flags] => 0
            [content_type] => 0
        )
    [1] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 6
            [type_name] => FLOAT
            [name] => world
            [original_name] => world
            [table] => numbers
            [original_table] => numbers
            [schema] => nonsense
            [catalog] => def
            [collation] => 0
            [fractional_digits] => 31
            [length] => 12
            [flags] => 1
            [content_type] => 0
        )
)

ColumnResult::getCharacterSetName

Get character set

说明

public string mysql_xdevapi\ColumnResult::getCharacterSetName ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getCharacterSetName example

<?php

/* ... */

?>

ColumnResult::getCollationName

Get collation name

说明

public string mysql_xdevapi\ColumnResult::getCollationName ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getCollationName example

<?php

/* ... */

?>

ColumnResult::getColumnLabel

Get column label

说明

public string mysql_xdevapi\ColumnResult::getColumnLabel ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getColumnLabel example

<?php

/* ... */

?>

ColumnResult::getColumnName

Get column name

说明

public string mysql_xdevapi\ColumnResult::getColumnName ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getColumnName example

<?php

/* ... */

?>

ColumnResult::getFractionalDigits

Get fractional digit length

说明

public integer mysql_xdevapi\ColumnResult::getFractionalDigits ( void )

Fetch the number of fractional digits for column.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getFractionalDigits example

<?php

/* ... */

?>

ColumnResult::getLength

Get column field length

说明

public integer mysql_xdevapi\ColumnResult::getLength ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getLength example

<?php

/* ... */

?>

ColumnResult::getSchemaName

Get schema name

说明

public string mysql_xdevapi\ColumnResult::getSchemaName ( void )

Fetch the schema name where the column is stored.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getSchemaName example

<?php

/* ... */

?>

ColumnResult::getTableLabel

Get table label

说明

public string mysql_xdevapi\ColumnResult::getTableLabel ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getTableLabel example

<?php

/* ... */

?>

ColumnResult::getTableName

Get table name

说明

public string mysql_xdevapi\ColumnResult::getTableName ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

Name of the table for the column.

范例

示例 #1 mysql_xdevapi\ColumnResult::getTableName example

<?php

/* ... */

?>

ColumnResult::getType

Get column type

说明

public integer mysql_xdevapi\ColumnResult::getType ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

范例

示例 #1 mysql_xdevapi\ColumnResult::getType example

<?php

/* ... */

?>

ColumnResult::isNumberSigned

Check if signed type

说明

public integer mysql_xdevapi\ColumnResult::isNumberSigned ( void )

Retrieve a table's column information, and is instantiated by the RowResult::getColumns() method.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

TRUE if a given column as a signed type.

范例

示例 #1 mysql_xdevapi\ColumnResult::isNumberSigned example

<?php

/* ... */

?>

ColumnResult::isPadded

Check if padded

说明

public integer mysql_xdevapi\ColumnResult::isPadded ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

TRUE if a given column is padded.

范例

示例 #1 mysql_xdevapi\ColumnResult::isPadded example

<?php

/* ... */

?>

简介

类摘要

mysql_xdevapi\CrudOperationBindable

class mysql_xdevapi\CrudOperationBindable {

/* 方法 */

abstract public mysql_xdevapi\CrudOperationBindable bind ( array $placeholder_values )

}

CrudOperationBindable::bind

Bind value to placeholder

说明

abstract public mysql_xdevapi\CrudOperationBindable mysql_xdevapi\CrudOperationBindable::bind ( array $placeholder_values )

Binds a value to a specific placeholder.

Warning

本函数还未编写文档,仅有参数列表。

参数

placeholder_values
The name of the placeholders and the values to bind.

返回值

A CrudOperationBindable object.

范例

示例 #1 mysql_xdevapi\CrudOperationBindable::bind example

<?php

$res = $coll->modify('name like :name')->arrayInsert('job[0]', 'Calciatore')->bind(['name' => 'ENTITY'])->execute();
$res = $table->delete()->orderby('age desc')->where('age < 20 and age > 12 and name != :name')->bind(['name' => 'Tierney'])->limit(2)->execute();

?>

简介

类摘要

mysql_xdevapi\CrudOperationLimitable

class mysql_xdevapi\CrudOperationLimitable {

/* 方法 */

abstract public mysql_xdevapi\CrudOperationLimitable limit ( integer $rows )

}

CrudOperationLimitable::limit

Set result limit

说明

abstract public mysql_xdevapi\CrudOperationLimitable mysql_xdevapi\CrudOperationLimitable::limit ( integer $rows )

Sets the maximum number of records or documents to return.

Warning

本函数还未编写文档,仅有参数列表。

参数

rows
The maximum number of records or documents.

返回值

A CrudOperationLimitable object.

范例

示例 #1 mysql_xdevapi\CrudOperationLimitable::limit example

<?php

$res = $coll->find()->fields(['name as n','age as a','job as j'])->groupBy('j')->limit(11)->execute();
$res = $table->update()->set('age',69)->where('age > 15 and age < 22')->limit(4)->orderby(['age asc','name desc'])->execute();

?>

简介

类摘要

mysql_xdevapi\CrudOperationSkippable

class mysql_xdevapi\CrudOperationSkippable {

/* 方法 */

abstract public mysql_xdevapi\CrudOperationSkippable skip ( integer $skip )

}

CrudOperationSkippable::skip

Number of operations to skip

说明

abstract public mysql_xdevapi\CrudOperationSkippable mysql_xdevapi\CrudOperationSkippable::skip ( integer $skip )

Skip this number of records in the returned operation.

Warning

本函数还未编写文档,仅有参数列表。

参数

skip
Number of elements to skip.

返回值

A CrudOperationSkippable object.

范例

示例 #1 mysql_xdevapi\CrudOperationSkippable::skip example

<?php

$res = $coll->find('job like \'Programmatore\'')->limit(1)->skip(3)->sort('age asc')->execute();

?>

简介

类摘要

mysql_xdevapi\CrudOperationSortable

class mysql_xdevapi\CrudOperationSortable {

/* 方法 */

abstract public mysql_xdevapi\CrudOperationSortable sort ( string $sort_expr )

}

CrudOperationSortable::sort

Sort results

说明

abstract public mysql_xdevapi\CrudOperationSortable mysql_xdevapi\CrudOperationSortable::sort ( string $sort_expr )

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档,仅有参数列表。

参数

sort_expr
One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CrudOperationSortable object.

范例

示例 #1 mysql_xdevapi\CrudOperationSortable::sort example

<?php

$res = $coll->find('job like \'Cavia\'')->sort('age desc', '_id desc')->execute();

?>

简介

类摘要

mysql_xdevapi\DatabaseObject

class mysql_xdevapi\DatabaseObject {

/* 方法 */

abstract public bool existsInDatabase ( void )

abstract public string getName ( void )

abstract public mysql_xdevapi\Session getSession ( void )

}

DatabaseObject::existsInDatabase

Check if object exists in database

说明

abstract public bool mysql_xdevapi\DatabaseObject::existsInDatabase ( void )

Verifies if the database object refers to an object that exists in the database.

参数

此函数没有参数。

返回值

Returns TRUE if object exists in the database, else FALSE if it does not.

范例

示例 #1 mysql_xdevapi\DatabaseObject::existsInDatabase example

<?php

$existInDb = $dbObj->existsInDatabase();

?>

DatabaseObject::getName

Get object name

说明

abstract public string mysql_xdevapi\DatabaseObject::getName ( void )

Fetch name of this database object.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

The name of this database object.

范例

示例 #1 mysql_xdevapi\DatabaseObject::getName example

<?php

$dbObjName = $dbObj->getName();

?>

DatabaseObject::getSession

Get session name

说明

abstract public mysql_xdevapi\Session mysql_xdevapi\DatabaseObject::getSession ( void )

Fetch session associated to the database object.

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

The Session object.

范例

示例 #1 mysql_xdevapi\DatabaseObject::getSession example

<?php

$session = $dbObj->getSession();

?>

简介

类摘要

mysql_xdevapi\DocResult

class mysql_xdevapi\DocResult implements mysql_xdevapi\BaseResult , Traversable {

/* 方法 */

public array fetchAll ( void )

public array fetchOne ( void )

public Array getWarnings ( void )

public integer getWarningsCount ( void )

}

DocResult::__construct

DocResult constructor

说明

private mysql_xdevapi\DocResult::__construct ( void )

Fetch document results and warnings, and is instantiated by CollectionFind.

参数

此函数没有参数。

范例

示例 #1 A DocResult example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name"