MySQLi

Last updated

The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP scripting language to provide an interface with MySQL databases (MySQL, Percona Server and MariaDB). [1]

Contents

There are three main API options when considering connecting to a MySQL database server:

The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the MySQLi extension, and the MySQL extension, are implemented using the PHP extension framework. An extension typically exposes an API to the PHP developer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP developer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP developer, but provides an interface to the PDO layer above it.

MySQLi is an improved version of the older PHP MySQL driver, offering various benefits. [2]

The authors of the PHP scripting language recommend using MySQLi when dealing with MySQL server versions 4.1.3 and newer (takes advantage of new functionality). [2]

Technical details

The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which (according to the PHP website [2] ) are:

Comparison of features [2]

PHP's MySQLi ExtensionPDOPHP's MySQL Extension
PHP version introduced5.05.0pre-3.0
Included with PHP 5.xYesYesYes
Included with PHP 7.xYesYesNo
Development statusActive developmentActive development as of PHP 5.3Deprecated as of PHP 5.5
Removed in PHP 7.0
Recommended by MySQL for new projectsYes - preferred optionYesNo
API supports CharsetsYesYesNo
API supports server-side Prepared StatementsYesYesNo
API supports client-side Prepared StatementsNoYesNo
API supports Stored ProceduresYesYesNo
API supports Multiple StatementsYesMostNo
Supports all MySQL 4.1+ functionalityYesMostNo

Start guide [3]

Dual interface

The MySQLi extension features a dual interface - it supports both the procedural and object-oriented programming paradigms.

Users migrating from the old MySQL extension may prefer the procedural interface. The procedural interface is similar to that of the old MySQL extension. In many cases, the function names differ only by prefix. Some MySQLi functions take a connection handle as their first argument, whereas matching functions in the old MySQL interface took it as an optional last argument.

New and old native function calls

<?php$mysqli=mysqli_connect("example.com","user","password","database");$result=mysqli_query($mysqli,"SELECT * FROM myDatabase");echomysqli_num_rows($result);$mysql=mysql_connect("example.com","user","password");mysql_select_db("database");$result=mysql_query("SELECT * FROM myDatabase",$mysql);echomysql_num_rows($result);?>

Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead.

Example. Special meaning of localhost

<?php$mysqli=newmysqli("localhost","user","password","database");if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}echo$mysqli->host_info."\n";$mysqli=newmysqli("127.0.0.1","user","password","database",3306);if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}echo$mysqli->host_info."\n";?>

Output

Localhost via UNIX socket 127.0.0.1 via TCP/IP

Executing statements

Statements can be executed with the mysqli_query(), mysqli_real_query() and mysqli_multi_query() functions. The mysqli_query() function is the most common, and combines the executing statement with a buffered fetch of its result set, if any, in one call. Calling mysqli_query() is identical to calling mysqli_real_query() followed by mysqli_store_result().

Example: Connecting to MySQL

<?php$mysqli=newmysqli("example.com","user","password","database");if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}if(!$mysqli->query("DROP TABLE IF EXISTS test")||!$mysqli->query("CREATE TABLE test(id INT)")||!$mysqli->query("INSERT INTO test(id) VALUES (1)")){echo"Table creation failed: (".$mysqli->errno.") ".$mysqli->error;}?>

Buffered result sets

After statement execution results can be retrieved at once to be buffered by the client or by read row by row. Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli_query() combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Example: Navigation through buffered results

