CakeFest 2024: The Official CakePHP Conference

mysqli::options

mysqli_options

(PHP 5, PHP 7, PHP 8)

mysqli::options -- mysqli_optionsDefine opções

Descrição

Estilo orientado a objetos

public mysqli::options(int $option, string|int $value): bool

Estilo procedural

mysqli_options(mysqli $mysql, int $option, string|int $value): bool

Usado para definir opções extras de conexão e afetar o comportamento de uma conexão.

Esta função pode ser chamada várias vezes para definir várias opções.

mysqli_options() deve ser chamado depois de mysqli_init() e antes de mysqli_real_connect().

Parâmetros

mysql

Somente no estilo procedural: Um objeto mysqli retornado por mysqli_connect() ou mysqli_init()

option

A opção que você deseja definir. Pode ser um dos seguintes valores:

Valid options
Name Description
MYSQLI_OPT_CONNECT_TIMEOUT Tempo limite de conexão em segundos
MYSQLI_OPT_READ_TIMEOUT Tempo limite do resultado da execução do comando em segundos. Disponível a partir do PHP 7.2.0.
MYSQLI_OPT_LOCAL_INFILE Ativar/desativar o uso de LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND Comando para executar depois ao conectar ao servidor MySQL
MYSQLI_SET_CHARSET_NAME O conjunto de caracteres a ser definido como padrão..
MYSQLI_READ_DEFAULT_FILE Lê as opções do arquivo de opções nomeadas em vez de my.cnf Não suportado por mysqlnd.
MYSQLI_READ_DEFAULT_GROUP Leia as opções do grupo nomeado de my.cnf ou o arquivo especificado com MYSQL_READ_DEFAULT_FILE. Não suportado pelo mysqlnd.
MYSQLI_SERVER_PUBLIC_KEY Arquivo de chave pública RSA usado com a autenticação baseada em SHA-256.
MYSQLI_OPT_NET_CMD_BUFFER_SIZE O tamanho do buffer interno de comando/rede. Válido apenas para mysqlnd.
MYSQLI_OPT_NET_READ_BUFFER_SIZE Tamanho máximo do bloco de leitura em bytes ao ler o corpo de um pacote de comando do MySQL. Válido apenas para mysqlnd.
MYSQLI_OPT_INT_AND_FLOAT_NATIVE Converte colunas de números inteiros e pontos flutuantes de volta para números PHP ao usar instruções não preparadas. Válido apenas para mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT Se deve-se verificar ou não o certificado do servidor.

value

O valor da opção.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros/Exceções

Se o relatório de erros da extensão mysqli estiver habilitado (MYSQLI_REPORT_ERROR) e a operação solicitada falhar, um aviso será gerado. Se, além disso, o modo for definido como MYSQLI_REPORT_STRICT, uma exceção mysqli_sql_exception será lançada em vez do aviso.

Exemplos

Veja mysqli_real_connect().

Notas

Nota:

O MySQLnd sempre assume o conjunto de caracteres padrão do servidor. Este conjunto de caracteres é enviado durante a criação/autenticação da conexão e será usado pelo mysqlnd.

A libmysqlclient usa o conjunto de caracteres padrão definido no arquivo my.cnf ou definido por uma chamada explícita a mysqli_options() antes de chamar mysqli_real_connect(), mas depois de chamar mysqli_init().

Veja Também

add a note

User Contributed Notes 6 notes

up
9
php at darkain dot com
5 years ago
There is an undocumented option: MYSQLI_OPT_READ_TIMEOUT. This is similar to MYSQLI_OPT_CONNECT_TIMEOUT in theory, but has a slightly different application. Connection timeout only specifies the wait time for the initial TCP connection. Once that is created, the timeout no longer applies. Read timeout, however, is from the time the TCP connection is created until the first packet of actual data is received. There are instances where a TCP connection can be established, but the MySQL server stalls indefinitely, preventing execution from ever returning to PHP. Specifying a read timeout alleviates this condition, whereas connect timeout wouldn't.

If the MYSQLI_OPT_READ_TIMEOUT constant isn't defined, it is still supported on versions where that isn't the case. You can define it yourself in older PHP versions with the following code.

<?php
if (!defined('MYSQLI_OPT_READ_TIMEOUT')) {
define ('MYSQLI_OPT_READ_TIMEOUT', 11);
}
?>

You can then use read timeout the same way you could a connect timeout as follows. Please note that since these are two different timeout values for two different parts of the entire connection process, the timeouts do stack (eg: 10 seconds connect timeout + 10 seconds read timeout = maximum possible timeout of 20 seconds)

<?php
//create the object
$connection = mysqli_init();

//specify the connection timeout
$connection->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);

//specify the read timeout
$connection->options(MYSQLI_OPT_READ_TIMEOUT, 10);

//initiate the connection to the server, using both previously specified timeouts
$connection->real_connect('server', 'user', 'pass', 'database');
?>
up
8
fluppy
17 years ago
Here es little example to create a SSL Connection

<?php

$db
= mysqli_init();

/*
When you want so use a separate cnf
$test = $db->options(MYSQLI_EAD_DEFAULT_FILE,'myother.cnf');
*/

$db->ssl_set('server-key.pem','server-cert.pem',
'cacert.pem',NULL,NULL);

$db->real_connect('localhost','root','','mydb');

//Here some query

$db->close();

?>
up
1
Procedural Man
2 years ago
Although it is not explained on the manual, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT is an option only valid for mysqlnd and will raise an error if used with mysqli.
up
1
Guy Sartorelli
10 months ago
The `MYSQLI_OPT_SSL_VERIFY_SERVER_CERT` seems to always fail, with `options()` always returning false.
Use the `MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT` flag with `real_connect()` instead.
up
1
puneetsharam9 at hotmail dot com
1 year ago
With Objective Approach
init of mysqli is depreciated from 8.1 it seem so
You could have to use an empty __construct()
So You have proper int and float

class DB extends \mysqli {
private function __construct(
private $_user = DBUSER,
private $_pass = DBPWD,
private $_dbName = DBNAME,
private $_dbHost = DBHOST,
) {
parent::__construct();
parent::options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
parent::real_connect($this->_dbHost, $this->_user, $this->_pass, $this->_dbName);
}
}
up
-2
king at bobfish dot org
16 years ago
Example on using mysqli_options to increase size of max_allowed_packet for working with big blobs.

function dbConnect()
{
$user = 'jomama';
$pass = 'cartoon';
$dbName = 'LifeCycle';
$host = 'localhost';

$mysqli = mysqli_init();
mysqli_options($mysqli,MYSQLI_READ_DEFAULT_GROUP,
"max_allowed_packet=50M");
mysqli_real_connect($mysqli,$host, $user, $pass,$dbName)
or die ('<P>Unable to connect</P>');

return $mysqli;
}
To Top