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.
XCVI. MySQL Melhorada
Introdução
A extensão mysqli permite a você acessar a funcionalidade provida pelo MySQL 4.1 e posterior. Maiores informações sobre o servidor de banco de dados MySQL podem ser encontradas em http://www.mysql.com/
Documentação para o MySQL pode ser encontrada em http://dev.mysql.com/doc/.
Partes desta documentação foram incluídas do manual do MySQL com a permissão de MySQL AB.
Dependências
Para ter esta funções disponíveis, você deverá compilar o PHP com suporte para a extensão mysqli.
Nota: A extensão mysqli foi criada para funcionar com a versão 4.1.2 ou posterior do MySQL. Para versões anteriores, por favor vejaa documentação da extensão MySQL.
Instalação
Para instalar a extensão mysqli para o PHP, use a opção de configuração --with-mysqli=mysql_config_path/mysql_config aonde mysql_config_path representa a localização do programa mysql_config que vem com versões do MySQL maiores do que 4.1.
Se você quiser instalar a extensão mysql junto com a extensão mysqli você tem que usar a mesma biblioteca de cliente para previnir quaisquer conflitos.
Configurações em execução
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
Tabela 1. Opções de configuração do MySQLi
| Nome | Padrão | Modificável |
|---|---|---|
| mysqli.max_links | "-1" | PHP_INI_SYSTEM |
| mysqli.default_port | NULL | PHP_INI_ALL |
| mysqli.default_socket | NULL | PHP_INI_ALL |
| mysqli.default_host | NULL | PHP_INI_ALL |
| mysqli.default_user | NULL | PHP_INI_ALL |
| mysqli.default_pw | NULL | PHP_INI_ALL |
Para maiores detalhes e definições das constantes PHP_INI_* acima, veja o capitulo sobre mudanças de configuração.
Breve descrição das diretivas de configuração.
- mysqli.max_links integer
O número máximo de conexões MySQL por processo.
- mysqli.default_port string
O número da porta TCP padrão para usar ao conectar ao servidor de banco de dados se não for especificada outra porta. Se não for especificado um padrão, então a porta será obtida da variável de ambiênte MYSQL_TCP_PORT, a entrada mysql-tcp em /etc/services ou a constante em tempo de compilação MYSQL_PORT, nesta ordem. Em Win32 será usada apenas a constante MYSQL_PORT.
- mysqli.default_socket string
O nome padrão do socket para usar ao conectar com um servidor de banco de dados local, se não for especificado outro nome de socket.
- mysqli.default_host string
O servidor padrão para usar ao conectar com o servidor de banco de dados se não for especificado um servidor. Não se aplica em safe mode.
- mysqli.default_user string
O nome de usuário padrão para usar ao conectar com o servidor de banco de dados. Não se aplica em safe mode.
- mysqli.default_password string
A senha padrão para usar ao conectar ao servidor de banco de dados se não for especificado outra senha. Não se aplica em safe mode.
Classes pré-definidas
mysqli
Representa uma conexão entre o PHP e um banco de dados MySQL.
Construtor
mysqli() - constroi um novo objeto mysqli
Métodos
autocommit() - ativa ou desativa o salvar automaticamente as modificações no banco de dados
change_user() - modifica o usuário da conexão com o banco de dados especficada
character_set_name - retorna o conjunto de caracteres padrão para a conexão com o banco de dados
close - fecha uma conexão aberta anteriormente
commit - grava a transação atual
connect - abre uma nova conexão com o servidor de banco de dados MySQL
debug - realiza operações de debug
dump_debug_info - mostra informações de debug
get_client_info - retorna a versão do cliente
get_host_info - retorna o tipo da conexão usada
get_server_info - retorna a versão do servidor MySQL
get_server_version - retorna a versão do servidor MySQL
init - inicia o objeto mysqli
info - retorna informação sobre a consulta mais recente executada
kill - diz ao servidor para matar uma thread do mysql
multi_query - executa multiplas consultas
more_results - confere se existem mais resultados na consulta multipla atual
next_result - lê o próximo resultado da consulta multipla atual
options - define opções
ping - pinga uma conexão com o servidor ou reconecta se não houver conexão
prepare - prepara uma consulta SQL
query - executa uma consulta
real_connect - tenta abrir uma conexão com o servidor de banco de dados MySQL
escape_string - escapa os caracteres especiais para usar em uma consulta SQL, levando em conta o conjunto de caracteres atual
rollback - desfaz a transação atual
select_db - define o banco de dados padrão
ssl_set - define parâmetros ssl
stat - retorna o estado atual do sistema
stmt_initInicia um comando para usar com mysqli_stmt_prepare
store_result - transfere um conjunto de resultados da ultima consulta
use_result - transfere um conjunto de resultados não guardado em buffer da ultima consulta
thread-safe - retorna quando thread safety é dado ou não
Propriedades
affected_rows - retorna o número de linhas afetadas pela operação MySQL anterior
errno - retorna o código de erro da chamada de função mais recente
error - retorna a string de erro da chamada de função mais recente
field_count - retorna o número de colunas da consulta mais recente
host_info - retorna uma string representando o tipo de conexão usada
info - retorna informação sobre a consulta mais recente executada
insert-id - retorna o id gerado automaticamente usado na ultima consulta
protocol_version - retorna a versão usada do protocolo MySQL
sqlstate - retorna uma string contendo o código de erro SQLSTATE do ultimo erro
thread_id - retorna o thread ID da conexão atual
warning-count - retorna o número de warnings(avisos) gerados durante a execução da consulta SQL anterior
mysqli_stmt
Representa um comando preparado.
Métodos
bind_param - Binds variables to a prepared statement
bind_result - Binds variables to a prepared statement for result storage
close - Fecha um comando preparado
data-seek - Move para uma linha arbritária em um conjuto de resultads em um comando preparado
execute - Executa um comando preparado
fetch - Obtém resultados de um comando preparado em variáveis
free_result - Libera a memória do resultado de um comando preparado
result_metadata - Retorna um conjunto de resultados de um comando preparado para informação de metadados
prepare - Prepara uma consulta SQL
send_long_data - Envia os dados em pedaços
store_result - Guarda todo o conjunto de resultados de um comando preparado em buffer
Propriedades
affected_rows - Retorna as linhas afetadas pela ultima consulta executada
errno - Retorna o código de erro pela ultima função do comando
errno - Retorna a mensagem de erro pela última função do comando
param_count - Retorna o número de parâmetros para o comando preparado
sqlstate - Retorna uma string contendo o código de erro SQLSTATE pela última função do comando
mysqli_result
Representa o conjunto de resultados da consulta feit ao banco de dados.
Métodos
close - fecha o conjunto de resultados
data_seek - move o ponteiro interno dos resultados
fetch_field - retorna informação sobre uma coluna do conjunto de resulatdos
fetch_fields - retorna informação sobre todas as colunas do conjunto de resultados
fetch_field_direct - retorna informação da coluna especificada
fetch_array - retorna uma linha em uma matriz associativa, uma matriz numérica, ou ambas.
fetch_assoc - retorna uma linha do resultado como uma matriz associativa
fetch_object - retorna uma linha do resultado como um objeto
fetch_row - retorna uma linha do resultado como uma matriz numérica
close - libera a memória usada
field_seek - define o ponteiro do resultado para o índice de campo especificado
Propriedades
current_field - retorna o índice do campo atual
field_count - retorna o número de campos do conjunto de resultados
lengths - retorna uma matriz com os tamanhos das colunas
num_rows - retorna o número de linhas em um conjunto de resultados
Constantes pré-definidas
Tabela 2. Constantes MySQLi
| Nome | Descrição |
|---|---|
| MYSQLI_READ_DEFAULT_GROUP (integer) | Lê opções do grupo especificado apartir do arquivo `my.cnf' ou do arquivo especificado por MYSQLI_READ_DEFAULT_FILE |
| MYSQLI_READ_DEFAULT_FILE (integer) | Lê opções apartir do arquivo indicado ao invés de my.cnf |
| MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Limite de tempo para conectar em segundos |
| MYSQLI_OPT_LOCAL_INFILE (integer) | Ativa o comando LOAD LOCAL INFILE |
| MYSQLI_INIT_COMMAND (integer) | Comando para executar ao conectar no servidor MySQL. Será automaticamente executado novamente ao reconectar. |
| MYSQLI_CLIENT_SSL (integer) | Usar SSL (protocolo criptografado). Esta opção não deve ser definida por programas aplicativos; ela é definida internamente na biblioteca de cliente MySQL |
| MYSQLI_CLIENT_COMPRESS (integer) | Usar o protocolo de compressão |
| MYSQLI_CLIENT_INTERACTIVE (integer) | Permite interactive_timeout segundos (ao invés de wait_timeout segundo) de inatividade antes de fechar a conexão. A variável de sessão do cliente wait_timeout variable será definida com o valor da variável interactive_timeout. |
| MYSQLI_CLIENT_IGNORE_SPACE (integer) | Permite espaçoes após os nomes de função. Torna todos os nomes de função palavras reservadas. |
| MYSQLI_CLIENT_NO_SCHEMA (integer) | Não permite a sintaxe nome_bancodados.nome_tabela.nome_coluna |
| MYSQLI_CLIENT_MULTI_QUERIES (integer) | |
| MYSQLI_STORE_RESULT (integer) | Para usar conjuntos de resultados guardados em buffer |
| MYSQLI_USE_RESULT (integer) | Para usar conjuntos de resultados não guardados em buffer |
| MYSQLI_ASSOC (integer) | As colunas são retornadas em uma matriz tendo o nome dos campos como indices da matriz. |
| MYSQLI_NUM (integer) | As colunas são retornadas em uma matriz tendo os índices numerados. |
| MYSQLI_BOTH (integer) | As colunas são retornadas em uma matriz tendo ambos os índices, numérico e o nome do campo como índice associativo. |
| MYSQLI_NOT_NULL_FLAG (integer) | Indica que um campo é definido como NOT NULL |
| MYSQLI_PRI_KEY_FLAG (integer) | O campo é parte do índice primário |
| MYSQLI_UNIQUE_KEY_FLAG (integer) | O campo é parte de um índice único. |
| MYSQLI_MULTIPLE_KEY_FLAG (integer) | O campo é parte de um índice. |
| MYSQLI_BLOB_FLAG (integer) | O campo é definido como BLOB |
| MYSQLI_UNSIGNED_FLAG (integer) | O campo é definido como UNSIGNED |
| MYSQLI_ZEROFILL_FLAG (integer) | O campo é definido como ZEROFILL |
| MYSQLI_AUTO_INCREMENT_FLAG (integer) | O campo é definido como AUTO_INCREMENT |
| MYSQLI_TIMESTAMP_FLAG (integer) | O campo é definido como TIMESTAMP |
| MYSQLI_SET_FLAG (integer) | O campo é definido como SET |
| MYSQLI_NUM_FLAG (integer) | O campo é definido como NUMERIC |
| MYSQLI_PART_KEY_FLAG (integer) | O campo é parte de um índice múltiplo |
| MYSQLI_GROUP_FLAG (integer) | O campo é parte de GROUP BY |
| MYSQLI_TYPE_DECIMAL (integer) | O campo é definido como DECIMAL |
| MYSQLI_TYPE_TINY (integer) | O campo é definido como TINYINT |
| MYSQLI_TYPE_SHORT (integer) | O campo é definido como INT |
| MYSQLI_TYPE_LONG (integer) | O campo é definido como INT |
| MYSQLI_TYPE_FLOAT (integer) | O campo é definido como FLOAT |
| MYSQLI_TYPE_DOUBLE (integer) | O campo é definido como DOUBLE |
| MYSQLI_TYPE_NULL (integer) | O campo é definido como DEFAULT NULL |
| MYSQLI_TYPE_TIMESTAMP (integer) | O campo é definido como TIMESTAMP |
| MYSQLI_TYPE_LONGLONG (integer) | O campo é definido como BIGINT |
| MYSQLI_TYPE_INT24 (integer) | O campo é definido como MEDIUMINT |
| MYSQLI_TYPE_DATE (integer) | O campo é definido como DATE |
| MYSQLI_TYPE_TIME (integer) | O campo é definido como TIME |
| MYSQLI_TYPE_DATETIME (integer) | O campo é definido como DATETIME |
| MYSQLI_TYPE_YEAR (integer) | O campo é definido como YEAR |
| MYSQLI_TYPE_NEWDATE (integer) | O campo é definido como DATE |
| MYSQLI_TYPE_ENUM (integer) | O campo é definido como ENUM |
| MYSQLI_TYPE_SET (integer) | Field is defined as SET |
| MYSQLI_TYPE_TINY_BLOB (integer) | Field is defined as TINYBLOB |
| MYSQLI_TYPE_MEDIUM_BLOB (integer) | O campo é definido como MEDIUMBLOB |
| MYSQLI_TYPE_LONG_BLOB (integer) | O campo é definido como LONGBLOB |
| MYSQLI_TYPE_BLOB (integer) | O campo é definido como BLOB |
| MYSQLI_TYPE_STRING (integer) | O campo é definido como VARCHAR |
| MYSQLI_TYPE_CHAR (integer) | O campo é definido como CHAR |
| MYSQLI_TYPE_GEOMETRY (integer) | O campo é definido como GEOMETRY |
| MYSQLI_NEED_DATA (integer) | More data available for bind variable |
| MYSQLI_NO_DATA (integer) | No more data available for bind variable |
Exemplos
Todos os exemplos na documentação MySQLI usam o banco de dados world da MySQL AB. O banco de dados world pode ser encontrado em http://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick
- Índice
- mysqli_affected_rows -- Retorna o número de linhas afetadas pela operação MySQL anterior
- mysqli_autocommit -- Ativa ou desativa o salvar automaticamente as modificações no banco de dados
- mysqli_bind_param -- Apelido para mysqli_stmt_bind_param()
- mysqli_bind_result -- Apelido para mysqli_stmt_bind_result()
- mysqli_change_user -- Modifica o usuário para a conexão com o banco de dados especificada
- mysqli_character_set_name -- Retorna o conjunto de caracteres padrão para a conexão com o banco de dados
- mysqli_client_encoding -- Apelido para mysqli_character_set_name()
- mysqli_close -- Fecha uma conexão aberta anteriormente com o banco de dados
- mysqli_commit -- Salva a transação atual
- mysqli_connect_errno -- Retorna o código de erro da ultima chamada a função connect
- mysqli_connect_error -- Retorna uma string descrevendo o ultimo erro da função connect
- mysqli_connect -- Abre uma nova conexão com o servidor MySQL
- mysqli_data_seek -- Ajusta o ponteiro do resultado para uma linha arbritaria no conjunto de resutados
- mysqli_debug -- Realiza operações de debug
- mysqli_disable_reads_from_master --
- mysqli_disable_rpl_parse --
- mysqli_dump_debug_info -- Descarrega informação de debug no log
- mysqli_embedded_connect -- Abre uma conexão com um servidor MySQL embutido
- mysqli_enable_reads_from_master --
- mysqli_enable_rpl_parse --
- mysqli_errno -- Retorna o código de erro para a chamada de função mais recente
- mysqli_error -- Retorna uma string descrevendo o ultimo erro
- mysqli_escape_string -- Apelido para mysqli_real_escape_string()
- mysqli_execute -- Apelido para mysqli_stmt_execute()
- mysqli_fetch_array -- Obtem uma linha do resultado como uma matriz associativa, numérica, ou ambas
- mysqli_fetch_assoc -- Obtem uma linha do conjunto de resultados como uma matriz associativa
- mysqli_fetch_field_direct -- Obtem meta dados para um único campo
- mysqli_fetch_field -- Retorna o próximo campo no conjunto de resultados
- mysqli_fetch_fields -- Retorna uma matriz de objetos representando os campos em um conjunto de resultados
- mysqli_fetch_lengths -- Retorna os tamanhos das colunas na linha atual no conjunto de resultados
- mysqli_fetch_object -- Retorna a linha atual do conjunto de resultados como um objeto
- mysqli_fetch_row -- Obtém uma linha do resultado como uma matriz numerada
- mysqli_fetch -- Apelido para mysqli_stmt_fetch()
- mysqli_field_count -- Retorna o número de colunas para a consulta mais recente
- mysqli_field_seek -- Move o ponteiro do resultado para um campo especificado
- mysqli_field_tell -- Obtém o índice do campo de um ponteiro de resultado
- mysqli_free_result -- Libera a memória associada ao resultado
- mysqli_get_client_info -- Retorna a versão do cliente MySQL como uma string
- mysqli_get_client_version -- Obtém informação sobre o cliente MySQL
- mysqli_get_host_info -- Retorna uma string representando o tipo da conexão usada
- mysqli_get_metadata -- Apelido para mysqli_stmt_result_metadata()
- mysqli_get_proto_info -- Retorna a versão do protocolo MySQL usada
- mysqli_get_server_info -- Retorna a versão do servidor MySQL
- mysqli_get_server_version -- Retorna a versão do servidor MySQL como um integer
- mysqli_info -- Obtém informação sobre a consulta executada mais recentemente
- mysqli_init -- Inicializa a MySQLi e tetorna um objeto para usar com mysqli_real_connect
- mysqli_insert_id -- Retorna o id gerado automaticamente na última consulta
- mysqli_kill -- Diz ao servidor para matar uma thread MySQL
- mysqli_master_query -- Força a execução de uma consulta no master em uma configuração master/slave
- mysqli_more_results -- Confere se existem mais resultados de consultas em uma consulta múltipla
- mysqli_multi_query -- Executa uma consulta no banco de dados
- mysqli_next_result -- Preepara o próximo resultado de uma consulta múltipla
- mysqli_num_fields -- Obtém o número de campos em um resultado
- mysqli_num_rows -- Gets the number of rows in a result
- mysqli_options -- Set options
- mysqli_param_count -- Alias for mysqli_stmt_param_count()
- mysqli_ping -- Pings a server connection, or tries to reconnect if the connection has gone down
- mysqli_prepare -- Prepare a SQL statement for execution
- mysqli_query -- Performs a query on the database
- mysqli_real_connect -- Opens a connection to a mysql server
- mysqli_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
- mysqli_real_query -- Execute an SQL query
- mysqli_report -- Enables or disables internal report functions
- mysqli_rollback -- Rolls back current transaction
- mysqli_rpl_parse_enabled -- Check if RPL parse is enabled
- mysqli_rpl_probe -- RPL probe
- mysqli_rpl_query_type -- Returns RPL query type
- mysqli_select_db -- Selects the default database for database queries
- mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()
- mysqli_send_query -- Send the query and return
- mysqli_server_end -- Shut down the embedded server
- mysqli_server_init -- Initialize embedded server
- mysqli_set_charset -- Sets the default client character set
- mysqli_set_opt -- Alias of mysqli_options()
- mysqli_sqlstate -- Returns the SQLSTATE error from previous MySQL operation
- mysqli_ssl_set -- Used for establishing secure connections using SSL
- mysqli_stat -- Gets the current system status
- mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
- mysqli_stmt_bind_param -- Binds variables to a prepared statement as parameters
- mysqli_stmt_bind_result -- Binds variables to a prepared statement for result storage
- mysqli_stmt_close -- Closes a prepared statement
- mysqli_stmt_data_seek -- Seeks to an arbitray row in statement result set
- mysqli_stmt_errno -- Returns the error code for the most recent statement call
- mysqli_stmt_error -- Returns a string description for last statement error
- mysqli_stmt_execute -- Executes a prepared Query
- mysqli_stmt_fetch -- Fetch results from a prepared statement into the bound variables
- mysqli_stmt_free_result -- Frees stored result memory for the given statement handle
- mysqli_stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepare
- mysqli_stmt_num_rows -- Return the number of rows in statements result set
- mysqli_stmt_param_count -- Returns the number of parameter for the given statement
- mysqli_stmt_prepare -- Prepare a SQL statement for execution
- mysqli_stmt_reset -- Resets a prepared statement
- mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement
- mysqli_stmt_send_long_data -- Send data in blocks
- mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
- mysqli_stmt_store_result -- Transfers a result set from a prepared statement
- mysqli_store_result -- Transfers a result set from the last query
- mysqli_thread_id -- Returns the thread ID for the current connection
- mysqli_thread_safe -- Returns whether thread safety is given or not
- mysqli_use_result -- Initiate a result set retrieval
- mysqli_warning_count -- Returns the number of warnings from the last query for the given link
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);
}
?>
