Chose Language:
comments
Author: Admin/Publisher |not finished |not checked

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

Sinopsis
class 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
}
contenido

Properites in PHP mysqli class

https://blastcoding.com/en/php-mysqli-class/#properties

In the properties, we will use the variable $dbconnection, which will be the connection obtained after instantiating the class.

mysqli class instance
$dbconnection = new mysqli('localhost', 'my_user', 'my_password', 'my_bd');
All these properties are readonly, so they cannot be changed. Their functionality is to quickly and effectively retrieve information.

affected_rows

https://blastcoding.com/en/php-mysqli-class/#affected_rows

Returns the number of rows affected in the last query

Sintaxis / Sintax
$dbconnection->affected_rows;

connect_errno

https://blastcoding.com/en/php-mysqli-class/#connect_errno

Error code from the last call.

Sintaxis
$dbconnection->connect_errno;

connect_error

https://blastcoding.com/en/php-mysqli-class/#connect_error

Returns a string with the description of the last connection error.

Sintaxis
$dbconnection->connect_error;

errno

https://blastcoding.com/en/php-mysqli-class/#errno

Error code from the last function call

Sintaxis
$dbconnection->errno;

error_list

https://blastcoding.com/en/php-mysqli-class/#error_list

List of errors since the last executed command.

Sintaxis
$dbconnection->error_list;

error

https://blastcoding.com/en/php-mysqli-class/#error

String that describes the last error.

Sintaxis
$dbconnection->error;

field_count

https://blastcoding.com/en/php-mysqli-class/#field_count

Number of columns for the most recent query.

Sintaxis
$dbconnection->field_count;

client_version

https://blastcoding.com/en/php-mysqli-class/#client_version

MySQL 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_info

String representing the type of connection used.

Sintaxis
$dbconnection->host_info;

protocol_version

https://blastcoding.com/en/php-mysqli-class/#protocol_version

Returns the version of the protocol used.

Sintaxis
$dbconnection->protocol_version;

server_info

https://blastcoding.com/en/php-mysqli-class/#server_info

MySQL server version returned as a string.

Sintaxis
$dbconnection->server_info;

server_version

https://blastcoding.com/en/php-mysqli-class/#server_version

MySQL server version as an integer

Sintaxis
$dbconnection->server_version;

info

https://blastcoding.com/en/php-mysqli-class/#info

Information about the most recent query executed.

Sintaxis
$dbconnection->info;

insert_id

https://blastcoding.com/en/php-mysqli-class/#insert_id

This 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/#sqlstate

The SQLSTATE error from a previous operation (query) in MySQL.

Sintaxis
$dbconnection->sqlstate;

thread_id

https://blastcoding.com/en/php-mysqli-class/#thread_id

The 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_count

It 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/#metodos

Here 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/#__construct

Opens a new connection to our MySQL server, creating our mysqli object that will represent this connection.

Description / Descripción
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/#autocommit

This 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.

It is recommended to use auto-commit with moderation and common sense.
Description
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_user

Changes 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

Description
public mysqli::change_user(string $user, string $password, string $database): bool
Sintaxis
$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_name

Returns 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ón
public mysqli::character_set_name(): string
Sintaxis
$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ón
public 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/#commit

Commits the current transaction.

Description / Descripción
public 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/#debug

Performs a debug operation.

We may explore this in depth in the near future. Returns true as the value.

Description[EN] / Descripción[ES]
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.

Ejemplo
mysqli_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.

Ejemplo utilizando POO(OOP[EN])
$dbconnection->debug("d:t:o,/tmp/client.trace");
Tabla de opciones
option characterDescription
O MYSQLND_DEBUG_FLUSH
A/a MYSQLND_DEBUG_APPEND
F MYSQLND_DEBUG_DUMP_FILE
i MYSQLND_DEBUG_DUMP_PID
LMYSQLND_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_info

Makes 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ón
public 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_charset

Returns the character set as an object (stdClass), which provides several properties of the character set:

Description / Descripción
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_info

Obtains information about the MySQL client; when this method is run, we will get a string representing the library of the MySQL client.

Description / Descripcion
public 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_stats

Returns statistics of the MySQL client connection. This data is very technical, and you will probably never use this method.

Description / Descripción
public mysqli::get_connection_stats(): array

Returns an array with the stats of the connection.

get_warnings

https://blastcoding.com/en/php-mysqli-class/#get_warnings

Obtains the result of running the SHOW WARNINGS query in MySQL. The result is returned as a mysqli_warning object.

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.

mysql.com

It will return a mysqli_warning object or false in case of an error

Description /Descripcion
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/#kill

Requests the MySQL server to terminate a thread process. This method is related to the thread_id, as the process ID corresponds to this ID

Description / Descripcion
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_results

Checks if there are more results from a multi_query.

Description / Descripción
public mysqli::more_results(): bool

