I had a problem compiling PHP 5.2.5 with mysqli enabled on Mac OS X. Whether this problem was unique to me I do not no, so I am posting this for anybody else that runs into the same problem. Configure would run right to the end, but I had it telling me something had failed and that it was likely messed up. Upon checking debug.log I noticed this:
dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
/bin/sh: line 1: /Users/daniel/desktop/php -5.2.5/tmp-php.ini: Permission denied
dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
make: [test] Error 133 (ignored)
After screwing around for an hour and screaming many profanities at my computer I looked back at the error and noticed:
"/usr/local/mysql/lib/<b>mysql/</b>libmysqlclient.15.dylib
Why it was using this path I do not know, but I headslapped when I realised how simple it was! I solved the problem by creating a link called mysql that linked back on itself:
cd /usr/local/mysql/lib
sudo ln -s ./ mysql
Problem solved! I probably should have figured out why it was doing this instead, but this was easier and saved me from allot more frustration.
XCI. Extensión mejorada de MySQL
Introducción
La extensión mysqli permite acceder a la funcionalidad proveida por MySQL 4.1 y superior. Más información acerca del servidor de base de datos MySQL puede ser encontrada en http://www.mysql.com/
La documentación para MySQL puede ser encontrada en http://dev.mysql.com/doc/.
Partes de esta documentación ha sido incluida del manual de MySQL con permiso de MySQL AB.
Requisitos
Para tener estas funciones disponibles, usted debe compilar PHP con soporte para la extensión MySQLI.
Nota: La extensión mysqli está diseñada para trabajar con la versión 4.1.3 o superior de MySQL. Para versiones previas, por favor vea documentación de la extensión MySQL.
Instalación
Para instalar la extensión de mysqli para PHP, use la opción de configuración --with-mysqli=mysql_config_path/mysql_config donde mysql_config_path representa la ubicación del programa mysql_config que viene con MySQL en versiones superiores a 4.1.
Si quiere instalar la extensión de mysql junto con la extensión mysqli, usted tiene que usar la mismas librerias cliente, para evitar cualquier conflicto.
Configuración en tiempo de ejecución
El comportamiento de estas funciones está afectado por los valores definidos en php.ini.
Tabla 1. Opciones de configuración de MySQLi
| Nombre | Default | Cambiable | Changelog |
|---|---|---|---|
| mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PPH 5.0.0. |
| mysqli.default_port | 3306 | PHP_INI_ALL | Available since PPH 5.0.0. |
| mysqli.default_socket | NULL | PHP_INI_ALL | Available since PPH 5.0.0. |
| mysqli.default_host | NULL | PHP_INI_ALL | Available since PPH 5.0.0. |
| mysqli.default_user | NULL | PHP_INI_ALL | Available since PPH 5.0.0. |
| mysqli.default_pw | NULL | PHP_INI_ALL | Available since PPH 5.0.0. |
Para más detalles y definiciones de las constantes PHP_INI_* anteriores, vea el capítulo sobre Cambios de configuración.
A continuación se presenta una corta explicación de las directivas de configuración.
- mysqli.max_links integer
El número máximo de conexiones MySQL por proceso.
- mysqli.default_port string
El puerto TCP por defecto a usar cuando se conecte al servidor de base de datos si no se ha específicado otro puerto. Si no se define el default, el puerto será tomado de la variable de ambiente MYSQL_TCP_PORT, la entrada mysql-tcp en el archivo /etc/services o la constante en tiempo de ejecución MYSQL_PORT en ese orden. Win32 usará solo la constante MYSQL_PORT.
- mysqli.default_socket string
El nombre de socket por defecto a usar cuando se conecte a un servidor de base de datos local si no se ha específicado otro nombre de socket.
- mysqli.default_host string
El servidor huésped por defecto a usar cuando se conecta al servidor de base de datos si no se ha específicado otro. No aplica en modo seguro.
- mysqli.default_user string
El nombre de usuario por defecto a usar cuando se conecta al servidor de base de datos si no se específica otro nombre. No aplica en modo seguro.
- mysqli.default_pw string
La contraseña a usar cuando se conecta al servidor de base de datos si no se específica otra contraseña. No aplica en modo seguro.
Clases predefinidas
mysqli
Representa una conexión entres PHP y la base de datos MySQL.
Constructor
mysqli - constructor de un nuevo objeto mysqli
Métodos
autocommit - cambia en on o off las modificaciones de auto-commiting en la base de datos
change_user - cambia el usuario del identificador de enlace específicado
character_set_name - regresa el conjunto de caracteres del identificador de enlace específicado
close - cierra una conexión previamente abierta
commit - completa la transacció actual
connect - abre una nueva conexión al servidor de MySQL
debug - realiza operaciones de rastreo
dump_debug_info - vacía informació de rastreo
get_client_info - regresa la versión del cliente
get_host_info - regresa el tipo de conexión usada
get_server_info - regresa la versión del servidor MySQL
get_server_version - regresa la versión del servidor MySQL
init - inicializa el objeto mysqli
info - obtiene información acerca de la consulta más recientemente ejecutada
kill - solicita al servidor destruir un thread de mysql
multi_query - realiza consultas de SQL múltiples
more_results - checa si existen mas resultados de la consulta múltiple actualmente ejecutada
next_result - lee el siguiente resultado de la consulta múltiple actualmente ejecutada
options - fija opciones
ping - llama una conexión con el servidor o reconecta si no hay conexión
prepare - prepara una sentencia SQL
query - ejecuta una sentencia SQL
real_connect - intenta abrir una conexión al servidor de base de datos MySQL
escape_string - caracteres especiales de escape para ser usados en una sentencia SQL, tomando en cuenta el conjunto de caracteres actual de la conexión
rollback - deshace la transacción actual
select_db - selecciona la base de datos por defecto
ssl_set - fija los parámetros SSL
stat - obtiene el estado actual del sistema
stmt_init - inicializa una sentencia para ser usada con mysqli_stmt_prepare
store_result - transfiere un resultado de la última consulta
use_result - transfiere un resultado sin almacenamiento intermedio de la última consulta
thread_safe - regresa si se ha dado thread_safety o no
Propiedades
affected_rows - obtiene el número de filas afectadas en la operación MySQL previa
client_info - regresa en una cadena la versión del cliente de MySQL
client_version - regresa en un entero la versión del cliente de MySQL
errno - regresa el código de error para la llamada a función más reciente
error - regresa la cadena de error para la llamada a función más reciente
field_count - regresa el número de columnas para la consulta más reciente
host_info - regresa la cadena representando el tipo de conexión usado
info - regresa información acerca de la consulta ejecutada más recientemente
insert_id - regresa el identificador generado automáticamente usado en la última consulta
protocol_version - regresa la versión del protocolo usado por MySQL
sqlstate - regresa una cadena que contiene el código de error SQLSTATE para el último error
thread_id - regresa el identificador del THREAD para la conexión actual
warning_count - regresa el número de alertas generadas durante la ejecución del enunciado SQL previo
mysqli_stmt
Representa una sentencia preparada.
Métodos
bind_param - enlaza variables a una sentencia preparada
bind_result - enlaza variables a una sentencia preparada para el almacenamiento del resultado
close - cierra la sentencia preparada
data_seek - busca a una fila arbitrariamente en el resultado
execute - ejecuta una sentencia preparada
fetch - obtiene el resultado de la sentencia preparada en variables límite
free_result - libera la memoria del resultado almacenado para el manejador de la sentencia dada
result_metadata - obtiene un resultado de la sentencia preparada para información de metadatos
prepare - prepara una consulta SQL
send_long_data - envía datos en partes
reset - resetea una sentencia preparada
store_result - almacena el resultado completo de la sentencia preparada
Propiedades
affected_rows - regresa las filas afectadas de la última sentencia ejecutdada
errno - regresa el código de error para la llamada a función más reciente
error - regresa el mensaje de error para la llamada a función más reciente
param_count - regresa el numero de parámetros para la sentencia preparada dada
sqlstate - regresa una cadena conteniendo el código de error SQLSTATE para la llamada a función más reciente
mysqli_result
Representa el resultado obtenido de la consulta hecha en la base de datos.
Métodos
close - cierra el resultado
data_seek - mueve el puntero interno del resultado
fetch_field - obtiene la información de la columna en el resultado
fetch_fields - obtiene la información para todas las columnas del resultado
fetch_field_direct - obtiene información de la columna para la columna dada
fetch_array - recupera una fila como una matriz asociativa, una matriz numérica, o ambos.
fetch_assoc - obtiene una fuka como una matriz asociativa
fetch_object - obtiene una fila como un objeto
fetch_row - obtiene una fila como una matriz enumerada
close - libera la memoria ocupada por el resultado
field_seek - fija el apuntador del resultado a la posición específicada
Propiedades
current_field - regresa la posición de puntero actual
field_count - regresa el número de campos en el resultado
lengths - regresa una matriz con la longitud de los campos
num_rows - regresa el número de filas en el resultado
Constantes predefinidas
Tabla 2. Constantes MySQLi
| Nombre | Descripción |
|---|---|
| MYSQLI_READ_DEFAULT_GROUP (integer) | Lee las opciones del grupo llamado de `my.cnf' o la fila especificada con MYSQLI_READ_DEFAULT_FILE |
| MYSQLI_READ_DEFAULT_FILE (integer) | Lee las opciones del archivo específicado en vez de my.cnf |
| MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Tiempo de espera para la conexión en segundos |
| MYSQLI_OPT_LOCAL_INFILE (integer) | Habilita el comando LOAD LOCAL INFILE |
| MYSQLI_INIT_COMMAND (integer) | Comando a ejecutar cuando se conecta al servidor MySQL. Será automáticamente re-ejecutado cuando se vuelva a conectar. |
| MYSQLI_CLIENT_SSL (integer) | Usa SSL (protocolo de encripción). Esta opción no debe ser fijado por programas de apliación; esta es fijada internamente en la libreria cliente de MySQL |
| MYSQLI_CLIENT_COMPRESS (integer) | Usa el protocolo de compresión |
| MYSQLI_CLIENT_INTERACTIVE (integer) | Permite tiempo de espera interactivo en segundos (en vez de esperar ciertos segundos) de inactividad antes de cerrar la conexión. La variable wait_timeout de sesión del cliente será fijada a el valor de la variable de sesión interactive_timeout. |
| MYSQLI_CLIENT_IGNORE_SPACE (integer) | Permite espacios después de los nombres de las funciones. Esto hace a todas las funciones palabras reservadas. |
| MYSQLI_CLIENT_NO_SCHEMA (integer) | No permite la sintaxis db_name.tbl_name.col_name syntax. |
| MYSQLI_CLIENT_MULTI_QUERIES (integer) | |
| MYSQLI_STORE_RESULT (integer) | Para usar resultados con almacenamiento intermedio |
| MYSQLI_USE_RESULT (integer) | Para usar resultados sin almacenamiento intermedio |
| MYSQLI_ASSOC (integer) | Las columnas son regresadas en una matriz que tiene el nombre del campo como índice de la matriz. |
| MYSQLI_NUM (integer) | Las columnas son regresadas en una matriz teniendo un índice enumerado. |
| MYSQLI_BOTH (integer) | Las clumnas son regresadas en una matriz teniendo ambas formas de índice numérico y con el nombre del campo como índice asociativo. |
| MYSQLI_NOT_NULL_FLAG (integer) | Indica que un campo es definido como NOT NULL |
| MYSQLI_PRI_KEY_FLAG (integer) | El campo es parte de un índice primario |
| MYSQLI_UNIQUE_KEY_FLAG (integer) | El campo es parte de un índice único |
| MYSQLI_MULTIPLE_KEY_FLAG (integer) | El campo es parte de un índice. |
| MYSQLI_BLOB_FLAG (integer) | El campo está definido como BLOB |
| MYSQLI_UNSIGNED_FLAG (integer) | El campo está definido como UNSIGNED |
| MYSQLI_ZEROFILL_FLAG (integer) | El campo está definido como ZEROFILL |
| MYSQLI_AUTO_INCREMENT_FLAG (integer) | El campo está definido como AUTO_INCREMENT |
| MYSQLI_TIMESTAMP_FLAG (integer) | El campo está definido como TIMESTAMP |
| MYSQLI_SET_FLAG (integer) | El campo está definido como SET |
| MYSQLI_NUM_FLAG (integer) | El campo está definido como NUMERIC |
| MYSQLI_PART_KEY_FLAG (integer) | El campo es parte de un índice multiple |
| MYSQLI_GROUP_FLAG (integer) | El campo es parte de GROUP BY |
| MYSQLI_TYPE_DECIMAL (integer) | El campo está definido como DECIMAL |
| MYSQLI_TYPE_TINY (integer) | El campo está definido como TINYINT |
| MYSQLI_TYPE_SHORT (integer) | El campo está definido como INT |
| MYSQLI_TYPE_LONG (integer) | El campo está definido como INT |
| MYSQLI_TYPE_FLOAT (integer) | El campo está definido como FLOAT |
| MYSQLI_TYPE_DOUBLE (integer) | El campo está definido como DOUBLE |
| MYSQLI_TYPE_NULL (integer) | El campo está definido como DEFAULT NULL |
| MYSQLI_TYPE_TIMESTAMP (integer) | El campo está definido como TIMESTAMP |
| MYSQLI_TYPE_LONGLONG (integer) | El campo está definido como BIGINT |
| MYSQLI_TYPE_INT24 (integer) | El campo está definido como MEDIUMINT |
| MYSQLI_TYPE_DATE (integer) | El campo está definido como DATE |
| MYSQLI_TYPE_TIME (integer) | El campo está definido como TIME |
| MYSQLI_TYPE_DATETIME (integer) | El campo está definido como DATETIME |
| MYSQLI_TYPE_YEAR (integer) | El campo está definido como YEAR |
| MYSQLI_TYPE_NEWDATE (integer) | El campo está definido como DATE |
| MYSQLI_TYPE_ENUM (integer) | El campo está definido como ENUM |
| MYSQLI_TYPE_SET (integer) | El campo está definido como SET |
| MYSQLI_TYPE_TINY_BLOB (integer) | El campo está definido como TINYBLOB |
| MYSQLI_TYPE_MEDIUM_BLOB (integer) | El campo está definido como MEDIUMBLOB |
| MYSQLI_TYPE_LONG_BLOB (integer) | El campo está definido como LONGBLOB |
| MYSQLI_TYPE_BLOB (integer) | El campo está definido como BLOB |
| MYSQLI_TYPE_VAR_STRING (integer) | El campo está definido como VARCHAR |
| MYSQLI_TYPE_STRING (integer) | El campo está definido como CHAR |
| MYSQLI_TYPE_GEOMETRY (integer) | El campo está definido como GEOMETRY |
| MYSQLI_NEED_DATA (integer) | Obtiene más información para varibles enlazadas (bind) |
| MYSQLI_NO_DATA (integer) | No obtiene más información para variables enlazadas (bind) |
Ejemplos
Todos los ejemplos en la documentación MySQLI usan la base de datos de MySQL AB. Puede ser encontrada en http://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick
- Tabla de contenidos
- mysqli_affected_rows -- Obtiene el número de filas afectadas en una operación de MySQL previa
- mysqli_autocommit -- Activa o desactiva la modificación de auto-entrega de la base de datos
- mysqli_bind_param -- Alias para mysqli_stmt_bind_param()
- mysqli_bind_result -- Alias para mysqli_stmt_bind_result()
- mysqli_change_user -- Cambia el usuario de la conexión a la base de datos especificada
- mysqli_character_set_name -- Regresa el conjunto de caracteres determinados por default para la conexión de base de datos
- mysqli_client_encoding -- Alias de mysqli_character_set_name()
- mysqli_close -- Cierra la conexión de base de datos previamente abierta
- mysqli_commit -- Completa la transacción actual
- mysqli_connect_errno -- Regresa el código de error de la última llamada a la conexión
- mysqli_connect_error -- Regresa una descripción del último error de la conexión
- mysqli_connect -- Abre una nueva conexión al servidor MySQL
- mysqli_data_seek -- Ajusta el apuntador arbitrariamente a una fila en el resultado
- mysqli_debug -- Realiza operaciones de rastreo de errores
- mysqli_disable_reads_from_master -- Deshabilita lectura del Servidor maestro
- mysqli_disable_rpl_parse -- Deshabilita el analizador RPL
- mysqli_dump_debug_info -- Vacía información de rastreo de errores en el log
- mysqli_embedded_connect -- Abre una conexió a un servidor MySQL embebido
- mysqli_enable_reads_from_master -- Habilita la lectura del servidor Maestro
- mysqli_enable_rpl_parse -- Habilita el analizador RPL
- mysqli_errno -- Regresa el código de error para la función más recientemente llamada
- mysqli_error -- Regresa una cadena con la descripció del último error
- mysqli_escape_string -- Alias de mysqli_real_escape_string()
- mysqli_execute -- Alias de mysqli_stmt_execute()
- mysqli_fetch_array -- Obtiene una fila como una matriz asociativa, una matriz numérica o ambos
- mysqli_fetch_assoc -- Obtiene una fila del resultado como una matriz asociativa
- mysqli_fetch_field_direct -- Obtiene los metadatos de un campo
- mysqli_fetch_field -- Regresa metadatos de el campo en el resultado
- mysqli_fetch_fields -- Regresa una matriz de objetos representando los campos en un resultado
- mysqli_fetch_lengths -- Regresa la longitud de las columnas de la fila actual en el resultado
- mysqli_fetch_object -- Regresa la fila actual del resultado como un objeto
- mysqli_fetch_row -- Obtiene una fila del resultado como una matriz enumerada
- mysqli_fetch -- Alias de mysqli_stmt_fetch()
- mysqli_field_count -- Regresa el número de columnas para la consulta más reciente
- mysqli_field_seek -- Fija el apuntador del resultado a una posicion específica
- mysqli_field_tell -- Obtiene la posición de desplazamiento del apuntador de un resultado
- mysqli_free_result -- Libera la memoria asociada con el resultado
- mysqli_get_client_info -- Regresa en una cadena la versión del cliente de MySQL
- mysqli_get_client_version -- Obtiene información del cliente MySQL
- mysqli_get_host_info -- Regresa una cadena que representa el tipo de conexión usada
- mysqli_get_metadata -- Alias para mysqli_stmt_result_metadata()
- mysqli_get_proto_info -- Regresa la versión del protocolo de MySQL usado
- mysqli_get_server_info -- Regresa la version del servidor de MySQL
- mysqli_get_server_version -- Regresa la versión del servidor MySQL como un entero
- mysqli_info -- Obtiene información acerca de la consulta más recientemente ejecutada
- mysqli_init -- Inicializa MySQLi y regresa un objeto para ser usado con mysqli_rea_connect
- mysqli_insert_id -- Regresa el ID generado automáticamente en la última consulta
- mysqli_kill -- Le pide al servidor "matar" el proceso MySQL
- mysqli_master_query -- Hace cumplir la ejecución de una consulta en el servidor en una configuración cliente/servidor
- mysqli_more_results -- Checa si hay má resultados de consultas de una consulta múltiple
- mysqli_multi_query -- Ejecuta una consulta en la base de datos
- mysqli_next_result -- Prepara el siguiente resultado de una consulta múltiple
- mysqli_num_fields -- Obtiene el número de campos en un resultado Get the number of fields in a result
- mysqli_num_rows -- Obtiene el número de filas en un resultado
- mysqli_options -- Fija opciones
- mysqli_param_count -- Alias para mysqli_stmt_param_count()
- mysqli_ping -- Revisa una conexión al servidor o intenta reconectar si la conexión se ha perdido
- mysqli_prepare -- Prepara una sentencia SQL para su ejecución
- mysqli_query -- Ejecuta una consulta en la base de datos
- mysqli_real_connect -- Abre una conexión a un servidor de MySQL
- mysqli_real_escape_string -- Protege caracteres especiales en una cadena para ser usada en una sentencia SQL, tomando en cuenta el conjunto de caracteres para la conexión
- mysqli_real_query -- Ejecuta una consulta SQL
- mysqli_report -- Habilita o deshabilita las funciones internas de reporte
- mysqli_rollback -- Regresa/deshace la transacción actual
- mysqli_rpl_parse_enabled -- Revisa si el analizador RPL está habilitado
- mysqli_rpl_probe -- Prueba RPL
- mysqli_rpl_query_type -- Regresa el tipo de consulta RPL
- mysqli_select_db -- Selecciona la base de datos por defecto para las consultas de la base de datos
- mysqli_send_long_data -- Alias para mysqli_stmt_send_long_data()
- mysqli_send_query -- Envía la consulta y regresa
- mysqli_server_end -- Termina el proceso del Servidor
- mysqli_server_init -- Inicializa un servidor embebido
- mysqli_set_charset -- Sets the default client character set
- mysqli_set_opt -- Alias de mysqli_options()
- mysqli_sqlstate -- Regresa el error SQLSTATE de la operación MySQL previa
- mysqli_ssl_set -- Usado para establecer conexiones seguras usando SSL
- mysqli_stat -- Obtiene el estado actual del sistema
- mysqli_stmt_affected_rows -- Regresa el número total de filas cambiadas, borradas o insertadas por la última sentencia ejecutada
- mysqli_stmt_bind_param -- Enlaza variables como parámetros a una sentencia preparada
- mysqli_stmt_bind_result -- Enlaza variables a una sentencia preparada para el almacenamiento del resultado
- mysqli_stmt_close -- Cierra la sentencia preparada
- mysqli_stmt_data_seek -- Busca una fila arbitrariamente en el resultado
- mysqli_stmt_errno -- Regresa el código de error para la llamada más reciente
- mysqli_stmt_error -- Regresa una descipción para el último error
- mysqli_stmt_execute -- Ejecuta una consulta preparada
- mysqli_stmt_fetch -- Obtiene el resultado de una sentencia SQL preparada en las variables enlazadas
- mysqli_stmt_free_result -- Libera la memoria donde se almacenó el resultado
- mysqli_stmt_init -- Inicializa una sentencia y regresa un objeto para ser usado con mysqli_stmt_prepare
- mysqli_stmt_num_rows -- Regresa el número de filas en un resultado de la sentencia
- mysqli_stmt_param_count -- Regresa el número de parámetros para la sentencia dada
- mysqli_stmt_prepare -- Prepara una sentencia SQL para su ejecución
- mysqli_stmt_reset -- Resetea una sentencia preparada
- mysqli_stmt_result_metadata -- Regresa metadatos del resultado de una sentencia preparada
- mysqli_stmt_send_long_data -- Envía los datos en bloques
- mysqli_stmt_sqlstate -- Regresa el error SQLSTATE de la operación con sentencias previa
- mysqli_stmt_store_result -- Transfiere un resultado de una sentencia preparada
- mysqli_store_result -- Transfiere un resultado de la última consulta
- mysqli_thread_id -- Regresa el identificador del THREAD para la conexión actual
- mysqli_thread_safe -- Regresa si se ha dado un THREAD seguro o no Returns whether thread safety is given or not
- mysqli_use_result -- Inicia una recuperación de un resultado
- mysqli_warning_count -- Regresa el número de alertas de la última consulta para el identificador de enlace dado
It looks as though mysqli persistent connections will be available by default in PHP 6.
The source code for the mysqli PHP 6 module is here in the mysql SVN:
http://svn.mysql.com/svnpublic/
php-mysqlnd/trunk/php6/ext/mysqli/mysqli.c
It has a ton a of references to persistence, and the ini setting for enabling persistence is true by default.
To bad this isn't be integrated into the latest PHP 5 builds.
If you want to extend mysqli and establish an connection with SSL authentication, the followings may be useful.
(note: not all php-mysqli supports mysqli_ssl_set())
class DataAccess extends mysqli
{
function __construct(
$hostname, $username, $passwd=null, $dbname=null,
$port=null, $socket=null, $flags=null,
$privatekey=null, $certificate=null, $caCertificate=null)
{
$link = parent::init();
if ($privatekey!=null && $certificate!=null && $caCertificate!=null)
$link->ssl_set($privatekey, $certificate, $caCertificate,
dirname($caCertificate),NULL);
parent::__construct($hostname, $username,
$passwd, $dbname, $port, $socket);
}
.....
}
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.
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. :-/
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()
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
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.
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
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.
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...
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/
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.
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
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.
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
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.
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
A couple tutorials on the subject of mysqli:
* http://www.zend.com/php5/articles/php5-mysqli.php
* http://www.zend.com/php5/articles/php5-mysqli2.php
Here is a little sample to do fast hierarchical queries using new prepared statements
<?php
// Root - lowest start element
// Top - most top element
// stack - array for storing info
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);
}
?>
