Php mysqlnd or php mysql

Выбор библиотеки

Модули mysqli и PDO_MySQL — всего лишь легковесные обёртки над библиотеками написанными на языке C. Эти модули могут использовать библиотеки mysqlnd и libmysqlclient . Выбор библиотеки необходимо сделать на этапе компиляции.

Библиотека mysqlnd является частью дистрибутива PHP. Она предоставляет такие возможности как ленивое соединение(lazy connections) и кеширование запросов. В библиотеке libmysqlclient данные возможности недоступны. Так что крайне рекомендуется использовать именно встроенную библиотеку mysqlnd. Для дополнительных сведений смотрите документацию mysqlnd.

Пример #1 Команды конфигурирования для mysqlnd и libmysqlclient

//Рекомендованная, компилирует с mysqlnd $ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd //Рекомендованная, компилирует с mysqlnd $ ./configure --with-mysqli --with-pdo-mysql //Не рекомендованная, компилирует с libmysqlclient $ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config

Сравнение возможностей библиотек

Рекомендуется использовать библиотеку mysqlnd, а не MySQL Client Server library (libmysqlclient). Обе библиотеки развиваются и поддерживаются производителями.

MySQL native driver (mysqlnd) MySQL client server library ( libmysqlclient )
Часть дистрибутива PHP Да Нет
Появилась в версии PHP 5.3.0 Нет данных
Лицензия PHP License 3.01 Двойная лицензия
Статус разработки Активный Активный
Жизненный цикл Окончание не анонсировано Окончание не анонсировано
Компилирование по умолчанию (для всех модулей MySQL) Да Нет
Поддержка протокола сжатия Да Да
Поддержка SSL Да Да
Поддержка именованных конвейеров (named pipes) Да Да
Неблокирующие, асинхронные запросы Да Нет
Статистика производительности Да Нет
LOAD LOCAL INFILE уважает директиву open_basedir Да нет
Использует штатный менеджер памяти PHP (т.е., ограничения памяти PHP) Да Нет
Возвращает числовые значения как значения с плавающей точкой(float) (COM_QUERY) Да нет
Возвращает числовые значения как строки (string) (COM_QUERY) Да Да
Поддержка плагинов Да Ограниченно
Автоматическое переподключение нет опционально
Читайте также:  Async без await python

User Contributed Notes

Источник

Raw bin collection of differences between mysqlnd and the MySQL Client Library (AKA libmysql)

This is a “raw bin” collection of differences between the MySQL native driver for PHP (mysqlnd) and the MySQL Client Library (AKA libmysql). If you want to do MySQL marketing a favour don’t use the term libmysql in the documentation.

A new sibling of the MySQL Client Library is the MySQL Connector/C (alternative MySQL naming: MySQL driver for C). The MySQL Connector/C is kind of a standalone version of the MySQL Client Library. Remember that the MySQL Client Library comes with the MySQL Server, unless you use your OS distribution packages. The MySQL driver for C is a spin-off from the MySQL Client Library that was shipped with MySQL 6.0.

That means user can choose between three different libraries for PHP: mysqlnd, MySQL Client Library and Connector/C. However, there are no major differences between Connector/C and the MySQL Client Library. For the sake of PHP, Connector/C = standalone version of MySQL Client Library.

mysqlnd is part of the PHP source code as of PHP 5.3. Therefore users do not need to install any MySQL libraries on their PHP build host.

Windows builds downloaded from php.net use mysqlnd as their default MySQL client library as of PHP 5.3. With PHP 5.4 the default library used with mysql, mysqli and PDO_MySQL is mysqlnd on all platforms. Using the MySQL Client Library (AKA libmysql) is still supported. There are no plans to remove libmysql support.

Major features added after PHP 5.3.0

Compression is supported since PHP 5.3.1. The MySQL compressed client/server protocol. See also, http://bugs.php.net/bug.php?id=47017

Feature and extension dependencies

Mysqlnd is tightly integrated into PHP. It is using PHP infrastructure, for example, PHP Streams. Some mysqlnd features depend on other PHP extensions:

Please make sure that you are using a PHP build with Zlib and OpenSSL support when switching from libmysql to mysqlnd. This will ensure that mysqlnd offers the same functionality as libmysql does.

Major feature differences

mysqlnd does not support:

mysqlnd only features:

security: mysqlnd can inspect LOAD LOCAL INFILE and check open_basedir setting, libmysql won’t care about open_basedir. libmysql allows accessing files which other PHP functions cannot access, if open_basedir is set

