|
|
XCVII. Расширение MySQL (Improved)
Расширение mysqli позволяет вам получить доступ к функциональности, которую предоставляет
MySQL версии 4.1 и выше. Больше информации о сервере баз данных MySQL
вы можете получить по адресу http://www.mysql.com/.
Документация MySQL находится по адресу http://dev.mysql.com/doc/.
Некоторые части данной документации включены из руководства по MySQL с разрешения MySQL AB.
Чтобы эти функции были доступны, PHP должен быть собран с поддержкой расширения mysqli.
Замечание:
Расширение mysqli разработано для работы с MySQL версии 4.1.3 и выше.
Для работы с более старыми версиями, обратитесь к документации к расширению
MySQL.
Для установки расширения mysqli для PHP, используйте конфигурационную директиву
--with-mysqli=mysql_config_path/mysql_config,
гдеmysql_config_path -
путь к утилите mysql_config, которая поставляется
с MySQL версии 4.1 и больше.
Если вы хотите установить расширение mysql вместе с mysqli,
вы должны использовать одинаковые клиентские библиотеки во избежание
возможных конфликтов.
Поведение этих функций зависит от установок в php.ini.
Таблица 1. MySQLi Параметры конфигурации | Имя | Значение по-умолчанию | Область изменения | История изменений |
|---|
| mysqli.max_links | "-1" | PHP_INI_SYSTEM | Доступен начиная с PHP 5.0.0. | | mysqli.default_port | "3306" | PHP_INI_ALL | Доступен начиная с PHP 5.0.0. | | mysqli.default_socket | NULL | PHP_INI_ALL | Доступен начиная с 5.0.0. | | mysqli.default_host | NULL | PHP_INI_ALL | Доступен начиная с PHP 5.0.0. | | mysqli.default_user | NULL | PHP_INI_ALL | Доступен начиная с PHP 5.0.0. | | mysqli.default_pw | NULL | PHP_INI_ALL | Доступен начиная с PHP 5.0.0. |
Дальнейшие детали и определения PHP_INI_* констант смотрите в разделе
конфигурационные изменения.
Краткое разъяснение конфигурационных
директив.
mysqli.max_links
integer
Максимальное число соединений MySQL на процесс.
mysqli.default_port
string
TCP порт, используемый по умолчанию для соединения с сервером баз данных
если другое значение явно не указано. Если значение по умолчанию не
указано, оно будет получено из переменной среды окружения
MYSQL_TCP_PORT, директивы mysql-tcp
в файле /etc/services или константы
MYSQL_PORT, которая задаётся во время компиляции, в
указанном порядке. Win32 использует только константу
MYSQL_PORT.
mysqli.default_socket
string
Имя сокета по умолчанию, которое используется для соединения с локальной
базой данных если имя сокета было не указано явно.
mysqli.default_host
string
Имя сервера, которое используется если имя не было указано явно.
Это имя не используется в безопасном режиме.
mysqli.default_user
string
Имя пользователя по умолчанию, используемое если имя не было указано
явно. Игнорируется в безопасном режиме.
mysqli.default_pw
string
Пароль по умолчанию, используемый если пароль не был явно указан.
Игнорируется в безопасном режиме.
Представляет соединение между PHP и базой данных MySQL.
autocommit -
включает или выключает автофиксацию изменений базы данных change_user -
изменение пользователя для выбранного соединения с базой данных character_set_name
- возвращает кодировку по-умолчанию (default character set) для
соединения с базой данных close - закрывает
открытое ранее соединение commit - фиксирует
текущую транзакцию connect -
открывает новое соединение с сервером баз данных MySQL debug - выполняет
операции по отладке dump_debug_info -
возвращает отладочную информацию get_client_info -
возвращает версию клиента get_host_info -
возвращает используемый тип соединения get_server_info -
возвращает информацию о сервере MySQL get_server_version
- возвращает версию сервера MySQL init -
инициализирует объект mysqli info - получает
информацию о последнем выполненном запросе kill - требует от
сервера убить mysql-поток multi_query -
выполняет множественный запрос more_results
- проверяет наличие дополнительных результатов в выполняемом
мульти-запросе next_result -
получает следующий результат в выполняемом мульти-запросе options -
устанавливает опции ping - проверяет
соединение с сервером или переподключается, если соединение недоступно prepare -
подготавливает SQL-запрос query - выполняет
запрос real_connect
- создает соединение с сервером MySQL escape_string -
экранирует спецсимволы в строке для использования в SQL-выражениях rollback - откат
текущей транзакции select_db -
выбирает базу данных по-умолчанию set_charset -
устанавливает кодировку клиента по-умолчанию ssl_set -
устанавливает параметры ssl stat - получает
текущее состояние системы stmt_init -
инициализирует выражение для использования с mysqli_stmt_prepare store_result
- получает набор данных от последнего запроса thread_safe -
возвращает информацию о том, собран ли клиент с поддеркой надежных
потоков use_result -
получает небуферизованный набор данных из последнего запроса
affected_rows -
получает количество затронутых рядов предыдущей MySQL-операцией client_info -
возвращает версию MySQL-клиента в виде строки client_version -
возвращает версию MySQL-клиента в целочисленном виде errno - возвращает
номер ошибки для последнего вызова функции error - возвращает
строку, содержащую текст ошибки для последнего вызова функции field_count -
возвращает количество колонок в последней выборке host_info -
возвращает строку с представлением используемого типа соединения info - возвращает
информацию о последнем выполненном запросе insert_id -
возвращает автоматически созданный id, использованый в последнем
запросе protocol_version -
возвращает версию использованного протокола MySQL server_info - возвращает строку, которая содержит номер версии сервера server_version - возвращает целочисленный номер версии сервера sqlstate -
возвращает строку, содержащую код ошибки SQLSTATE для последней ошибки thread_id -
возвращает ID потока для текущего соединения warning_count -
возвращает количество предупреждений (warnings), сгенерированных во
время выполнения последнего SQL-выражения
Представляет подготовленное выражение.
bind_param -
присваивает переменные подготовленному выражению bind_result -
присваивает переменные подготовленному выражению для хранилища
результатов close -
закрывает подготовленное выражение data_seek
- переходит на произвольную строку в наборе данных выражения execute -
выполняет подготовленное выражение fetch -
получает результат из подготовленного выражения в связанные
переменные free_result -
освобождает занятую результатом память для переданного дескриптора
выражения prepare -
подготавливает SQL-запрос reset -
сбрасывает подготовленное выражение result_metadata
- получает набор данных из подготовленного выражения для получения
метаинформации send_long_data
- отправляет информацию на сервер по частям store_result -
полностью буферизирует набор данных из подготовленного запроса
affected_rows -
возвращает количество затронутых в результате последнего выполнения
выражения рядов errno -
возвращает код ошибки для последнего выполненного выражения error -
возвращает текст ошибки для последнего выполненного выражения field_count -
возвращает количество полей в результате запроса id - возвращает идентификатор выражения insert_id -
возвращает значение, созданное подготовленным выражением поля с
AUTO_INCREMENT num_rows -
возвращает количество рядов в результате запроса param_count -
возвращает количество параметров для переданного подготовленного
выражения sqlstate -
возвращает строку, содержащую код ошибки SQLSTATE для последнего
вызова выражения
Представляет набор данных, полученныйх в результате запроса к базе данных.
close -
закрывает набор данных data_seek -
передвигает внутренний указатель результата fetch_array -
получает ряд из набора данных в виде ассоциативного массива,
нумерованного массива, или обоих fetch_assoc -
получает ряд из набора данных в виде ассоциативного массива fetch_field -
получает информацию о столбце из набора данных fetch_fields
- получает информацию о всех столбцах из набора данных fetch_field_direct
- получает информацию об определенном столбце fetch_object
- получает ряд из набора данных в виде объекта fetch_row -
получает ряд из набора данных в виде нумерованного массива field_seek -
установить указатель на результат смещенным на определенное
количество полей free_result -
освобождает память, занимаемую результатом запроса
current_field
- возвращает смещение текущего указателя field_count -
возвращает количество полей в наборе данных lengths -
возвращает массив значений длины столбцов num_rows -
возвращает количество рядов в наборе данных type - возвращает MYSQLI_STORE_RESULT или
MYSQLI_USE_RESULT
Таблица 2. Константы MySQLi | Имя | Описание |
|---|
|
MYSQLI_READ_DEFAULT_GROUP
(integer)
|
Читать опции из указанной группы в файле `my.cnf' или файле указанном
с помощью MYSQLI_READ_DEFAULT_FILE
| |
MYSQLI_READ_DEFAULT_FILE
(integer)
|
Читать опции из указанного файла вместо my.cnf
| |
MYSQLI_OPT_CONNECT_TIMEOUT
(integer)
|
Тайм-аут подключения в секундах.
| |
MYSQLI_OPT_LOCAL_INFILE
(integer)
|
Включает команду LOAD LOCAL INFILE.
| |
MYSQLI_INIT_COMMAND
(integer)
|
Команда, которая будет выполнена при подключении к серверу MySQL.
Эта команда будет повторно вызвана при переподключении.
| |
MYSQLI_CLIENT_SSL
(integer)
|
Использовать SSL (шифрованый протокол). Эта опция не может быть уставовлена приложениями;
она устанавливается внутри библиотеки клиента MySQL.
| |
MYSQLI_CLIENT_COMPRESS
(integer)
|
Использовать компрессию.
| |
MYSQLI_CLIENT_INTERACTIVE
(integer)
|
Ждать interactive_timeout секунд (вместо
wait_timeout) бездействия перед закрытием
соединения. Переменная сессии клиента wait_timeout
будет установлена в значение переменной сессии
interactive_timeout.
| |
MYSQLI_CLIENT_IGNORE_SPACE
(integer)
|
Разрешить пробелы после имен функций. Делает все имена функций зарезервированными словами.
| |
MYSQLI_CLIENT_NO_SCHEMA
(integer)
|
Запретить синтаксис db_name.tbl_name.col_name.
| |
MYSQLI_CLIENT_MULTI_QUERIES
(integer)
| | |
MYSQLI_STORE_RESULT
(integer)
|
Для использования буферизации наборов данных.
| |
MYSQLI_USE_RESULT
(integer)
|
Для использования небуферизированных наборов данных.
| |
MYSQLI_ASSOC
(integer)
|
Результат возвращается в виде ассоциативного массива с именами полей в
качестве индексов.
| |
MYSQLI_NUM
(integer)
|
Результат возвращается в виде индексного массива.
| |
MYSQLI_BOTH
(integer)
|
Результат возвращается в виде массива, который содержит как числовой,
так ассоциативный (с именами полей) индексы.
| |
MYSQLI_NOT_NULL_FLAG
(integer)
|
Информирует о том, что поле определено как NOT NULL.
| |
MYSQLI_PRI_KEY_FLAG
(integer)
|
Поле является частью первичного индекса.
| |
MYSQLI_UNIQUE_KEY_FLAG
(integer)
|
Поле является частью уникального индекса.
| |
MYSQLI_MULTIPLE_KEY_FLAG
(integer)
|
Поле является частью индекса.
| |
MYSQLI_BLOB_FLAG
(integer)
| Поле определено как BLOB. | |
MYSQLI_UNSIGNED_FLAG
(integer)
| Поле определено как UNSIGNED. | |
MYSQLI_ZEROFILL_FLAG
(integer)
| Поле определено как ZEROFILL. | |
MYSQLI_AUTO_INCREMENT_FLAG
(integer)
| Поле определено как AUTO_INCREMENT. | |
MYSQLI_TIMESTAMP_FLAG
(integer)
| Поле определено как TIMESTAMP. | |
MYSQLI_SET_FLAG
(integer)
| Поле определено как SET. | |
MYSQLI_NUM_FLAG
(integer)
| Поле определено как NUMERIC. | |
MYSQLI_PART_KEY_FLAG
(integer)
| Поле является честью мультииндекса. | |
MYSQLI_GROUP_FLAG
(integer)
| Поле является частью GROUP BY. | |
MYSQLI_TYPE_DECIMAL
(integer)
| Поле определено как DECIMAL. | |
MYSQLI_TYPE_NEWDECIMAL
(integer)
| Математическая точность полей DECIMAL или
NUMERIC (MySQL 5.0.3 и выше). | |
MYSQLI_TYPE_BIT
(integer)
| Поле определено как BIT (MySQL 5.0.3 и выше). | |
MYSQLI_TYPE_TINY
(integer)
| Поле определено как TINYINT. | |
MYSQLI_TYPE_SHORT
(integer)
| Поле определено как INT. | |
MYSQLI_TYPE_LONG
(integer)
| Поле определено как INT. | |
MYSQLI_TYPE_FLOAT
(integer)
| Поле определено как FLOAT. | |
MYSQLI_TYPE_DOUBLE
(integer)
| Поле определено как DOUBLE. | |
MYSQLI_TYPE_NULL
(integer)
| Поле определено как DEFAULT NULL. | |
MYSQLI_TYPE_TIMESTAMP
(integer)
| Поле определено как TIMESTAMP. | |
MYSQLI_TYPE_LONGLONG
(integer)
| Поле определено как BIGINT. | |
MYSQLI_TYPE_INT24
(integer)
| Поле определено как MEDIUMINT. | |
MYSQLI_TYPE_DATE
(integer)
| Поле определено как DATE. | |
MYSQLI_TYPE_TIME
(integer)
| Поле определено как TIME. | |
MYSQLI_TYPE_DATETIME
(integer)
| Поле определено как DATETIME. | |
MYSQLI_TYPE_YEAR
(integer)
| Поле определено как YEAR. | |
MYSQLI_TYPE_NEWDATE
(integer)
| Поле определено как DATE. | |
MYSQLI_TYPE_ENUM
(integer)
| Поле определено как ENUM. | |
MYSQLI_TYPE_SET
(integer)
| Поле определено как SET. | |
MYSQLI_TYPE_TINY_BLOB
(integer)
| Поле определено как TINYBLOB. | |
MYSQLI_TYPE_MEDIUM_BLOB
(integer)
| Поле определено как MEDIUMBLOB. | |
MYSQLI_TYPE_LONG_BLOB
(integer)
| Поле определено как LONGBLOB. | |
MYSQLI_TYPE_BLOB
(integer)
| Поле определено как BLOB. | |
MYSQLI_TYPE_VAR_STRING
(integer)
| Поле определено как VARCHAR. | |
MYSQLI_TYPE_STRING
(integer)
| Поле определено как CHAR. | |
MYSQLI_TYPE_GEOMETRY
(integer)
| Поле определено как GEOMETRY. | |
MYSQLI_NEED_DATA
(integer)
| Имеются еще данные, доступные для связанных переменных. | |
MYSQLI_NO_DATA
(integer)
| Больше нет доступных данных для связанных переменных. | |
MYSQLI_DATA_TRUNCATED
(integer)
|
Произошло урезание данных. Доступно начиная с PHP 5.1.0 и MySQL 5.0.5.
|
add a note
User Contributed Notes
Расширение MySQL (Improved)
kenashkov at gmail dot com
05-Oct-2007 06:00
It seems that the mysqli class is overloaded.
get_class_vars(mysqli) returns nothing.
__set() and __get() are overloaded, but __isset() it not!!!
This means that the code:
<?
$mysqli_object = new mysqli();
if(isset($mysqli_object->client_info))
{
print $mysqli_object->client_info;
}
?>
will not print anything.
The workaround is:
<?
if($mysqli_object->client_info!==null)
{
print $mysqli_object->client_info;
}
?>
marcus at synchromedia dot co dot uk
03-Oct-2007 09:27
For those having trouble getting MySQLi to work, there is another way that is set to become much more common:
http://dev.mysql.com/downloads/connector/php-mysqlnd/
This is the new MySQL native driver which has been backported from PHP6 and replaces MySQLi with a version that doesn't require any local MySQL client libraries or binaries.
smurf at smurf dot noris dot de
03-Jul-2007 05:45
Yay. No more persistent connections. I am NOT happy about that.
As soon as you get more than 250 requests per second (ever been slashdotted?) there will not be any more free TCP ports for talking to the database server, because each TCP port will be kept in TIME_WAIT for two minutes and there are only 30000 ports in the local range.
And that's not the only problem. There's also more than twice the packet rate on the network link to the database. Frankly I'd like my CPUs to spend their cycles on something producive. :-/
dan+php dot net-note-about-mysqli at obluda dot cz
27-Sep-2006 02:15
Hints for upgrading PHP code from MySQL to MySQLi:
Note - MySQLi doesn't support persistent connection. If you need it, you must implement it by self. This case is not covered in this note.
First - change all occurences of MYSQL_ to MYSQLI_ and mysql_ to mysqli_
Most of changes is required because mysqli* functions has no implicit link argument, so it need to be added explicitly if not present already. Even if it is present, most mysqli_ functions require 'link' argument as first (and mandatory) argument instead of last (and optional) as required by mysql_ functions. So, we need to change order of arguments at least.
So, you need to found names of all mysql_ functions used in your code, check if it need reoder of parameters or add the link parameter. Only *_connect() functions need review, but most scripts contain only few connect call.
If you use functions deprecated in mysql, then may not be impemented in mysqli. Those need to be reimplemented if required. In most case, it's very simple. In advance, PHP script written by carefull programer should not contain deprecated calls, so it's not problem in most cases at all.
Most of scripts I ported from mysql_ to mysqli_ can be converted by simple sed script followed by *_connect() function call review only. Especially when when programmer doesn't used the link as implicit argument and doesn't use deprecated functions the conversion of PHP source is trivial task and converted script work with no problem.
Special handling of some functions:
mysql_connect(),mysql_pconnect()
-----------------------------------------
Call with 3 or less parameters need not to be modified.
4-parameters call - delete 4th parameter as mysqli is always non-persistent
5-parameters - replace it by sequence of mysqli_init();mysqli_options();mysqli_real_connect()
mysql_create_db(), mysql_drop_db(), mysql_list_dbs(), mysql_db_name(),mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_db_query(),mysql_table_name()
------------------------------------------
mysqli variant doesn't exist (those functions has been deprecated even in mysql_) but it's easy to reimplement each of it. Use apropropriate SQL command followed by standard loop for processing query results where applicable. If no connection to server yet you need to use explicit mysqli_connect call.
mysql_result()
-----------------
mysqli variant doesn't exist. Use one of mysqli_fetch_* variant (depending of type of mysql_result() third argument)
mysql_unbuffered_query()
-----------------
mysqli variant doesn't exist. Use mysqli_real_query()
chris <at> gerlt.net
07-Jul-2006 11:47
For installing mysqli extension after PHP is installed on a Linux ubuntu ( or other linux distro with apt-get such as debian, etc...):
# apt-get install php5-mysqli
NOTE: after install, you need to reboot apache
# apache2ctl graceful
Docey
08-Jun-2006 11:11
It should be noticed that mysqli does not support persistent
connections, so do not bother about implementing them
unless you got a million hits an hour on your website.
also about using both mysql and mysqli, i want to note
that under windows the best approach is to load either
mysql or mysqli at runtime not both.
i know that under php5 this is deprecated but it seems
to work fine. i used the same appoach under debian-linux
and seems to work aswell. just don't know for the
speed cost. maybe someone can benchmark this out.
just my 2 eurocents.
kronicade@yahoo
09-Mar-2006 11:42
Same problem, no solution. I'm running Solaris sparc with mysql 4.1.12. I've tried every config command I can think of and have modified my PATH as follows:
setenv PATH /usr/ccs/bin:
/usr/local/bin:
/usr/local/ipw/bin:
/usr/local/ipw/contrib/bin:
/sbin:/usr/sbin:
/usr/bin:
/usr/bin/X11:
/usr/ucb:
/usr/openwin/bin
./configure '--prefix=/usr/local/php' '--localstatedir=/usr/local' '--mandir=/usr/share/man' '--with-mysqli=/usr/local/mysql/bin/mysql_config' '--includedir=/usr/lib' '--enable-shared=max' '--enable-module=most' '--with-imap=/usr/local/imap' '--with-imap-ssl=/usr/local/ssl' '--with-apxs2=/usr/local/apache2/bin/apxs' '--enable-fastcgi' '--enable-mbstring=all' '--with-zlib-dir=/usr' '--with-openssl=/usr/local/ssl'
I think it's a compatibility issue with the version of mysql running 64-bit.
-Andrew
Michael <mstclaire at myprintflow dot com>
12-Jan-2006 07:10
I was running into some random issues using the myqli extension with MySQL 5 on Mac OS X.
I discovered that when I compiled php 5 with the --with-mysqli flag, it was building php with the pre-installed MySQL 4 client libraries.
Heres how it fixed it to build php with the correct MySQL client libraries.
----------------
I had installed the binary version of MySQL 5 from MySQL AB. It installs everything in the default location /usr/local/mysql, which is fine. The MySQL version that comes with OS X ( v.4.x, depends on your OS X version ) installs the mysql_config help utility at /usr/bin/mysql_config. When php configs, it uses that one by default, inheritently using the wrong MySQL client libs.
No problem I thought, I just changed the --with-mysqli flag to --with-mysqli=/usr/local/mysql/bin/mysql_config ( or sudo find / -name mysql_config to find yours ). Nope, php throws a build error because it can't find the matching libraries. Hmmm...
So i tested /usr/local/mysql/bin/mysql_config --version, and I am shown my most current MySQL install. The problem is that the binary editions for OS X DO NOT include the shared libs ( libmysqlclient.dylib ). Oh no, I did not want to compile MySQL myself, not because I don't know how, but because MySQL AB does not recommend it, and for good reasons. Trust me, I've found out the hard way.
So what do you do? Download the source version of MySQL 5 that matches my binary version.
Configure MySQL:
./configure --enable-shared ( it's listed as ON as default, but I want to be sure )
Build MySQL:
make ( requires Developer Tools, but you knew that )
DO NOT make install !!! I repeat, DO NOT make install unless you really wish to overwrite your binary verions, which is not a good idea. ( You can configure MySQL with the --without-server flag, but I want to be certain I don't mess up )
Ok, almost done. Go to the lib directory in your MySQL build location and go to the invisible directory, .libs . There you will find your shared libraries, namely libmysqlclient.15.0.0.dylib.
Copy this to your /usr/local/mysql/lib directory. Now do the following from the lib directory:
ln -s libmysqlclient.15.0.0.dylib libmysqlclient.15.dylib
ln -s libmysqlclient.15.0.0.dylib libmysqlclient.dylib
mkdir mysql
cd mysql
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.15.0.0.dylib
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.15.dylib
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.dylib
Now you can build your php with the correct library. After you build, check your phpinfo(); to validate the client version under the mysqli section. When I restarted Apache, it originally couldn't find my libraries, thus the /usr/local/mysql/lib/mysql directory.
Hope this helped.
Brad Marsh
09-Nov-2005 07:54
Notes for FreeBSD 6.0-RELEASE
MySQL 5.0.15 (source), Apache 2.0.55 (port), PHP 5.0.15 (source) - I used sources for MySQL and PHP because I could not get it all to work together using only ports.
First MySQL:
==================================
cd /usr/local/src
tar zxvf /path/to/mysql-5.0.15.tar.gz
./configure --prefix=/usr/local/mysql --localstatedir=/usr/local/mysql/data --enable-assembler --with-mysqld-ldflags=-all-static CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti"
make
make install
Apache:
==================================
MAKE SURE YOUR PORTS ARE UP-TO-DATE - use cvsup
cd /usr/ports/www/apache2
make
make install
make clean
PHP:
==================================
cd /usr/local/src
tar zxvf /path/to/php-5.0.5.tar.gz
./configure --with-xml --with-zlib --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-apxs2=/usr/local/sbin/apxs
EXTRA STEP for mysql and mysqli extensions at the same time:
See this forum thread: http://www.kofler.cc/forum/forumthread.php?rootID=3571
In the PHP Makefile, I changed the line (note all the duplicates)
EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lm -lxml2 -lz -liconv -lm -lxml2 -lz -liconv -lm -lmysqlclient -lz -lcrypt -lm -lxml2 -lz -liconv -lm -lcrypt -lxml2 -lz -liconv -lm -lcrypt
to
EXTRA_LIBS = -lcrypt -lmysqlclient -lz -lm -lxml2 -liconv
make
make install
Hope this helps somebody...
dgbaley27 at comcast dot net
28-Oct-2005 01:06
I wrote the following mysqli extension to make it a little easier to pull data for some peope. It combines the query() and fetch_assoc() methods:
<?
class Sql extends mysqli {
function __construct($host, $user, $password, $table) {
parent::__construct($host, $user, $password, $table);
}
function data($SQL, $force=0) {
static $holdQuery;
static $result;
if ($SQL != $holdQuery) {
$result = $this->query($SQL);
$holdQuery = $SQL;
}
return $result->fetch_assoc();
}
}
?>
So to implement:
<?
$link = new Sql("host", "user", "password", "table");
$SQL = "SELECT * FROM anyTable";
while ($row = $link->data($SQL)) {
// manipulate data
}
?>
This can be very much expanded upon but I'm a freak for minimal code and I'm sure there are pleanty of you out there like me.
Ezbakhe Yassin <yassin88 at gmail dot com>
31-Aug-2005 04:03
I made a simple class that extends mysqli. It has the following features:
- Use an XML file to store multiple connection parameters.
- Auto display DB error messages (you can easily disable this in a production server)
- Retrieve columns max lenght
- Retrieve column comments
- Retrieve ENUM|SET possible values as an array
You are free to extend/modify it, but please give me credit.
<?php
class mysqli2 extends mysqli
{
private $dbHost, $dbUser, $dbPassword, $dbSchema;
public function __construct($XMLFilePath, $connectionID)
{
$this->_getDBParameters($XMLFilePath, $connectionID);
@parent::__construct($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbSchema);
if (mysqli_connect_errno())
{
die(sprintf("Can't connect to database. Error: %s", mysqli_connect_error()));
}
}
public function __destruct()
{
if (!mysqli_connect_errno())
{
$this->close();
}
}
private function _getDBParameters($XMLFilePath, $connectionID)
{
if (!(file_exists($XMLFilePath)))
{
return FALSE;
}
$connections = simplexml_load_file($XMLFilePath);
foreach ($connections as $connection)
{
if ($connection['ID'] == $connectionID)
{
$this->dbHost = $connection->dbHost;
$this->dbUser = $connection->dbUser;
$this->dbPassword = $connection->dbPassword;
$this->dbSchema = $connection->dbSchema;
}
}
}
public function query($sql)
{
if (!($result = parent::query($sql)))
{
die(sprintf("Can't perform query on database. Error: %s", $this->error));
}
return $result;
}
public function get_columns_max_len($dbTable)
{
if (!($result = $this->query("DESCRIBE $dbTable")))
{
return FALSE;
}
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
if (ereg('^.+\((.+)\)', $row['Type'], $columnMaxLen))
{
$columnMaxLens[$row['Field']] = (int)$columnMaxLen[1];
}
}
return $columnMaxLens;
}
public function get_columns_comments($dbTable)
{
if (!($result = $this->query("SHOW CREATE TABLE $dbTable")))
{
return FALSE;
}
$row = $result->fetch_row();
$tableSQL = explode("\n", $row[1]);
foreach ($tableSQL as $tableSQLLine)
{
if (ereg(".+ `(.+)` .+ COMMENT '(.+)'", $tableSQLLine, $columnCommentsBuffer))
{
$columnComments[$columnCommentsBuffer[1]] = $columnCommentsBuffer[2];
}
}
return $columnComments;
}
public function get_enum_options($dbTable, $dbColumn)
{
if (!($result = $this->query("DESCRIBE $dbTable")))
{
return FALSE;
}
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
if ($row['Field'] == $dbColumn)
{
if (eregi('(enum|set)\((.+)\)', $row['Type'], $enumValues))
{
$enumValues = explode(",", str_replace("'", NULL, $enumValues[2]));
}
}
}
return isset($enumValues) ? $enumValues : FALSE;
}
}
?>
The XML file looks like:
<?xml version ='1.0' encoding ='UTF-8' ?>
<connections>
<connection ID="1">
<dbHost>*DATA*</dbHost>
<dbUser>*DATA*</dbUser>
<dbPassword>*DATA*</dbPassword>
<dbSchema>*DATA*</dbSchema>
</connection>
</connections>
arjen at mysql dot com
04-Aug-2005 01:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.
The script is at:
http://www.coggeshall.org/oss/mysql2i/
hans at lintoo dot dk
22-Mar-2005 08:33
While writing a class that extends mysqli I ran across some rather strange bugs,
that however did resove itself, when I found out that they were caused by:
<?php
parent::__construct( ... ... ... $this->dbase_password);
?>
so I changed it to the following:
<?php
class DBase extends mysqli {
protected $dbase_hostname;
protected $dbase_username;
protected $dbase_password;
protected $dbase_name;
public function __construct(File $settings_ini_file) {
$ini_array = parse_ini_file($settings_ini_file->requireFilePath());
$this->dbase_hostname = $ini_array["dbase_hostname"];
$this->dbase_username = $ini_array["dbase_username"];
$this->dbase_password = $ini_array["dbase_password"];
$this->dbase_name = $ini_array["dbase_name"];
parent::__construct(
$ini_array["dbase_hostname"],
$ini_array["dbase_username"],
$ini_array["dbase_password"],
$ini_array["dbase_name"]);
if (mysqli_connect_error()) {
throw new Exception("Connect exception:\n".mysqli_connect_error());
}
}
public function __destruct() {
parent::__destruct();
parent::close($this);
}
public function getName() {
return $this->dbase_name;
}
public function query($query) {
$result = parent::query($query);
if (mysqli_error($this))
throw new Exception("Query exception:\n".mysqli_error($this));
return $result;
}
}
?>
btw the File class is my own as well... couldn't find any File object in PHP5 ? :S
They are both avaible for download at:
http://www.lintoo.dk/public/dbase_and_file_class.zip
Hans Duedal // hans@lintoo.dk
jedifreeman at comcast dot net
21-Mar-2005 01:49
It should be noted here that mysqli is a PHP 5 only extension.
Andrei Nazarenko
22-Feb-2005 11:21
If you are having trouble compiling PHP5 with MySQLi support on Linux and getting a message:
"configure: error: wrong mysql library version or lib not found"
and the config.log shows an error about -lnss_files being not found, here is the solution:
edit your mysql_config file and *REMOVE* all "-lnss_files" AND "-lnss_dns" entries from it.
After that PHP should not complain anymore.
neil
10-Feb-2005 02:15
I have spent far too much time finding this answer:
Since PHP5 many many people are having installation problems. I found many apps were broken when I upgraded to version 5. I tried to install mysql and mysqli and had problems.
Here's the solution:
After doing:
./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config
do this:
"
if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"
then you can:
make
make install
......
Please note: the mysql-dev must be installed or you won't have a mysql_config anywhere. I installed the mysql-dev rpm
Further note: the information about the Makefile's duplicate instances of "-libmysqlclient" came from Michael Kofler. Thanks should be directed to him. He gives more details at the following link:
http://www.kofler.cc/forum/forumthread.php?rootID=3571
php at arwin dot net
02-Feb-2005 03:32
For those having trouble compiling with both --with-mysql AND --with-mysqli, I found a solution at this URL:
http://bugs.php.net/bug.php?id=29860&edit=1
rjanson at msn dot com writes:
OK, finally an answer!
I checked Makefile and found the following line:
EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lpng -lz -lz -lresolv -lm
-ldl -lnsl -lxml2 -
lz -lm -lxml2 -lz -lm -lmysqlclient -lcrypt -lnsl -lm -lz -lnss_files
-lnss_dns -lresolv -lnss_files
-lnss_dns -lresolv -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt
By removing one of the -lmysqlclient entries on this line I was able to
successfully make and make install with both mysql and mysqli. As
confirmed by phpInfo().
I'm not sure why the other libs have multiple entries and don't cause
make to crash.
Yair Lapin
10-Nov-2004 07:28
I successed to install php support for a mysql 4.1.7 database after several attempts because the instructions are not clear.
I have a server with linux SuSe 9 enterprise with apache 1.3.31. I installed mysql from rpm files, i installed php 4.3.9 as dynamic library. this version database needs its own client library else the mysql functions in php will not work.
configuration must be as following:
./configure --with-msqli=/usr/bin/mysql_config --with-mysql=/usr --with-apxs=/usr/local/apache/bin/apxs
Must be installed in your machine the correct mysql librery:
MySQL-devel-4.1.7-0
MySQL-shared-4.1.7-0
nathansquires at pacbell dot net
13-Sep-2004 10:44
If you want to build php with both the Mysql and mysqli extensions, make sure your mysql distribution comes with shared libraries or build mysql yourself with shared libraries. With only static mysql libraries the compile process will fail.
severin dot kacianka at aon dot at
12-Aug-2004 03:55
I tryed Marco Kaiser's way of getting both mysql_* and mysqli_*, but it failed for me. However I could get it working this way:
First of all I installed the MySQL 4.1.3 binary disribution acourding to the manual. Then I simply passed these ./configure arguments:
--with-mysql=/path/to/mysql4.1.3
--with-mysqli=/path/to/mysql4.1.3/bin/mysql_config
This enabled both, the mysql_* and mysqli_* functions.
Severin Kacianka
ajp at aripollak dot com
19-Jul-2004 04:50
From README.PHP4-TO-PHP5-THIN-CHANGES:
Be careful when porting from ext/mysql to ext/mysqli. The following
functions return NULL when no more data is available in the result set
(ext/mysql's functions return FALSE).
- mysqli_fetch_row()
- mysqli_fetch_array()
- mysqli_fetch_assoc()
phoeniks[at]nm[dot]ru
08-Apr-2004 03:21
Here is a little sample to do fast hierarchical queries using new prepared statements
<?php
function tree_rise($root, &$stack, $top = 0) {
$mysqli = mysqli_connect('localhost', 'root');
$top = (int)$top;
$stmt = mysqli_prepare($mysqli, "SELECT id, pid, title FROM news.strg WHERE id = ? LIMIT 1");
mysqli_stmt_bind_param($stmt, "i", $root);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_bind_result($stmt, $id, $root, $title);
while (mysqli_fetch($stmt)) {
$stack[$id] = $title;
if ($root != $top && !is_null($root)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
}
}
return count($stack);
}
?>
|