<?php$mysqli=newmysqli("example.com","user","password","database");if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}if(!$mysqli->query("DROP TABLE IF EXISTS test")||!$mysqli->query("CREATE TABLE test(id INT)")||!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")){echo"Table creation failed: (".$mysqli->errno.") ".$mysqli->error;}$res=$mysqli->query("SELECT id FROM test ORDER BY id ASC");echo"Reverse order...\n";for($row_no=$res->num_rows-1;$row_no>=0;$row_no--){$res->data_seek($row_no);$row=$res->fetch_assoc();echo" id = ".$row['id']."\n";}echo"Result set order...\n";$res->data_seek(0);while($row=$res->fetch_assoc()){echo" id = ".$row['id']."\n";}?>

The above example will output:

Reverse order...  id = 3  id = 2  id = 1 Result set order...  id = 1  id = 2  id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

Example: Navigation through unbuffered results

<?php$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");$res=$mysqli->use_result();echo"Result set order...\n";while($row=$res->fetch_assoc()){echo" id = ".$row['id']."\n";}?>

Result set values data types

The mysqli_query(), mysqli_real_query() and mysqli_multi_query() functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The MySQL client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

Example: Text protocol returns strings by default

<?php$mysqli=newmysqli("example.com","user","password","database");if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}if(!$mysqli->query("DROP TABLE IF EXISTS test")||!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))")||!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")){echo"Table creation failed: (".$mysqli->errno.") ".$mysqli->error;}$res=$mysqli->query("SELECT id, label FROM test WHERE id = 1");$row=$res->fetch_assoc();printf("id = %s (%s)\n",$row['id'],gettype($row['id']));printf("label = %s (%s)\n",$row['label'],gettype($row['label']));?>

The above example will output:

id = 1 (string) label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

Example: Native data types with mysqlnd and connection option

<?php$mysqli=mysqli_init();$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE,1);$mysqli->real_connect("example.com","user","password","database");if($mysqli->connect_errno){echo"Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;}if(!$mysqli->query("DROP TABLE IF EXISTS test")||!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))")||!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")){echo"Table creation failed: (".$mysqli->errno.") ".$mysqli->error;}$res=$mysqli->query("SELECT id, label FROM test WHERE id = 1");$row=$res->fetch_assoc();printf("id = %s (%s)\n",$row['id'],gettype($row['id']));printf("label = %s (%s)\n",$row['label'],gettype($row['label']));?>

The above example will output:

id = 1 (integer) label = a (string)

Prepared statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with ?.

See example in. [4]

Stored procedures [5]

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The MySQLi interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

See examples in. [5]

Multiple statements [6]

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Multiple statements or multi queries must be executed with mysqli_multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

See examples in [6]

API support for transactions [7]

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the auto commit mode and for committing and rolling back transactions.

Examples here. [7]

Metadata [8]

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the MySQLi interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

View more here. [8]

The MySQLi extension and persistent connections [2]

Persistent connection support was introduced in PHP 5.3 for the MySQLi extension. Support was already present in PDO MYSQL and ext/mysql. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.

Unlike the MySQL extension, MySQLi does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend p: to the hostname when connecting.

The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection "as is". Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.

The persistent connection of the MySQLi extension however provides built-in cleanup handling code. The cleanup carried out by MySQLi includes:

This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.

The MySQLi extension does this cleanup by automatically calling the C-API function mysql_change_user().

The automatic cleanup feature has advantages and disadvantages though. The advantage is that the developer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.

It is possible to switch off the automatic cleanup code, by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.

Note: The MySQLi extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

Related Research Articles

<span class="mw-page-title-main">MySQL</span> SQL database engine software

MySQL is an open-source relational database management system (RDBMS). Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language. A relational database organizes data into one or more data tables in which data may be related to each other; these relations help structure the data. SQL is a language that programmers use to create, modify and extract data from the relational database, as well as control user access to the database. In addition to relational databases and SQL, an RDBMS like MySQL works with an operating system to implement a relational database in a computer's storage system, manages users, allows for network access and facilitates testing database integrity and creation of backups.

<span class="mw-page-title-main">PostgreSQL</span> Free and open-source object relational database management system

PostgreSQL, also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. PostgreSQL features transactions with atomicity, consistency, isolation, durability (ACID) properties, automatically updatable views, materialized views, triggers, foreign keys, and stored procedures. It is supported on all major operating systems, including Linux, FreeBSD, OpenBSD, macOS, and Windows, and handles a range of workloads from single machines to data warehouses or web services with many concurrent users.

<span class="mw-page-title-main">SQL injection</span> Computer hacking technique

In computing, SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution. SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.

The SQL SELECT statement returns a result set of records, from one or more tables.

An SQL INSERT statement adds one or more records to any single table in a relational database.

