mysqli::options

mysqli_options

(PHP 5, PHP 7, PHP 8)

mysqli::options -- mysqli_optionsDefine las opciones

Descripción

Estilo orientado a objetos

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

Estilo por procedimientos

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

Útil para definir opciones de conexión y así afectar el comportamiento de la conexión actual.

Esta función puede ser llamada múltiples veces para definir múltiples opciones.

mysqli_options() debe ser llamada después de mysqli_init() y antes de mysqli_real_connect().

Parámetros

link

Sólo estilo por procediminetos: Un identificador de enlace devuelto por mysqli_connect() o mysqli_init()

option

La opción que se desea definir. Puede tomar uno de los siguientes valores:

Opciones válidas
Nombre Descripción
MYSQLI_OPT_CONNECT_TIMEOUT Tiempo máximo de conexión en segundos
MYSQLI_OPT_READ_TIMEOUT Tiempo de espera de ejecución de un comando en segundos. Disponible a partir de PHP 7.2.0.
MYSQLI_OPT_LOCAL_INFILE Activa/desactiva el uso de LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND Comando a ejecutar después de la conexión al servidor MySQL
MYSQLI_SET_CHARSET_NAME El juego de caracteres a definir por defecto.
MYSQLI_READ_DEFAULT_FILE Lee las opciones desde el nombre de la opción en lugar del archivo my.cnf No soportado por mysqlnd
MYSQLI_READ_DEFAULT_GROUP Lee las opciones del grupo desde my.cnf o desde el archivo especificado con MYSQL_READ_DEFAULT_FILE. No soportado por mysqlnd
MYSQLI_SERVER_PUBLIC_KEY Archivo que contiene la clave pública RSA utilizada con la autenticación basada en SHA-256.
MYSQLI_OPT_NET_CMD_BUFFER_SIZE El tamaño del buffer interno de comando/red. Únicamente válido para mysqlnd.
MYSQLI_OPT_NET_READ_BUFFER_SIZE Tamaño, en bytes, máximo de la parte a leer durante la lectura del cuerpo de un paquete de comando MySQL. Únicamente válido para mysqlnd.
MYSQLI_OPT_INT_AND_FLOAT_NATIVE Convierte las columnas enteras y de coma flotante en números PHP al utilizar declaraciones no preparadas. Válido únicamente para mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT Si el certificado del servidor debe ser verificado o no.

value

El valor para la opción.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

Ejemplos

Ver mysqli_real_connect().

Notas

Nota:

MySQLnd siempre utiliza el juego de caracteres de idioma predeterminado. El juego de caracteres se envía en la autentificación/acuerdo que se produce durante la conexión, que utilizará mysqlnd.

Libmysqlclient utiliza el juego de caracteres predeterminado definido en my.cnf o se puede establecer llamando mysqli_options() antes de user mysqli_real_connect(), pero después de mysqli_init().

Ver también

add a note

User Contributed Notes 6 notes

up
3
Guy Sartorelli
2 years 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
9
php at darkain dot com
6 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
18 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
2
puneetsharam9 at hotmail dot com
2 years 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
Procedural Man
3 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
-2
king at bobfish dot org
17 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