PHP mysqli class
The PHP mysqli class is the main class of the MySQLi extension of PHP. This class represents a connection to the database created with a MySQL DBMS.
The following synopsis is the same as that given on PHP.net
Sinopsisclass mysqli { /* Propiedades */ int $affected_rows; int $connect_errno; string $connect_error; int $errno; array $error_list; string $error; int $field_count; int $client_version; string $host_info; string $protocol_version; string $server_info; int $server_version; string $info; mixed $insert_id; string $sqlstate; int $thread_id; int $warning_count; /* Métodos */ __construct( string $host = ini_get("mysqli.default_host"), string $username = ini_get("mysqli.default_user"), string $passwd = ini_get("mysqli.default_pw"), string $dbname = "", int $port = ini_get("mysqli.default_port"), string $socket = ini_get("mysqli.default_socket") ) autocommit(bool $mode): bool change_user(string $user, string $password, string $database): bool character_set_name(): string close(): bool commit(int $flags = ?, string $name = ?): bool debug(string $message): bool dump_debug_info(): bool get_charset(): object get_client_info(): string get_connection_stats(): bool mysqli_stmt::get_server_info(): string get_warnings(): mysqli_warning init(): mysqli kill(int $processid): bool more_results(): bool multi_query(string $query): bool next_result(): bool options(int $option, mixed $value): bool ping(): bool public static poll( array &$read, array &$error, array &$reject, int $sec, int $usec = ? ): int prepare(string $query): mysqli_stmt query(string $query, int $resultmode = MYSQLI_STORE_RESULT): mixed real_connect( string $host = ?, string $username = ?, string $passwd = ?, string $dbname = ?, int $port = ?, string $socket = ?, int $flags = ? ): bool escape_string(string $escapestr): string real_query(string $query): bool public reap_async_query(): mysqli_result public refresh(int $options): bool rollback(int $flags = ?, string $name = ?): bool select_db(string $dbname): bool set_charset(string $charset): bool ssl_set( string $key, string $cert, string $ca, string $capath, string $cipher ): bool stat(): string stmt_init(): mysqli_stmt store_result(int $option = ?): mysqli_result use_result(): mysqli_result }
Properites in PHP mysqli class
https://blastcoding.com/en/php-mysqli-class/#propertiesIn the properties, we will use the variable $dbconnection
, which will be the connection obtained after instantiating the class.
$dbconnection = new mysqli('localhost', 'my_user', 'my_password', 'my_bd');
affected_rows
https://blastcoding.com/en/php-mysqli-class/#affected_rowsReturns the number of rows affected in the last query
Sintaxis / Sintax$dbconnection->affected_rows;
connect_errno
https://blastcoding.com/en/php-mysqli-class/#connect_errnoError code from the last call.
Sintaxis$dbconnection->connect_errno;
connect_error
https://blastcoding.com/en/php-mysqli-class/#connect_errorReturns a string with the description of the last connection error.
Sintaxis$dbconnection->connect_error;
errno
https://blastcoding.com/en/php-mysqli-class/#errnoError code from the last function call
Sintaxis$dbconnection->errno;
error_list
https://blastcoding.com/en/php-mysqli-class/#error_listList of errors since the last executed command.
Sintaxis$dbconnection->error_list;
error
https://blastcoding.com/en/php-mysqli-class/#errorString that describes the last error.
Sintaxis$dbconnection->error;
field_count
https://blastcoding.com/en/php-mysqli-class/#field_countNumber of columns for the most recent query.
Sintaxis$dbconnection->field_count;
client_version
https://blastcoding.com/en/php-mysqli-class/#client_versionMySQL client version as an integer value. This is the version of the library, allowing us to determine whether we can use certain MySQL features or functionalities.
Sintaxis$dbconnection->client_version;
host_info
https://blastcoding.com/en/php-mysqli-class/#host_infoString representing the type of connection used.
Sintaxis$dbconnection->host_info;
protocol_version
https://blastcoding.com/en/php-mysqli-class/#protocol_versionReturns the version of the protocol used.
Sintaxis$dbconnection->protocol_version;
server_info
https://blastcoding.com/en/php-mysqli-class/#server_infoMySQL server version returned as a string.
Sintaxis$dbconnection->server_info;
server_version
https://blastcoding.com/en/php-mysqli-class/#server_versionMySQL server version as an integer
Sintaxis$dbconnection->server_version;
info
https://blastcoding.com/en/php-mysqli-class/#infoInformation about the most recent query executed.
Sintaxis$dbconnection->info;
insert_id
https://blastcoding.com/en/php-mysqli-class/#insert_idThis is the value generated by an AUTO_INCREMENT belonging to a column in our database, created by the last query.
It is clear that for the last query to give us this number, the table must have an AUTO_INCREMENT id.
Sintaxis$dbconnection->insert_id;
sqlstate
https://blastcoding.com/en/php-mysqli-class/#sqlstateThe SQLSTATE error from a previous operation (query) in MySQL.
Sintaxis$dbconnection->sqlstate;
thread_id
https://blastcoding.com/en/php-mysqli-class/#thread_idThe thread ID of the current connection. You will probably never use this property; you would need a large number of users to worry about the threads connecting to the database
Sintaxis$dbconnection->thread_id;
warning_count
https://blastcoding.com/en/php-mysqli-class/#warning_countIt will return the number of warnings since the last query for the given link.
Sintaxis$dbconnection->warning_count;
PHP mysqli class methods
https://blastcoding.com/en/php-mysqli-class/#metodosHere we will see the different methods belonging to our mysqli
class. This is the main class of the MySQLi extension and, therefore, has the largest number of methods.
__construct
https://blastcoding.com/en/php-mysqli-class/#__constructOpens a new connection to our MySQL server, creating our mysqli
object that will represent this connection.
public mysqli::__construct( string $host = ini_get("mysqli.default_host"), string $username = ini_get("mysqli.default_user"), string $passwd = ini_get("mysqli.default_pw"), string $dbname = "", int $port = ini_get("mysqli.default_port"), string $socket = ini_get("mysqli.default_socket") )Sintaxis
$db = new mysqli($host, $username, $passwd, $dbname, $port, $socket);
Usually, one of the following names is used for the variable that contains the mysqli
object: $conn
, $db
, $dbconn
, $dbconnection
, $database
.
Parameters
$host
– The given value must be a string, for example, the host name “localhost” or the host IP “127.0.0.1”.
$username
– The username that will use our database.
$passwd
– Password of the user who will use the database.
$dbname
– The name of the database.
$port
– Port.
$socket
– Socket (combination of IP + port).
Returns
mysqli[obj]
– Returns a mysqli
object if the connection to the database can be established.
false
– This method returns false in case of an error.
autocommit
https://blastcoding.com/en/php-mysqli-class/#autocommitThis method determines whether we want queries to auto-commit or not. What I must emphasize about this is: we need to be careful when using it, as it makes no sense to use auto-commit if we want to perform a transaction.
For example, if we have several tables to change with an insert, what would happen if it fails in the middle of these inserts? We should be able to roll back, but unfortunately, we have already committed, and that doesn’t make sense.
public mysqli::autocommit(bool $mode): bool
The $mode
parameter is of type bool
and indicates whether it is enabled or not.
Typically, it is ensured that auto-commit is not enabled when performing a transaction, while it is used enabled for simple queries.
change_user
https://blastcoding.com/en/php-mysqli-class/#change_userChanges the user for the database connection.
There are occasions when we may want to change the user with which we connect to the database, as they may have different permissions
Descriptionpublic mysqli::change_user(string $user, string $password, string $database): boolSintaxis
$dbconnection->change_user($user, $password, $database);
Parameters
$user
– This is the name of the new database user that will connect.
$password
– Password of the user that will connect.
$database
– Database; if you do not want to change the database, you can pass null
.
Returns
true or false depending on whether the user change was successful.
character_set_name
https://blastcoding.com/en/php-mysqli-class/#character_set_nameReturns the character set of the database connection. See https://dev.mysql.com/doc/refman/8.0/en/charset.html for a better understanding of character sets.
Description / Descripciónpublic mysqli::character_set_name(): stringSintaxis
$dbconnection->character_set_name();
Returns
This method will return a string.
An example of the return value you will get is ‘latin1_swedish_ci’
close
This method will finalize the connection.
Description / Descripciónpublic mysqli::close(): bool
Returns
It will return true
or false
depending on whether it could not close the connection. If the connection is persistent, it will not be closed.
commit
https://blastcoding.com/en/php-mysqli-class/#commitCommits the current transaction.
Description / Descripciónpublic mysqli::commit(int $flags = ?, string $name = ?): bool
Returns
true
or false
depending on whether the transaction could be completed or not.
debug
https://blastcoding.com/en/php-mysqli-class/#debugPerforms a debug operation.
We may explore this in depth in the near future. Returns true
as the value.
public mysqli::debug(string $options): bool
$option
is a string that represents the different operations to be performed, with each operation separated by a colon.
PHP.net provides the following example, which uses an alias function; nevertheless, we will analyze this example.
Ejemplomysqli_debug("d:t:o,/tmp/client.trace");
Notice that our string is ‘d:t,/tmp/client.trace’; therefore, it will use option ‘d’, option ‘t’, and option ‘o’, which also has ‘,/tmp/client.trace’. This is the file where it will save the data for options ‘d’ and ‘t’. On the other hand, ‘o’ means output without specifying the operation, or this file would not be created.
How would the method be used when utilizing OOP?
Let’s suppose we already have a connection $dbconnection
.
$dbconnection->debug("d:t:o,/tmp/client.trace");
option character | Description |
---|---|
O | MYSQLND_DEBUG_FLUSH |
A/a | MYSQLND_DEBUG_APPEND |
F | MYSQLND_DEBUG_DUMP_FILE |
i | MYSQLND_DEBUG_DUMP_PID |
L | MYSQLND_DEBUG_DUMP_LINE |
m | MYSQLND_DEBUG_TRACE_MEMORY_CALLS |
n | MYSQLND_DEBUG_DUMP_LEVEL |
o | output to file |
T | MYSQLND_DEBUG_DUMP_TIME |
t | MYSQLND_DEBUG_DUMP_TRACE |
x | MYSQLND_DEBUG_PROFILE_CALLS |
In this table, what ‘d’ does is not found, but I have come across another source to learn about what these options do, as they are the same ones used in C/C++ debug.
This blog -> http://tiebing.blogspot.com/2011/10/cc-dbug-library.html
d :Enable output from DBUG_ macros for
for the current state. May be followed
by a list of keywords which selects output
only for the DBUG macros with that keyword.
A null list of keywords implies output for
all macros.
dump_debug_info
https://blastcoding.com/en/php-mysqli-class/#dump_debug_infoMakes a dump of the information while debugging in the log. In simple terms, it creates a dump (or copy, if you prefer) of what is happening in a log file.
The user utilizing this method should be a SUPERUSER or have the highest privileges for that database.
Description / Descripciónpublic mysqli::dump_debug_info(): bool
Returns
It returns true
if the dump can be made; otherwise, it will return false
(error).
get_charset
https://blastcoding.com/en/php-mysqli-class/#get_charsetReturns the character set as an object (stdClass
), which provides several properties of the character set:
public mysqli::get_charset(): ?object
Returns an object of type stdClass
with the following data:
state – Character set status (?)
charset – Character set name
collation – Collation name
dir – Directory the charset description was fetched from (?) or an empty string for built-in character sets
min_length – Minimum character length in bytes
max_length – Maximum character length in bytes
number – Internal character set number
get_client_info(En desuso desde PHP 8.1, use $client_info)
https://blastcoding.com/en/php-mysqli-class/#get_client_infoObtains information about the MySQL client; when this method is run, we will get a string representing the library of the MySQL client.
Description / Descripcionpublic mysqli::get_client_info(): string
Returns information about the MySQL client as a string.
get_connection_stats
https://blastcoding.com/en/php-mysqli-class/#get_connection_statsReturns statistics of the MySQL client connection. This data is very technical, and you will probably never use this method.
Description / Descripciónpublic mysqli::get_connection_stats(): array
Returns an array with the stats of the connection.
get_warnings
https://blastcoding.com/en/php-mysqli-class/#get_warningsObtains the result of running the SHOW WARNINGS
query in MySQL. The result is returned as a mysqli_warning
object.
mysql.com
SHOW WARNINGS
is a diagnostic statement that displays information about the conditions (errors, warnings, and notes) resulting from executing a statement in the current session.
It will return a mysqli_warning
object or false
in case of an error
public mysqli::get_warnings(): mysqli_warning|false
init(en des-uso vea __construct)
We will not cover this function/method.
kill
https://blastcoding.com/en/php-mysqli-class/#killRequests the MySQL server to terminate a thread process. This method is related to the thread_id
, as the process ID corresponds to this ID
public mysqli::kill(int $process_id): bool
Parameter
$process_id – This is the same ID that we can obtain with thread_id
Returns
true or false depending on whether the process could be terminated or not.
more_results
https://blastcoding.com/en/php-mysqli-class/#more_resultsChecks if there are more results from a multi_query
.
public mysqli::more_results(): bool
multi_query
https://blastcoding.com/en/php-mysqli-class/#multi_queryExecutes one or more queries to the database.
Description / Descripciónpublic mysqli::multi_query(string $query): bool
next_result
https://blastcoding.com/en/php-mysqli-class/#next_resultIt is the next result if multi_query
has been used. It must be used in conjunction with multi_query
.
public mysqli::next_result(): bool
options
https://blastcoding.com/en/php-mysqli-class/#optionsWith this method, we can set options that change the behavior for a connection. For example, we can specify that the connection lasts a certain amount of time; after all, we may not want to keep a connection always open as it consumes resources.
Description / Descripciónpublic mysqli::options(int $option, mixed $value): boolSintaxis
$dbconnection->options($option,$value);
Name | Description |
---|---|
MYSQLI_OPT_CONNECT_TIMEOUT | Connection timeout in seconds |
MYSQLI_OPT_READ_TIMEOUT | Command execution result timeout in seconds. Available as of PHP 7.2.0. |
MYSQLI_OPT_LOCAL_INFILE | Enable/disable use of LOAD LOCAL INFILE |
MYSQLI_INIT_COMMAND | Command to execute after when connecting to MySQL server |
MYSQLI_SET_CHARSET_NAME | The charset to be set as default. |
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf Not supported by mysqlnd. |
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. Not supported by mysqlnd. |
MYSQLI_SERVER_PUBLIC_KEY | RSA public key file used with the SHA-256 based authentication. |
MYSQLI_OPT_NET_CMD_BUFFER_SIZE | The size of the internal command/network buffer. Only valid for mysqlnd. |
MYSQLI_OPT_NET_READ_BUFFER_SIZE | Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd. |
MYSQLI_OPT_INT_AND_FLOAT_NATIVE | Convert integer and float columns back to PHP numbers. Only valid for mysqlnd. |
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT | Whether to verify server certificate or not. |
ping
https://blastcoding.com/en/php-mysqli-class/#pingPings the connection to the MySQL server; if the connection is down, it attempts to reconnect.
Description / Descripciónpublic mysqli::ping(): bool
If the ping or reconnection is successful, the return will be true
; otherwise, it will be false
.
prepare
https://blastcoding.com/en/php-mysqli-class/#prepareThis method allows us to create a prepared statement for execution. It returns a mysqli_stmt
object or false
in case of an error.
public mysqli::prepare(string $query): mysqli_stmt|false
query
https://blastcoding.com/en/php-mysqli-class/#queryAllows us to perform a query on our database; the query will be passed as a parameter in the form of a string.
Descripción / Descripciónpublic mysqli::query(string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool
Parameters
$query
– This will be the query that we pass to be executed on our database, and it must be a string, for example: "SELECT * FROM usuarios"
.
$result_mode
– Can be either MYSQLI_USE_RESULT
or MYSQLI_STORE_RESULT
.
Returns
This method will return a mysqli_result
object if the query is successfully executed and false
otherwise.
real_connect
https://blastcoding.com/en/php-mysqli-class/#real_connectOpens a connection to the MySQL server; this connection uses the connection established with the __construct
constructor.
public mysqli::real_connect( string $host = ?, string $username = ?, string $passwd = ?, string $dbname = ?, int $port = ?, string $socket = ?, int $flags = ? ): bool
Parameters
$host
– It can be an IP address or the hostname passed as a string. If null
or “localhost” is specified, its value will be that of the local host.
$username
– Username
$passwd
– Password
$dbname
– Name of the database
$port
– Port
$socket
– Socket
$flag
– Flag is one of the following:
Name | Description |
---|---|
MYSQLI_CLIENT_COMPRESS | Use compression protocol |
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows |
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words. |
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection |
MYSQLI_CLIENT_SSL | Use SSL (encryption) |
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT | Like MYSQLI_CLIENT_SSL, but disables validation of the provided SSL certificate. This is only for installations using MySQL Native Driver and MySQL 5.6 or later. |
Returns
true or false depending on whether the connection could be established or not.
real_escape_string / escape_string
https://blastcoding.com/en/php-mysqli-class/#real_escape_stringEscapes special characters in a string for use in an SQL statement, taking into account the current character set of the connection.
Description / Descripciónpublic mysqli::real_escape_string(string $string): string
Parameters
$string – This is the string that you want to escape.
Returns
Returns an escaped string.
Pay close attention to the following example from php.net.
Ejemplo de real_scape_string de [php.net]<?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $city = "'s-Hertogenbosch"; /* this query with escaped $city will work */ $query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $mysqli->real_escape_string($city)); $result = $mysqli->query($query); printf("Select returned %d rows.\n", $result->num_rows); /* this query will fail, because we didn't escape $city */ $query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city); $result = $mysqli->query($query);
In the example, mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
is used to ensure that the escaping function must be used. But what would happen if we didn’t use this escape? It could easily allow someone to delete all the data from our table.
For example, if I have a form where I input the value I’m searching for, but instead of passing a city name, I pass something like "'s-Hertogenbosch"
and instead enter something similar to weak";DROP TABLE City;
And our table disappears, meaning something like this
In the future, I believe we will talk about this.
There is a page that explains this topic very well, and it is https://portswigger.net/web-security/sql-injection.
real_query
https://blastcoding.com/en/php-mysqli-class/#real_queryExecutes an SQL query on our database. As we mentioned before, using query
with mysqli in PHP instead of prepare
can lead to significant problems with SQL injection attacks. It is recommended to use prepare
whenever we have inputs.
public mysqli::real_query(string $query): bool
reap_async_query
https://blastcoding.com/en/php-mysqli-class/#reap_async_queryRetrieves the result of an asynchronous query. To use this method, you will need the mysqlnd (MySQL Native Driver).
Description / Descripciónpublic mysqli::reap_async_query(): mysqli_result[obj]
Returns a mysqli_result object, or false in case of an error.
refresh(Deprecated by MySQL)
https://blastcoding.com/en/php-mysqli-class/#refreshPerforms a refresh operation, flushing tables or caches, or resetting replicated server information.
mysql_real_query()
.
rollback
https://blastcoding.com/en/php-mysqli-class/#rollbackReverts the ongoing transaction.
Description / Descripciónpublic mysqli::rollback(int $flags = 0, ?string $name = null): bool
select_db
https://blastcoding.com/en/php-mysqli-class/#select_dbSelects the database. Although it’s possible to change the default database for a query, it’s recommended to use this method only to set the connection database, which can already be done with the constructor method.
You can change the database of the connection as long as the user remains the same.
Description / Descripciónublic mysqli::select_db(string $database): bool
set_charset
https://blastcoding.com/en/php-mysqli-class/#set_charsetSetea el charset de la conexión cliente MySQL para data proveniente desde el servidor, como para data hacia el servidor.
Si necesitas saber las charset que puedes usar este link muestra todas las charset de MySQL posibles
Description / Descripciónpublic mysqli::set_charset(string $charset): bool
ssl_set
https://blastcoding.com/en/php-mysqli-class/#ssl_setssl_set es utilizado para establecer una conexión segura utilizando SSL.
Description / Descripciónpublic mysqli::ssl_set( ?string $key, ?string $certificate, ?string $ca_certificate, ?string $ca_path, ?string $cipher_algos ): bool
stat
https://blastcoding.com/en/php-mysqli-class/#statGets the current system status
public mysqli::stat(): string|false
stmt_init
https://blastcoding.com/en/php-mysqli-class/#stmt_initInitializes a prepared statement and creates a mysqli_stmt
object.
public mysqli::stmt_init(): mysqli_stmt|falseSintaxis
$stmt = $dbconnection->stmt_init();
store_result
https://blastcoding.com/en/php-mysqli-class/#store_resultTransfers a result set from the last executed query
Description / Descripciónpublic mysqli::store_result(int $mode = 0): mysqli_result|false
use_result
https://blastcoding.com/en/php-mysqli-class/#use_resultStarts retrieving a result set. Essentially, suppose you run a query and need the result later. This method will return the result of the last executed query
Description / Descripciónpublic mysqli::use_result(): mysqli_result|false