In computing, a data source name is a string that has an associated data structure used to describe a connection to a data source. Most commonly used in connection with ODBC, DSNs also exist for JDBC and for other data access mechanisms. The term often overlaps with "connection string". Most systems do not make a distinction between DSNs or connection strings and the term can often be used interchangeably.

Code injection is the exploitation of a computer bug that is caused by processing invalid data. The injection is used by an attacker to introduce code into a vulnerable computer program and change the course of execution. The result of successful code injection can be disastrous, for example, by allowing computer viruses or computer worms to propagate.

A data control language (DCL) is a syntax similar to a computer programming language used to control access to data stored in a database (authorization). In particular, it is a component of Structured Query Language (SQL). Data Control Language is one of the logical group in SQL Commands. SQL is the standard language for relational database management systems. SQL statements are used to perform tasks such as insert data to a database, delete or update data in a database, or retrieve data from a database.

In a database, a view is the result set of a stored query, which can be queried in the same manner as a persistent database collection object. This pre-established query command is kept in the data dictionary. Unlike ordinary base tables in a relational database, a view does not form part of the physical schema: as a result set, it is a virtual table computed or collated dynamically from data in the database when access to that view is requested. Changes applied to the data in a relevant underlying table are reflected in the data shown in subsequent invocations of the view.

In computer science, a database cursor is a mechanism that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.

Set operations in SQL is a type of operations which allow the results of multiple queries to be combined into a single result set.

Gadfly is a relational database management system written in Python. Gadfly is a collection of Python modules that provides relational database functionality entirely implemented in Python. It supports a subset of the standard RDBMS Structured Query Language (SQL).

<span class="mw-page-title-main">MySQL Workbench</span> Database design graphical tool

MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation and maintenance into a single integrated development environment for the MySQL database system. It is the successor to DBDesigner 4 from fabFORCE.net, and replaces the previous package of software, MySQL GUI Tools Bundle.

A database connection is a facility in computer science that allows client software to talk to database server software, whether on the same machine or not. A connection is required to send commands and receive answers, usually in the form of a result set.

Microsoft SQL Server is a proprietary relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network. Microsoft markets at least a dozen different editions of Microsoft SQL Server, aimed at different audiences and for workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users.

CUBRID ( "cube-rid") is an open-source SQL-based relational database management system (RDBMS) with object extensions developed by CUBRID Corp. for OLTP. The name CUBRID is a combination of the two words cube and bridge, cube standing for a space for data and bridge standing for data bridge.

Java Database Connectivity (JDBC) is an application programming interface (API) for the Java programming language which defines how a client may access a database. It is a Java-based data access technology used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides methods to query and update data in a database, and is oriented toward relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host environment.

Circuit breaker is a design pattern used in software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.

In database management systems (DBMS), a prepared statement, parameterized statement, or parameterized query is a feature where the database pre-compiles SQL code and stores the results, separating it from data. Benefits of prepared statements are:

The syntax of the SQL programming language is defined and maintained by ISO/IEC SC 32 as part of ISO/IEC 9075. This standard is not freely available. Despite the existence of the standard, SQL code is not completely portable among different database systems without adjustments.

References

  1. "Connection to MySQL/MariaDB/Percona for PHP". Virtuozzo. Retrieved November 22, 2023.
  2. 1 2 3 4 5 "Overview - Manual". PHP. Retrieved August 11, 2014.
  3. "PHP: Quick start guide - Manual". In2.php.net. Retrieved August 11, 2014.
  4. "PHP: Prepared Statements - Manual". In2.php.net. Retrieved August 11, 2014.
  5. 1 2 Jonathon (May 24, 2013). "PHP: Stored Procedures - Manual". In2.php.net. Retrieved August 11, 2014.
  6. 1 2 eric dot noel at gmail dot com (March 31, 2014). "PHP: Multiple Statements - Manual". In2.php.net. Retrieved August 11, 2014.
  7. 1 2 "PHP: API support for transactions - Manual". In2.php.net. Retrieved August 11, 2014.
  8. 1 2 "PHP: Metadata - Manual". In2.php.net. Retrieved August 11, 2014.

Further reading