On debugging: memory usage of the MySQL Client Library and libmysql cannot be compared using memory_get_usage(). memory_get_usage() does not take memory into account allocated by the MySQL Client Library — see “Internet Super Hero” blog post.

API differences

general

ini settings

Only available with mysqlnd:

note (general, not mysqlnd specific): flag “O” vs. “o” — flush after every [disk] write yes/no -> performance

Enable the collection of various client statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), mysqli_get_cache_stats() and are shown in mysqlnd section of the output of the phpinfo() function as well. NOTE: Statistics are aggregated among all extensions that use mysqlnd. For example, when compiling both ext/mysql and ext/mysqli against mysqlnd, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out to find out how much a certain API call from any extension that uses mysqlnd has impacted a certain statistic. You can configure the MySQL driver for PDO, ext/mysql and ext/mysqli to optionally use mysqlnd. When doing so, all three extensions will change the statistics. Note also the difference between global and connection statistics explained in the blog postings.

Enable the collection of various memory statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), mysqli_get_cache_stats() and are shown in mysqlnd section of the output of the phpinfo() function as well.

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (“normal” query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields() and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists — it should happen rarely.

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

(The default change may/should make it into 5.31 — lets wait and see what the release manager decides)

The value can also be set using mysqli_option(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size)

Maximum read chunk size in bytes when reading the body of a MySQL command packet. The MySQL client server protocol encapsulated all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. mysqlnd reads the body in chunks of MIN(header.size, mysqlnd.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call read() multiple times.

The value can also be set using mysqli_optionS(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size)

. we have never done any proper performance testing around this. Larger values force PHP streams to allocate larger buffers and we have to doo less read calls. On the other hand might the transport protocol (TCP or Unix Sockets) in use work even better with smaller buffers. but it should also depend on your SQL queries: do you have queries that generate result sets larger than mysqlnd.net_read_buffer_size . No idea for a recommendation but “run your own tests and don’t be disappointed if it makes no big difference”.

No meaning for a standard PHP binary, see http://blog.ulf-wendel.de/?p=272 . Bug in PHP 5.3.0: the default of 0 has disabled the update of the mysqlnd statistics “no_index_used”, “bad_index_used”, “slow_query”. As of PHP 5.3.1 — if the patch makes it into 5.3.1 — the log mask does no longer impact collecting statistics.

ext/mysqli

Constants

In general mysqlnd exports everything exported by ext/mysqli when using MySQL Client Library 5.0.8 or newer.

Only available with mysqlnd:

Источник

GizmoLA.com

So you are installing a modern version of php using one of the alternative repositories, and suddenly you are confronted with a confusing choice. You want support for mysql (mysqli or PDO-mysql) in your php program. But which one to choose?

First off, you should probably be using PDO. It’s just a cleaner database interface when compared to mysqli, and also tends to be the supported option if you’re using an ORM like Doctrine2.

But you probably have found that installing the PDO package doesn’t get you support for MySQL.

So what are these 2 packages? Well let’s see what yum under Centos shows us, once we’ve setup webtatic as a repo:

* webtatic: us-east.repo.webtatic.com
==============================================
php56w-mysql.x86_64 : A module for PHP applications that use MySQL databases
php56w-mysqlnd.x86_64 : A module for PHP applications that use MySQL databases

In short, the mysql extension aka the mysql library is to quote Oracle/mysql

This was the original php approach to supporting mysql. MySQL provided a client api library, and using that c library, a php extension was created that depends upon libmysql implementing the famous mysql_ functions that allowed php to talk to mysql.

The mysqlnd package (where nd stands for «native driver») is the fruit of a project to make mysql work optimally in the php language. Again to quote the mysql site:

The mysqlnd library is highly optimized for and tightly integrated into PHP. The MySQL Client Library cannot offer the same optimizations because it is a general-purpose client library.

The mysqlnd library is using PHP internal C infrastructure for seamless integration into PHP. In addition, it is using PHP memory management, PHP Streams (I/O abstraction) and PHP string handling routines. The use of PHP memory management by mysqlnd allows, for example, memory savings by using read-only variables (copy on write) and makes mysqlnd apply to PHP memory limits.

On top of these benefits are a number of interesting enhancements and support for plugins that might be of specific interest to you as a developer or sysadmin.

In general nothing should break in your code as the api should work the same under mysqlnd as it did with the old mysql library.

In summary, you want to use mysqlnd now and in the future.

Источник

Оцените статью