multi_query

https://blastcoding.com/en/php-mysqli-class/#multi_query

Executes one or more queries to the database.

Description / Descripción
public mysqli::multi_query(string $query): bool

next_result

https://blastcoding.com/en/php-mysqli-class/#next_result

It is the next result if multi_query has been used. It must be used in conjunction with multi_query.

Description / Descripción
public mysqli::next_result(): bool

options

https://blastcoding.com/en/php-mysqli-class/#options

With 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ón
public mysqli::options(int $option, mixed $value): bool
Sintaxis
$dbconnection->options($option,$value);
NameDescription
MYSQLI_OPT_CONNECT_TIMEOUTConnection timeout in seconds
MYSQLI_OPT_READ_TIMEOUTCommand execution result timeout in seconds. Available as of PHP 7.2.0.
MYSQLI_OPT_LOCAL_INFILEEnable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMANDCommand to execute after when connecting to MySQL server
MYSQLI_SET_CHARSET_NAMEThe charset to be set as default.
MYSQLI_READ_DEFAULT_FILERead options from named option file instead of my.cnf Not supported by mysqlnd.
MYSQLI_READ_DEFAULT_GROUPRead options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. Not supported by mysqlnd.
MYSQLI_SERVER_PUBLIC_KEYRSA public key file used with the SHA-256 based authentication.
MYSQLI_OPT_NET_CMD_BUFFER_SIZEThe size of the internal command/network buffer. Only valid for mysqlnd.
MYSQLI_OPT_NET_READ_BUFFER_SIZEMaximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.
MYSQLI_OPT_INT_AND_FLOAT_NATIVEConvert integer and float columns back to PHP numbers. Only valid for mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERTWhether to verify server certificate or not.

ping

https://blastcoding.com/en/php-mysqli-class/#ping

Pings the connection to the MySQL server; if the connection is down, it attempts to reconnect.

Description / Descripción
 public 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/#prepare

This method allows us to create a prepared statement for execution. It returns a mysqli_stmt object or false in case of an error.

Description / Descripción
public mysqli::prepare(string $query): mysqli_stmt|false

query

https://blastcoding.com/en/php-mysqli-class/#query

Allows 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ón
public 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_connect

Opens a connection to the MySQL server; this connection uses the connection established with the __construct constructor.

Description / Descripción
 
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:

NameDescription
MYSQLI_CLIENT_COMPRESSUse compression protocol
MYSQLI_CLIENT_FOUND_ROWSreturn 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_SSLUse 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_string

Escapes special characters in a string for use in an SQL statement, taking into account the current character set of the connection.

Description / Descripción
public mysqli::real_escape_string(string $string): string

Parameters

$string – This is the string that you want to escape.

Returns

Returns an escaped string.

This function plays an important role in preventing code injections when using query or real_query.

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_query

Executes 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.

Description / Descripción
public mysqli::real_query(string $query): bool

reap_async_query

https://blastcoding.com/en/php-mysqli-class/#reap_async_query

Retrieves the result of an asynchronous query. To use this method, you will need the mysqlnd (MySQL Native Driver).

Description / Descripción
public 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/#refresh

Performs a refresh operation, flushing tables or caches, or resetting replicated server information.

This method has been deprecated by MySQL and should not be used. Instead, you are encouraged to use mysql_real_query().

rollback

https://blastcoding.com/en/php-mysqli-class/#rollback

Reverts the ongoing transaction.

Description / Descripción
public mysqli::rollback(int $flags = 0, ?string $name = null): bool

select_db

https://blastcoding.com/en/php-mysqli-class/#select_db

Selects 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ón
ublic mysqli::select_db(string $database): bool

set_charset

https://blastcoding.com/en/php-mysqli-class/#set_charset

Setea 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

https://dev.mysql.com/doc/refman/8.0/en/charset-charsets.html
Description / Descripción
 public mysqli::set_charset(string $charset): bool

ssl_set

https://blastcoding.com/en/php-mysqli-class/#ssl_set

ssl_set es utilizado para establecer una conexión segura utilizando SSL.

Description / Descripción
public 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/#stat

Gets the current system status

public mysqli::stat(): string|false

stmt_init

https://blastcoding.com/en/php-mysqli-class/#stmt_init

Initializes a prepared statement and creates a mysqli_stmt object.

Description / Descripción
public mysqli::stmt_init(): mysqli_stmt|false
Sintaxis
$stmt = $dbconnection->stmt_init();

store_result

https://blastcoding.com/en/php-mysqli-class/#store_result

Transfers a result set from the last executed query

Description / Descripción
public mysqli::store_result(int $mode = 0): mysqli_result|false

use_result

https://blastcoding.com/en/php-mysqli-class/#use_result

Starts 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ón
public mysqli::use_result(): mysqli_result|false
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments