Apis PHP en
Apis PHP en
Preface
PHP is a server-side, HTML-embedded scripting language that may be used to create dynamic Web pages. It is available for most operating systems and Web servers, and can access most common databases, including MySQL. PHP may be run as a separate program or compiled as a module for use with the Apache Web server. PHP actually provides two different MySQL API extensions: mysql: Available for PHP versions 4 and 5, this extension is intended for use with MySQL versions prior to MySQL 4.1. This extension does not support the improved authentication protocol used in MySQL 4.1, nor does it support prepared statements or multiple statements. If you wish to use this extension with MySQL 4.1, you will likely want to configure the MySQL server to use the -old-passwords option (see Client does not support authentication protocol). This extension is documented on the PHP Web site at http://php.net/mysql. Chapter 2, MySQL Improved Extension (Mysqli) - Stands for MySQL, Improved; this extension is available only in PHP 5. It is intended for use with MySQL 4.1.1 and later. This extension fully supports the authentication protocol used in MySQL 5.0, as well as the Prepared Statements and Multiple Statements APIs. In addition, this extension provides an advanced, object-oriented programming interface. You can read the documentation for the mysqli extension at http://php.net/mysqli. Helpful article can be found at http://devzone.zend.com/node/view/id/686 and http://devzone.zend.com/node/view/id/687.
If you're experiencing problems with enabling both the mysql and the mysqli extension when building PHP on Linux yourself, see Chapter 7, Enabling Both mysql and mysqli in PHP. The PHP distribution and documentation are available from the PHP Web site. Portions of this section are Copyright (c) 1997-2008 the PHP Documentation Group This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution 3.0 License or later. A copy of the Creative Commons Attribution 3.0 license is distributed with this manual. The latest version is presently available at This material may be distributed only subject to the terms and conditio\ ns set forth in the Open Publication License, v1.0.8 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
iv
1.1. Installing/Configuring
Copyright 1997-2010 the PHP Documentation Group.
1.1.1. Requirements
Copyright 1997-2010 the PHP Documentation Group. In order to have these functions available, you must compile PHP with MySQL support.
1.1.2. Installation
Copyright 1997-2010 the PHP Documentation Group. For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installation directory. Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these versions provide. For that, use the MySQLi extension. If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.
1.1.2.1.1. PHP 4
Copyright 1997-2010 the PHP Documentation Group. The option --with-mysql is enabled by default. This default behavior may be disabled with the --without-mysql configure option. If MySQL is enabled without specifying the path to the MySQL install DIR, PHP will use the bundled MySQL client libraries. Users who run other applications that use MySQL (for example, auth-mysql) should not use the bundled library, but rather specify the path to MySQL's install directory, like so: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries installed by MySQL, thus avoiding any conflicts.
Client Library (libmysql) is no longer required in order to support connection to a MySQL database. The extensions mysql, mysqli, and PHP_PDO_MYSQL are all enabled by default in PHP 5.3.0+, and all use the MySQL Native Driver by default. In each case no further installation steps are required in order to use these extensions, although you may want to set some preferences in php.ini depending on your requirements.
1.1.2.2.1. PHP 4
Copyright 1997-2010 the PHP Documentation Group. The PHP MySQL extension is compiled into PHP.
Note
If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.
Warning
Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.
Note
If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset support.
Name mysql.allow_persistent mysql.max_persistent mysql.max_links mysql.trace_mode mysql.default_port mysql.default_socket mysql.default_host mysql.default_user mysql.default_password mysql.connect_timeout
Default "1" "-1" "-1" "0" NULL NULL NULL NULL NULL "60"
Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL
Changelog
For further details and definitions of the PHP_INI_* modes, see the configuration.changes.modes. Here's a short explanation of the configuration directives.
mysql.allow_persistent boolean mysql.max_persistent integer mysql.max_links integer mysql.trace_mode boolean mysql.default_port string
Whether to allow persistent connections to MySQL. The maximum number of persistent MySQL connections per process. The maximum number of MySQL connections per process, including persistent connections. Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0) The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant. The default socket name to use when connecting to a local database server if no other socket name is specified. The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in SQL safe mode. The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in SQL safe mode. The default password to use when connecting to the database server if no other password is specified. Doesn't apply in SQL safe mode. Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.
mysql.default_socket string mysql.default_host string mysql.default_user string mysql.default_password string mysql.connect_timeout integer
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime. Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect and mysql_pconnect functions. The following constants are defined:
The function mysql_fetch_array uses a constant for the different types of result arrays. The following constants are defined:
1.3. Examples
Copyright 1997-2010 the PHP Documentation Group.
1.3.1. Basic
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.
Note
Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE .
1.4.1. mysql_affected_rows
Copyright 1997-2010 the PHP Documentation Group. mysql_affected_rows Get number of affected rows in previous MySQL operation Description
int mysql_affected_rows(resource link_identifier);
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the number of affected rows on success, and -1 if the last query failed. If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2. When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally affected by the query. The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records. Examples
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'); printf("Records deleted: %d\n", mysql_affected_rows()); /* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'); printf("Records deleted: %d\n", mysql_affected_rows()); ?>
Updated Records: 10
Notes
Transactions
If you are using transactions, you need to call mysql_affected_rows after your INSERT, UPDATE, or DELETE query, not after the COMMIT.
SELECT Statements
To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows.
mysql_info
1.4.2. mysql_client_encoding
Copyright 1997-2010 the PHP Documentation Group. mysql_client_encoding Returns the name of the character set Description
string mysql_client_encoding(resource link_identifier);
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the default character set name for the current connection. Examples
1.4.3. mysql_close
Copyright 1997-2010 the PHP Documentation Group. mysql_close 7
mysql_close closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used. Using mysql_close isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Connected successfully
Notes
Note
mysql_close will not close persistent links created by mysql_pconnect. See Also mysql_connect mysql_free_result
1.4.4. mysql_connect
8
Copyright 1997-2010 the PHP Documentation Group. mysql_connect Open a connection to a MySQL Server Description
resource mysql_connect(string server= =ini_get("mysql.default_host"), string username= =ini_get("mysql.default_user"), string password= =ini_get("mysql.default_password"), bool new_link= =false, int client_flags= =0);
server
The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.
The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used. The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used. If a second call is made to mysql_connect with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect always open a new link, even if mysql_connect was called before with the same parameters. In SQL safe mode, this parameter is ignored. The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL , MYSQL_CLIENT_COMPRESS , MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . Read the section about Table 1.2, MySQL client constants for further information. In SQL safe mode, this parameter is ignored.
client_flags
Return Values Returns a MySQL link identifier on success or FALSE on failure. Changelog Version 4.3.0 4.2.0 Examples Description Added the client_flags parameter. Added the new_link parameter.
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?>
Notes
Note
Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as mysql.default_host string in your PHP configuration and leave the server field blank.
Note
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close. 10
Note
You can suppress the error message on failure by prepending a @ to the function name.
Note
Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. See Also mysql_pconnect mysql_close
1.4.5. mysql_create_db
Copyright 1997-2010 the PHP Documentation Group. mysql_create_db Create a MySQL database Description
bool mysql_create_db(string database_name, resource link_identifier);
mysql_create_db attempts to create a new database on the server associated with the specified link identifier. Parameters
database_name link_identifier
The name of the database being created. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
11
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_createdb
Note
This function will not be available if the MySQL extension was built against a MySQL 4.x client library. See Also mysql_query mysql_select_db
1.4.6. mysql_data_seek
Copyright 1997-2010 the PHP Documentation Group. mysql_data_seek Move internal result pointer Description
bool mysql_data_seek(resource result, int row_number);
mysql_data_seek moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc, would return that row. row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows - 1. However if the result set is empty (mysql_num_rows == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek will return FALSE . Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query. The desired row number of the new result pointer.
12
Notes
Note
The function mysql_data_seek can be used in conjunction only with mysql_query, not with mysql_unbuffered_query. See Also mysql_query mysql_num_rows mysql_fetch_row mysql_fetch_assoc mysql_fetch_array mysql_fetch_object
1.4.7. mysql_db_name
Copyright 1997-2010 the PHP Documentation Group. mysql_db_name Get result data Description
string mysql_db_name(resource result, int row, mixed field);
13
The result pointer from a call to mysql_list_dbs. The index into the result set. The field name.
Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error to determine the nature of the error. Examples
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_dbname See Also mysql_list_dbs mysql_tablename
1.4.8. mysql_db_query
Copyright 1997-2010 the PHP Documentation Group. mysql_db_query Send a MySQL query Description
resource mysql_db_query(string database, string query, resource link_identifier);
Warning
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. 14
Parameters
database query
The name of the database that will be selected. The MySQL query. Data inside the query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE / FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure. Changelog Version 5.3.0 4.0.6 Description This function now throws an E_DEPRECATED notice. This function is deprecated, do not use this function. Use mysql_select_db and mysql_query instead.
Examples
Notes
Note
Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db instead of this function. 15
1.4.9. mysql_drop_db
Copyright 1997-2010 the PHP Documentation Group. mysql_drop_db Drop (delete) a MySQL database Description
bool mysql_drop_db(string database_name, resource link_identifier);
mysql_drop_db attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query to issue an sql DROP DATABASE statement instead. Parameters
database_name link_identifier
The name of the database that will be deleted. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Notes
Warning
This function will not be available if the MySQL extension was built against a MySQL 4.x client library.
16
Note
For backward compatibility, the following deprecated alias may be used: mysql_dropdb See Also mysql_query
1.4.10. mysql_errno
Copyright 1997-2010 the PHP Documentation Group. mysql_errno Returns the numerical value of the error message from previous MySQL operation Description
int mysql_errno(resource link_identifier);
Returns the error number from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error and mysql_errno), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the error number from the last MySQL function, or 0 (zero) if no error occurred. Examples
17
1.4.11. mysql_error
Copyright 1997-2010 the PHP Documentation Group. mysql_error Returns the text of the error message from previous MySQL operation Description
string mysql_error(resource link_identifier);
Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error and mysql_errno), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the error text from the last MySQL function, or '' (empty string) if no error occurred. Examples
18
1.4.12. mysql_escape_string
Copyright 1997-2010 the PHP Documentation Group. mysql_escape_string Escapes a string for use in a mysql_query Description
string mysql_escape_string(string unescaped_string);
This function will escape the unescaped_string, so that it is safe to place it in a mysql_query. This function is deprecated. This function is identical to mysql_real_escape_string except that mysql_real_escape_string takes a connection handler and escapes the string according to the current character set. mysql_escape_string does not take a connection argument and does not respect the current charset setting.
Warning
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. Parameters
unescaped_string Return Values Returns the escaped string. Changelog Version 5.3.0 4.3.0
Description This function now throws an E_DEPRECATED notice. This function became deprecated, do not use this function. Instead, use mysql_real_escape_string.
Examples
19
Notes
Note
mysql_escape_string does not escape % and _. See Also mysql_real_escape_string addslashes The magic_quotes_gpc directive.
1.4.13. mysql_fetch_array
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both Description
array mysql_fetch_array(resource result, int result_type= =MYSQL_BOTH);
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters
result result_type
The result resource that is being evaluated. This result comes from a call to mysql_query. The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC , MYSQL_NUM , and MYSQL_BOTH .
Return Values Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC , you only get associative indices (as mysql_fetch_assoc works), using MYSQL_NUM , you only get number indices (as mysql_fetch_row works). If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name. Examples
20
Notes
Performance
An important thing to note is that using mysql_fetch_array is not significantly slower than using mysql_fetch_row, while it provides a significant added value.
Note
Field names returned by this function are case-sensitive.
21
Note
This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_row mysql_fetch_assoc mysql_data_seek mysql_query
1.4.14. mysql_fetch_assoc
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_assoc Fetch a result row as an associative array Description
array mysql_fetch_assoc(resource result);
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc is equivalent to calling mysql_fetch_array with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query.
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row or add alias names. See the example at the mysql_fetch_array description about aliases. Examples
22
} if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } // While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } mysql_free_result($result); ?>
Notes
Performance
An important thing to note is that using mysql_fetch_assoc is not significantly slower than using mysql_fetch_row, while it provides a significant added value.
Note
Field names returned by this function are case-sensitive.
Note
This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_row mysql_fetch_array mysql_data_seek mysql_query mysql_error
1.4.15. mysql_fetch_field
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_field Get column information from a result and return as an object Description
object mysql_fetch_field(resource result, int field_offset= =0);
Returns an object containing field information. This function can be used to obtain information about fields in the provided query result. Parameters
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.
23
Return Values Returns an object containing field information. The properties of the object are:
name - column name table - name of the table the column belongs to max_length - maximum length of the column not_null - 1 if the column cannot be NULL primary_key - 1 if the column is a primary key unique_key - 1 if the column is a unique key multiple_key - 1 if the column is a non-unique key numeric - 1 if the column is numeric blob - 1 if the column is a BLOB type - the type of the column unsigned - 1 if the column is unsigned zerofill - 1 if the column is zero-filled
Examples
24
Notes
Note
Field names returned by this function are case-sensitive. See Also mysql_field_seek
1.4.16. mysql_fetch_lengths
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_lengths Get the length of each output in a result Description
array mysql_fetch_lengths(resource result);
Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL. mysql_fetch_lengths stores the lengths of each result column in the last row returned by mysql_fetch_row, mysql_fetch_assoc, mysql_fetch_array, and mysql_fetch_object in an array, starting at offset 0. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query.
25
1.4.17. mysql_fetch_object
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_object Fetch a result row as an object Description
object mysql_fetch_object(resource result, string class_name, array params);
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query. The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned. An optional array of parameters to pass to the constructor for class_name objects.
Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows. Changelog Version 5.0.0 Examples Description Added the ability to return as a different object.
26
$result = mysql_query("select * from mytable"); while ($row = mysql_fetch_object($result)) { echo $row->user_id; echo $row->fullname; } mysql_free_result($result); ?>
Notes
Performance
Speed-wise, the function is identical to mysql_fetch_array, and almost as quick as mysql_fetch_row (the difference is insignificant).
Note
mysql_fetch_object is similar to mysql_fetch_array, with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Note
Field names returned by this function are case-sensitive.
Note
This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_row mysql_data_seek mysql_query
1.4.18. mysql_fetch_row
Copyright 1997-2010 the PHP Documentation Group. mysql_fetch_row Get a result row as an enumerated array
27
Description
array mysql_fetch_row(resource result);
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query.
Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows. mysql_fetch_row fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. Examples
Notes
Note
This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_result
1.4.19. mysql_field_flags
Copyright 1997-2010 the PHP Documentation Group. mysql_field_flags Get the flags associated with the specified field in a result Description 28
mysql_field_flags returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode. Parameters
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
Return Values Returns a string of flags associated with the result or FALSE on failure. The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp". Examples
not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment )
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_fieldflags See Also mysql_field_type mysql_field_len
29
1.4.20. mysql_field_len
Copyright 1997-2010 the PHP Documentation Group. mysql_field_len Returns the length of the specified field Description
int mysql_field_len(resource result, int field_offset);
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
Return Values The length of the specified field index on success or FALSE on failure. Examples
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_fieldlen See Also mysql_fetch_lengths strlen
1.4.21. mysql_field_name
Copyright 1997-2010 the PHP Documentation Group.
30
Description
string mysql_field_name(resource result, int field_offset);
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
Return Values The name of the specified field index on success or FALSE on failure. Examples
user_id password
Notes
Note
Field names returned by this function are case-sensitive.
Note
31
For backward compatibility, the following deprecated alias may be used: mysql_fieldname See Also mysql_field_type mysql_field_len
1.4.22. mysql_field_seek
Copyright 1997-2010 the PHP Documentation Group. mysql_field_seek Set result pointer to a specified field offset Description
bool mysql_field_seek(resource result, int field_offset);
Seeks to the specified field offset. If the next call to mysql_fetch_field doesn't include a field offset, the field offset specified in mysql_field_seek will be returned. Parameters
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
Return Values Returns TRUE on success or FALSE on failure. See Also mysql_fetch_field
1.4.23. mysql_field_table
Copyright 1997-2010 the PHP Documentation Group. mysql_field_table Get name of the table the specified field is in Description
string mysql_field_table(resource result, int field_offset);
Returns the name of the table that the specified field is in. Parameters
32
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
<?php $query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = countr // get the result from the DB $result = mysql_query($query); // Lists the table name and then the field name for ($i = 0; $i < mysql_num_fields($result); ++$i) { $table = mysql_field_table($result, $i); $field = mysql_field_name($result, $i); echo "$table: $field\n"; } ?>
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_fieldtable See Also mysql_list_tables
1.4.24. mysql_field_type
Copyright 1997-2010 the PHP Documentation Group. mysql_field_type Get the type of the specified field in a result Description
string mysql_field_type(resource result, int field_offset);
mysql_field_type is similar to the mysql_field_name function. The arguments are identical, but the field type is returned instead. Parameters
result field_offset
The result resource that is being evaluated. This result comes from a call to mysql_query. The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. 33
Return Values The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation. Examples
Your 'func' table has 4 fields and 1 record(s) The table has the following fields: string name 64 not_null primary_key binary int ret 1 not_null string dl 128 not_null string type 9 not_null enum
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_fieldtype See Also mysql_field_name mysql_field_len
1.4.25. mysql_free_result
Copyright 1997-2010 the PHP Documentation Group. mysql_free_result Free result memory Description
bool mysql_free_result(resource result);
34
mysql_free_result will free all memory associated with the result identifier result. mysql_free_result only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query.
Returns TRUE on success or FALSE on failure. If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries. Examples
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_freeresult See Also mysql_query is_resource
1.4.26. mysql_get_client_info
Copyright 1997-2010 the PHP Documentation Group. mysql_get_client_info Get MySQL client info Description
string mysql_get_client_info();
35
mysql_get_client_info returns a string that represents the client library version. Return Values The MySQL client version. Examples
1.4.27. mysql_get_host_info
Copyright 1997-2010 the PHP Documentation Group. mysql_get_host_info Get MySQL host info Description
string mysql_get_host_info(resource link_identifier);
Describes the type of connection in use for the connection, including the server host name. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure. Examples
36
1.4.28. mysql_get_proto_info
Copyright 1997-2010 the PHP Documentation Group. mysql_get_proto_info Get MySQL protocol info Description
int mysql_get_proto_info(resource link_identifier);
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the MySQL protocol on success or FALSE on failure. Examples
37
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } printf("MySQL protocol version: %s\n", mysql_get_proto_info()); ?>
1.4.29. mysql_get_server_info
Copyright 1997-2010 the PHP Documentation Group. mysql_get_server_info Get MySQL server info Description
string mysql_get_server_info(resource link_identifier);
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns the MySQL server version on success or FALSE on failure. Examples
38
1.4.30. mysql_info
Copyright 1997-2010 the PHP Documentation Group. mysql_info Get information about the most recent query Description
string mysql_info(resource link_identifier);
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE . Examples
39
Notes
Note
mysql_info returns a non- FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement. See Also mysql_affected_rows mysql_insert_id mysql_stat
1.4.31. mysql_insert_id
Copyright 1997-2010 the PHP Documentation Group. mysql_insert_id Get the ID generated in the last query Description
int mysql_insert_id(resource link_identifier);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established. Examples
40
Notes
Caution
mysql_insert_id will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.
Note
Because mysql_insert_id acts on the last performed query, be sure to call mysql_insert_id immediately after the query that generates the value.
Note
The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries. See Also mysql_query mysql_info
1.4.32. mysql_list_dbs
Copyright 1997-2010 the PHP Documentation Group. mysql_list_dbs List databases available on a MySQL server Description
resource mysql_list_dbs(resource link_identifier);
Returns a result pointer containing the databases available from the current mysql daemon. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array. Examples
41
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_listdbs See Also mysql_db_name mysql_select_db
1.4.33. mysql_list_fields
Copyright 1997-2010 the PHP Documentation Group. mysql_list_fields List MySQL table fields Description
resource mysql_list_fields(string database_name, string table_name, resource link_identifier);
Retrieves information about the given table name. This function is deprecated. It is preferable to use mysql_query to issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead. Parameters
The name of the database that's being queried. The name of the table that's being queried. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
The returned result can be used with mysql_field_flags, mysql_field_len, mysql_field_name and mysql_field_type. Examples
Array ( [Field] => id [Type] => int(7) [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) Array ( [Field] => email [Type] => varchar(100) [Null] => [Key] => [Default] => [Extra] => )
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_listfields See Also mysql_field_flags mysql_info
1.4.34. mysql_list_processes
Copyright 1997-2010 the PHP Documentation Group. mysql_list_processes List MySQL processes Description 43
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
1.4.35. mysql_list_tables
Copyright 1997-2010 the PHP Documentation Group. mysql_list_tables List tables in a MySQL database Description
resource mysql_list_tables(string database, resource link_identifier);
44
Retrieves a list of table names from a MySQL database. This function is deprecated. It is preferable to use mysql_query to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. Parameters
database link_identifier
The name of the database The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values A result pointer resource on success or FALSE on failure. Use the mysql_tablename function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array. Changelog Version 4.3.7 Examples Description This function became deprecated.
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_listtables See Also mysql_list_dbs 45
mysql_tablename
1.4.36. mysql_num_fields
Copyright 1997-2010 the PHP Documentation Group. mysql_num_fields Get number of fields in result Description
int mysql_num_fields(resource result);
The result resource that is being evaluated. This result comes from a call to mysql_query.
Returns the number of fields in the result set resource on success or FALSE on failure. Examples
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_numfields See Also mysql_select_db mysql_query mysql_fetch_field mysql_num_rows
1.4.37. mysql_num_rows
Copyright 1997-2010 the PHP Documentation Group.
46
Description
int mysql_num_rows(resource result);
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows. Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query.
Notes
Note
If you use mysql_unbuffered_query, mysql_num_rows will not return the correct value until all the rows in the result set have been retrieved.
Note
For backward compatibility, the following deprecated alias may be used: mysql_numrows See Also mysql_affected_rows mysql_connect mysql_data_seek mysql_select_db mysql_query
1.4.38. mysql_pconnect
Copyright 1997-2010 the PHP Documentation Group.
47
Description
resource mysql_pconnect(string server= =ini_get("mysql.default_host"), string username= =ini_get("mysql.default_user"), string password= =ini_get("mysql.default_password"), int client_flags);
Establishes a persistent connection to a MySQL server. mysql_pconnect acts very much like mysql_connect with two major differences. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close will not close links established by mysql_pconnect). This type of link is therefore called 'persistent'. Parameters
server
The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'
The username. Default value is the name of the user that owns the server process. The password. Default value is an empty password. The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL , MYSQL_CLIENT_COMPRESS , MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE .
Return Values Returns a MySQL persistent link identifier on success, or FALSE on failure. Changelog Version 4.3.0 Notes Description Added the client_flags parameter.
Note
Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.
Warning
Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.
48
Note
You can suppress the error message on failure by prepending a @ to the function name. See Also mysql_connect Persistent Database Connections
1.4.39. mysql_ping
Copyright 1997-2010 the PHP Documentation Group. mysql_ping Ping a server connection or reconnect if there is no connection Description
bool mysql_ping(resource link_identifier);
Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.
Note
Since MySQL 5.0.13, automatic reconnection feature is disabled. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE . Examples
49
1.4.40. mysql_query
Copyright 1997-2010 the PHP Documentation Group. mysql_query Send a MySQL query Description
resource mysql_query(string query, resource link_identifier);
mysql_query sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier. Parameters
query
An SQL query The query string should not end with a semicolon. Data inside the query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query returns TRUE on success or FALSE on error. The returned result resource should be passed to mysql_fetch_array, and other functions for dealing with result tables, to access the returned data. Use mysql_num_rows to find out how many rows were returned for a SELECT statement or mysql_affected_rows to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement. mysql_query will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. Examples
The following query is syntactically invalid, so mysql_query fails and returns FALSE .
<?php $result = mysql_query('SELECT * WHERE 1=1'); if (!$result) { die('Invalid query: ' . mysql_error()); } ?>
1.4.41. mysql_real_escape_string
Copyright 1997-2010 the PHP Documentation Group. mysql_real_escape_string Escapes special characters in a string for use in an SQL statement
51
Description
string mysql_real_escape_string(string unescaped_string, resource link_identifier);
Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query. If binary data is to be inserted, this function must be used. mysql_real_escape_string calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. Parameters
unescaped_string link_identifier
The string that is to be escaped. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
52
Note
A MySQL connection is required before using mysql_real_escape_string otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.
Note
If magic_quotes_gpc is enabled, first apply stripslashes to the data. Using this function on data which has already been escaped will escape the data twice.
Note
If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.
Note
mysql_real_escape_string does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE. See Also mysql_client_encoding addslashes stripslashes The magic_quotes_gpc directive The magic_quotes_runtime directive
1.4.42. mysql_result
Copyright 1997-2010 the PHP Documentation Group. mysql_result Get result data Description
string mysql_result(resource result, int row, mixed field= =0);
Retrieves the contents of one cell from a MySQL result set. When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result. Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument. Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query.
53
row field
The row number from the result that's being retrieved. Row numbers start at 0. The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.
Return Values The contents of one cell from a MySQL result set on success, or FALSE on failure. Examples
Notes
Note
Calls to mysql_result should not be mixed with calls to other functions that deal with the result set. See Also mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object
1.4.43. mysql_select_db
Copyright 1997-2010 the PHP Documentation Group. mysql_select_db Select a MySQL database Description
bool mysql_select_db(string database_name, resource link_identifier);
Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to
54
database_name link_identifier
The name of the database that is to be selected. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Notes
Note
For backward compatibility, the following deprecated alias may be used: mysql_selectdb See Also mysql_connect mysql_pconnect mysql_query
1.4.44. mysql_set_charset
Copyright 1997-2010 the PHP Documentation Group. mysql_set_charset Sets the client character set Description
bool mysql_set_charset(string charset, resource link_identifier);
55
Parameters
charset link_identifier
A valid character set name. The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Note
This function requires MySQL 5.0.7 or later.
Note
This is the preferred way to change the charset. Using mysql_query to execute SET NAMES .. is not recommended. See Also mysql_client_encoding List of character sets that MySQL supports
1.4.45. mysql_stat
Copyright 1997-2010 the PHP Documentation Group. mysql_stat Get current system status Description
string mysql_stat(resource link_identifier);
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the SHOW STATUS SQL command. If link_identifier is invalid, NULL is returned. Examples
56
Uptime: 5380 Threads: 2 Questions: 1321299 Slow queries: 0 Opens: 26 Flush tables: 1 Open tables: 17 Queries per second avg: 245.595
back_log = 50 basedir = /usr/local/ bdb_cache_size = 8388600 bdb_log_buffer_size = 32768 bdb_home = /var/db/mysql/ bdb_max_lock = 10000 bdb_logdir = bdb_shared_data = OFF bdb_tmpdir = /var/tmp/ ...
1.4.46. mysql_tablename
Copyright 1997-2010 the PHP Documentation Group.
57
Description
string mysql_tablename(resource result, int i);
Retrieves the table name from a result. This function is deprecated. It is preferable to use mysql_query to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. Parameters
A result pointer resource that's returned from mysql_list_tables. The integer index (row/table number)
The name of the table on success or FALSE on failure. Use the mysql_tablename function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array. Examples
Notes
Note
The mysql_num_rows function may be used to determine the number of tables in the result pointer. See Also mysql_list_tables mysql_field_table mysql_db_name
1.4.47. mysql_thread_id
Copyright 1997-2010 the PHP Documentation Group.
58
Description
int mysql_thread_id(resource link_identifier);
Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping is executed, the thread ID will change. This means only retrieve the thread ID when needed. Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
current thread id is 73
1.4.48. mysql_unbuffered_query
Copyright 1997-2010 the PHP Documentation Group. mysql_unbuffered_query Send an SQL query to MySQL without fetching and buffering the result rows.
59
Description
resource mysql_unbuffered_query(string query, resource link_identifier);
mysql_unbuffered_query sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query while multiple database connections are open, you must specify the optional parameter link_identifier to identify which connection you want to use. Parameters
query
The SQL query to execute. Data inside the query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query returns a resource on success, or FALSE on error. For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query returns TRUE on success or FALSE on error. Notes
Note
The benefits of mysql_unbuffered_query come at a cost: you cannot use mysql_num_rows and mysql_data_seek on a result set returned from mysql_unbuffered_query. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL. See Also mysql_query
60
2.1. Examples
Copyright 1997-2010 the PHP Documentation Group. All examples in the mysqli documentation use the world database. The world database can be found at http://downloads.mysql.com/docs/world.sql.gz
2.2. Overview
Copyright 1997-2010 the PHP Documentation Group. This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database. What is an API? An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions. APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organised code. When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application. What is a Connector? In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP. If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server. What is a Driver? A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server. By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server. Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term driver is reserved for software that provides the database-specific part of a connector package.
61
What is an Extension? In the PHP documentation you will come across another term - extension. 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 programmer, 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 programmer. The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it. The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer. What are the main PHP API offerings for using MySQL? There are three main API options when considering connecting to a MySQL database server: PHP's MySQL Extension PHP's mysqli Extension PHP Data Objects (PDO)
Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API. What is PHP's MySQL Extension? This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.
Note
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead. The mysql extension source code is located in the PHP extension directory ext/mysql. For further information on the mysql extension, see Chapter 1, MySQL Extension (mysql). What is PHP's mysqli Extension? The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later. The mysqli extension has a number of benefits, the key enhancements over the mysql extension being: Object-oriented interface Support for Prepared Statements Support for Multiple Statements Support for Transactions Enhanced debugging capabilities Embedded server support
Note
62
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension. As well as the object-oriented interface the extension also provides a procedural interface. The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli. For further information on the mysqli extension, see Chapter 2, MySQL Improved Extension (Mysqli). What is PDO? PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code. Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl. While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements. PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo. For further information on PDO, see the Chapter 4, MySQL Functions (PDO_MYSQL). What is the PDO MYSQL driver? The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server. The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers. The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/ pdo_mysql. It does not expose an API to the PHP programmer. For further information on the PDO MYSQL driver, see Chapter 4, MySQL Functions (PDO_MYSQL). What is PHP's MySQL Native Driver? In order to communicate with the MySQL database server the mysql extension, mysqli and the PDO MYSQL driver each use a lowlevel library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as libmysql. However, the interface presented by libmysql was not optimized for communication with PHP applications, as libmysql was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysql for PHP applications. The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql. You are strongly encouraged to take advantage of these improvements.
Note
The MySQL Native Driver can only be used with MySQL server versions 4.1.3 and later. The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer. Comparison of Features The following table compares the functionality of the three main methods of connecting to MySQL from PHP:
63
PDO (Using PDO MySQL Driver and MySQL Native Driver) 5.0 yes Active development as of PHP 5.3 Yes Yes Yes Yes Yes Most Most
PHP version introduced Included with PHP 5.x MySQL development status Recommended by MySQL for new projects API supports Charsets API supports server-side Prepared Statements API supports client-side Prepared Statements API supports Multiple Statements
2.3. Installing/Configuring
Copyright 1997-2010 the PHP Documentation Group.
2.3.1. Requirements
Copyright 1997-2010 the PHP Documentation Group. In order to have these functions available, you must compile PHP with support for the mysqli extension.
Note
The mysqli extension is designed to work with MySQL version 4.1.13 or newer, or 5.0.7 or newer. For previous versions, please see the MySQL extension documentation.
2.3.2. Installation
Copyright 1997-2010 the PHP Documentation Group. The mysqli extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.
64
If building from source code, to ensure that the mysqli extension for PHP is enabled, you will need to configure the PHP source code to use mysqli. This is achieved by running the configure script with the option -with-mysqli=mysql_config_path/mysql_config, prior to building PHP. This will enable mysqli and it will use the MySQL Client Library (libmysql) to communicate with the MySQL Server. The mysql_config_path represents the location of the mysql_config program that comes with MySQL Server.
Note
If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysqli.dll'", this is because php_mysqli.dll and/or libmysql.dll cannot be found by the system.
65
For further details and definitions of the preceding PHP_INI_* constants, see the chapter on configuration changes. Here's a short explanation of the configuration directives.
Enable the ability to create persistent connections using mysqli_connect. Maximum of persistent connections that can be made. Set to 0 for unlimited. The maximum number of MySQL connections per process. The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant. The default socket name to use when connecting to a local database server if no other socket name is specified. The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode. The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode. The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.
66
mysqli.reconnect integer
mysqli.allow_local_infil mysqli.cache_size integer Available only with mysqlnd. e integer Users cannot set MYSQL_OPT_READ_TIMEOUT through an API call or runtime configuration setting. Note that if it were possible there would be differences between how libmysql and streams would interpret the value of MYSQL_OPT_READ_TIMEOUT.
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 programmer 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 Lib67
rary.
MYSQLI_CLIENT_INTERACTIV Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity E before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable. MYSQLI_CLIENT_IGNORE_SPA Allow spaces after function names. Makes all functions names reserved words. CE MYSQLI_CLIENT_NO_SCHEMA Don't allow the db_name.tbl_name.col_name syntax. MYSQLI_CLIENT_MULTI_QUER Allows multiple semicolon-delimited queries in a single mysqli_query call. IES MYSQLI_STORE_RESULT For using buffered resultsets MYSQLI_USE_RESULT MYSQLI_ASSOC MYSQLI_NUM MYSQLI_BOTH MYSQLI_NOT_NULL_FLAG MYSQLI_PRI_KEY_FLAG MYSQLI_UNIQUE_KEY_FLAG For using unbuffered resultsets Columns are returned into the array having the fieldname as the array index. Columns are returned into the array having an enumerated index. Columns are returned into the array having both a numerical index and the fieldname as the associative index. Indicates that a field is defined as NOT NULL Field is part of a primary index Field is part of a unique index.
MYSQLI_MULTIPLE_KEY_FLAG Field is part of an index. MYSQLI_BLOB_FLAG MYSQLI_UNSIGNED_FLAG MYSQLI_ZEROFILL_FLAG Field is defined as BLOB Field is defined as UNSIGNED Field is defined as ZEROFILL
MYSQLI_AUTO_INCREMENT_FL Field is defined as AUTO_INCREMENT AG MYSQLI_TIMESTAMP_FLAG Field is defined as TIMESTAMP MYSQLI_SET_FLAG MYSQLI_NUM_FLAG Field is defined as SET Field is defined as NUMERIC
68
MYSQLI_PART_KEY_FLAG MYSQLI_GROUP_FLAG MYSQLI_TYPE_DECIMAL MYSQLI_TYPE_NEWDECIMAL MYSQLI_TYPE_BIT MYSQLI_TYPE_TINY MYSQLI_TYPE_SHORT MYSQLI_TYPE_LONG MYSQLI_TYPE_FLOAT MYSQLI_TYPE_DOUBLE MYSQLI_TYPE_NULL MYSQLI_TYPE_TIMESTAMP MYSQLI_TYPE_LONGLONG MYSQLI_TYPE_INT24 MYSQLI_TYPE_DATE MYSQLI_TYPE_TIME MYSQLI_TYPE_DATETIME MYSQLI_TYPE_YEAR MYSQLI_TYPE_NEWDATE MYSQLI_TYPE_INTERVAL MYSQLI_TYPE_ENUM MYSQLI_TYPE_SET MYSQLI_TYPE_TINY_BLOB MYSQLI_TYPE_MEDIUM_BLOB MYSQLI_TYPE_LONG_BLOB MYSQLI_TYPE_BLOB MYSQLI_TYPE_VAR_STRING MYSQLI_TYPE_STRING MYSQLI_TYPE_CHAR MYSQLI_TYPE_GEOMETRY MYSQLI_NEED_DATA MYSQLI_NO_DATA MYSQLI_DATA_TRUNCATED MYSQLI_ENUM_FLAG
Field is part of an multi-index Field is part of GROUP BY Field is defined as DECIMAL Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up) Field is defined as BIT (MySQL 5.0.3 and up) Field is defined as TINYINT Field is defined as SMALLINT Field is defined as INT Field is defined as FLOAT Field is defined as DOUBLE Field is defined as DEFAULT NULL Field is defined as TIMESTAMP Field is defined as BIGINT Field is defined as MEDIUMINT Field is defined as DATE Field is defined as TIME Field is defined as DATETIME Field is defined as YEAR Field is defined as DATE Field is defined as INTERVAL Field is defined as ENUM Field is defined as SET Field is defined as TINYBLOB Field is defined as MEDIUMBLOB Field is defined as LONGBLOB Field is defined as BLOB Field is defined as VARCHAR Field is defined as STRING Field is defined as CHAR Field is defined as GEOMETRY More data available for bind variable No more data available for bind variable Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5. Field is defined as ENUM. Available since PHP 5.3.0. 69
MYSQLI_CURSOR_TYPE_FOR_U MYSQLI_CURSOR_TYPE_NO_CU PDATE MYSQLI_CURSOR_TYPE_READ_ RSOR MYSQLI_CURSOR_TYPE_SCROL ONLY MYSQLI_STMT_ATTR_CURSOR_ LABLE MYSQLI_STMT_ATTR_PREFETC TYPE MYSQLI_STMT_ATTR_UPDATE_ H_ROWS MYSQLI_SET_CHARSET_NAME MAX_LENGTH
$mysqli->client_info $mysqli->client_version $mysqli->connect_errno $mysqli->connect_error $mysqli->errno $mysqli->error $mysqli->field_count $mysqli->host_info $mysqli->protocol_version $mysqli->server_info $mysqli->server_version $mysqli->info $mysqli->insert_id $mysqli->sqlstate $mysqli->warning_count
mysqli_get_client_inf o mysqli_get_client_ver sion mysqli_connect_errno mysqli_connect_error mysqli_errno mysqli_error mysqli_field_count mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_inf o mysqli_get_server_ver sion mysqli_info mysqli_insert_id mysqli_sqlstate mysqli_warning_count
N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A
70
MySQLi Class OOP Interface mysqli>character_set_name, mysqli->client_encoding mysqli->close mysqli->commit mysqli::__construct Procedural Interface mysqli_character_set_ name mysqli_close mysqli_commit mysqli_connect Alias (Do not use) mysqli_client_encodin g N/A N/A N/A Description Returns the default character set for the database connection Closes a previously opened database connection Commits the current transaction Open a new connection to the MySQL server [Note: static (i.e. class) method] Performs debugging operations Dump debugging information into the log Returns a character set object Returns client connection statistics. Available only with mysqlnd. Returns the MySQL client version as a string Returns client per-process statistics. Available only with mysqlnd. Returns client Zval cache statistics. Available only with mysqlnd. NOT DOCUMENTED NOT DOCUMENTED Initializes MySQLi and returns a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.] Asks the server to kill a MySQL thread Check if there are any more query results from a multi query Performs a query on the database Prepare next result from multi_query Set options Pings a server connection, or tries to reconnect if the connection has gone down Prepare an SQL statement for execution Performs a query on the database Opens a connection to a mysql server Escapes special characters in a
mysqli->debug mysqli>dump_debug_info mysqli->get_charset mysqli>get_connection_stats mysqli>get_client_info mysqli>get_client_stats mysqli>get_cache_stats mysqli>get_server_info mysqli->get_warnings mysqli::init
mysqli_debug mysqli_dump_debug_inf o mysqli_get_charset mysqli_get_connection _stats mysqli_get_client_inf o mysqli_get_client_sta ts mysqli_get_cache_stat s mysqli_get_server_inf o mysqli_get_warnings mysqli_init
N/A N/A
N/A
MySQLi Class OOP Interface >real_escape_string, mysqli->escape_string mysqli->real_query mysqli->rollback mysqli->select_db mysqli->set_charset mysqli>set_local_infile_def ault mysqli>set_local_infile_han dler mysqli->ssl_set mysqli->stat mysqli->stmt_init Procedural Interface ring Alias (Do not use) Description string for use in an SQL statement, taking into account the current charset of the connection N/A N/A N/A N/A N/A Execute an SQL query Rolls back current transaction Selects the default database for database queries Sets the default client character set Unsets user defined handler for load local infile command Set callback function for LOAD DATA LOCAL INFILE command Used for establishing secure connections using SSL Gets the current system status Initializes a statement and returns an object for use with mysqli_stmt_prepare Transfers a result set from the last query Returns the thread ID for the current connection Returns whether thread safety is given or not Initiate a result set retrieval
mysqli_real_query mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infi le_default mysqli_set_local_infi le_handler mysqli_ssl_set mysqli_stat mysqli_stmt_init
N/A
MySQL_STMT OOP Interface Properties $mysqli_stmt->affected_rows mysqli_stmt_affected_ rows mysqli_stmt_errno mysqli_stmt_error mysqli_stmt_field_cou nt mysqli_stmt_insert_id mysqli_stmt_num_rows mysqli_stmt_param_cou nt mysqli_stmt_sqlstate N/A Returns the total number of rows changed, deleted, or inserted by the last executed statement Returns the error code for the most recent statement call Returns a string description for last statement error Returns the number of field in the given statement - not documented Get the ID generated from the previous INSERT operation Return the number of rows in statements result set Returns the number of parameter for the given statement Returns SQLSTATE error from previous statement operation Procedural Interface Alias (Do not use) Description
72
MySQL_STMT OOP Interface Methods mysqli_stmt->attr_get mysqli_stmt->attr_set mysqli_stmt->bind_par am mysqli_stmt->bind_res ult mysqli_stmt->close mysqli_stmt->data_see k mysqli_stmt->execute mysqli_stmt->fetch mysqli_stmt_attr_get mysqli_stmt_attr_set mysqli_stmt_bind_para m mysqli_stmt_bind_resu lt mysqli_stmt_close mysqli_stmt_data_seek mysqli_stmt_execute mysqli_stmt_fetch N/A N/A mysqli_bind_param mysqli_bind_result N/A N/A mysqli_execute mysqli_fetch Used to get the current value of a statement attribute Used to modify the behavior of a prepared statement Binds variables to a prepared statement as parameters Binds variables to a prepared statement for result storage Closes a prepared statement Seeks to an arbitrary row in statement result set Executes a prepared Query Fetch results from a prepared statement into the bound variables Frees stored result memory for the given statement handle NOT DOCUMENTED Available only with mysqlnd. NOT DOCUMENTED NOT DOCUMENTED Available only with mysqlnd. NOT DOCUMENTED Available only with mysqlnd. See also property $mysqli_stmt->num_rows Prepare an SQL statement for execution Resets a prepared statement Returns result set metadata from a prepared statement Send data in blocks Transfers a result set from a prepared statement Procedural Interface Alias (Do not use) Description
mysqli_stmt->free_res ult $mysqli_stmt->get_result() mysqli_stmt->get_warn ings $mysqli_stmt->more_results() $mysqli_stmt->next_result() mysqli_stmt->num_rows mysqli_stmt->prepare mysqli_stmt->reset mysqli_stmt->result_m etadata mysqli_stmt->send_lon g_data mysqli_stmt->store_re sult
mysqli_stmt_free_resu lt mysqli_stmt_get_result mysqli_stmt_get_warni ngs mysqli_stmt_more_results() mysqli_stmt_next_result() mysqli_stmt_num_rows mysqli_stmt_prepare mysqli_stmt_reset mysqli_stmt_result_me tadata mysqli_stmt_send_long _data mysqli_stmt_store_res ult
N/A N/A N/A N/A N/A N/A N/A N/A mysqli_get_metadata mysqli_send_long_data N/A
MySQLi_RESULT OOP Interface Properties $mysqli_result->current_field $mysqli_result->field_count $mysqli_result->lengths mysqli_field_tell mysqli_num_fields mysqli_fetch_lengths N/A N/A N/A Get current field offset of a result pointer Get the number of fields in a result Returns the lengths of the columns of the current row in the result set Gets the number of rows in a Procedural Interface Alias (Do not use) Description
$mysqli_result->num_rows
mysqli_num_rows 73
N/A
MySQLi_RESULT OOP Interface Methods mysqli_result->data_s eek mysqli_result->fetch_ all mysqli_data_seek mysqli_fetch_all N/A N/A Adjusts the result pointer to an arbitary row in the result Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd. Fetch a result row as an associative, a numeric array, or both Fetch a result row as an associative array Fetch meta-data for a single field Returns the next field in the result set Returns an array of objects representing the fields in a result set Returns the current row of a result set as an object Get a result row as an enumerated array Set result pointer to a specified field offset Frees the memory associated with a result Procedural Interface Alias (Do not use) Description result
mysqli_result->fetch_ array mysqli_result->fetch_ assoc mysqli_result->fetch_ field_direct mysqli_result->fetch_ field mysqli_result->fetch_ fields mysqli_result->fetch_ object mysqli_result->fetch_ row mysqli_result->field_ seek mysqli_result->free, mysqli_result->close, mysqli_result->free_result
mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_di rect mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_object mysqli_fetch_row mysqli_field_seek mysqli_free_result
MySQL_Driver OOP Interface Properties N/A Methods mysqli_driver->embedd ed_server_end mysqli_driver->embedd ed_server_start mysqli_embedded_serve r_end mysqli_embedded_serve r_start N/A N/A NOT DOCUMENTED NOT DOCUMENTED Procedural Interface Alias (Do not use) Description
Note
Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.
74
Properties int affected_rows ; string client_info ; int client_version ; string connect_errno ; string connect_error ; int errno ; 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 ; Methods int mysqli_affected_rows(mysqli link); bool mysqli::autocommit(bool mode); bool mysqli::change_user(string user, string password, string database); string mysqli::character_set_name(); string mysqli_get_client_info(mysqli link); int mysqli_get_client_version(mysqli link); bool mysqli::close(); bool mysqli::commit();
75
int mysqli_connect_errno(); string mysqli_connect_error(); mysqli mysqli_connect(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")); bool mysqli::debug(string message); bool mysqli::dump_debug_info(); int mysqli_errno(mysqli link); string mysqli_error(mysqli link); int mysqli_field_count(mysqli link); object mysqli::get_charset(); string mysqli::get_client_info(); array mysqli_get_client_stats(); int mysqli_get_client_version(mysqli link); bool mysqli::get_connection_stats(); string mysqli_get_host_info(mysqli link); int mysqli_get_proto_info(mysqli link); string mysqli_get_server_info(mysqli link); int mysqli_get_server_version(mysqli link); mysqli_warning mysqli::get_warnings(); string mysqli_info(mysqli link); mysqli mysqli::init(); mixed mysqli_insert_id(mysqli link); bool mysqli::kill(int processid); bool mysqli::more_results(); bool mysqli::multi_query(string query); bool mysqli::next_result(); bool mysqli::options(int option, mixed value);
76
bool mysqli::ping(); public int mysqli::poll(array read, array error, array reject, int sec, int usec); mysqli_stmt mysqli::prepare(string query); mixed mysqli::query(string query, int resultmode); bool mysqli::real_connect(string host, string username, string passwd, string dbname, int port, string socket, int flags); string mysqli::escape_string(string escapestr); bool mysqli::real_query(string query); public mysqli_result mysqli::reap_async_query(); bool mysqli::rollback(); bool mysqli::select_db(string dbname); bool mysqli::set_charset(string charset); void mysqli_set_local_infile_default(mysqli link); bool mysqli::set_local_infile_handler(mysqli link, callback read_func); string mysqli_sqlstate(mysqli link); bool mysqli::ssl_set(string string string string string string mysqli::stat(); mysqli_stmt mysqli::stmt_init(); mysqli_result mysqli::store_result(); int mysqli_thread_id(mysqli link); bool mysqli_thread_safe(); mysqli_result mysqli::use_result(); int mysqli_warning_count(mysqli link); } key, cert, ca, capath, cipher);
77
Procedural style
int mysqli_affected_rows(mysqli link);
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. For SELECT statements mysqli_affected_rows works like mysqli_num_rows. Parameters
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
Note
If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string. Examples
78
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows); /* select all rows */ $result = $mysqli->query("SELECT CountryCode FROM Language"); printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows); $result->close(); /* Delete table Language */ $mysqli->query("DROP TABLE Language"); /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); if (!$link) { printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error()); exit(); } /* Insert rows */ mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage"); printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link)); mysqli_query($link, "ALTER TABLE Language ADD Status int default 0"); /* update rows */ mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50"); printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link)); /* delete rows */ mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50"); printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link)); /* select all rows */ $result = mysqli_query($link, "SELECT CountryCode FROM Language"); printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link)); mysqli_free_result($result); /* Delete table Language */ mysqli_query($link, "DROP TABLE Language"); /* close connection */ mysqli_close($link); ?>
79
Procedural style
bool mysqli_autocommit(mysqli link, bool mode);
Turns on or off auto-commit mode on queries for the database connection. To determine the current state of autocommit use the SQL command SELECT @@autocommit. Parameters
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Whether to turn on auto-commit or not.
Note
This function doesn't work with non transactional table types (like MyISAM or ISAM). Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); if (!$link) { printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error()); exit(); } /* turn autocommit on */ mysqli_autocommit($link, TRUE); if ($result = mysqli_query($link, "SELECT @@autocommit")) { $row = mysqli_fetch_row($result); printf("Autocommit is %s\n", $row[0]);
80
Autocommit is 1
Procedural style
bool mysqli_change_user(mysqli string string string link, user, password, database);
Changes the user of the specified database connection and sets the current database. In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain. Parameters
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The MySQL user name. The MySQL password. The database to change to. If desired, the NULL value may be passed resulting in only changing the user and not selecting a 81
database. To select a database in this case use the mysqli_select_db function. Return Values Returns TRUE on success or FALSE on failure. Notes
Note
Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables. Examples
Procedural style
<?php /* connect database test */ $link = mysqli_connect("localhost", "my_user", "my_password", "test"); /* check connection */ if (!$link) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Set Variable a */ mysqli_query($link, "SET @a:=1"); /* reset all and select a new database */ mysqli_change_user($link, "my_user", "my_password", "world"); if ($result = mysqli_query($link, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); printf("Default database: %s\n", $row[0]); mysqli_free_result($result); } if ($result = mysqli_query($link, "SELECT @a")) { $row = mysqli_fetch_row($result); if ($row[0] === NULL) { printf("Value of variable a is NULL\n"); } mysqli_free_result($result);
82
Procedural style
string mysqli_character_set_name(mysqli link);
Returns the current character set for the database connection. Parameters
83
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Print current character set */ $charset = $mysqli->character_set_name(); printf ("Current character set is %s\n", $charset); $mysqli->close(); ?>
Procedural style
<?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (!$link) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Print current character set */ $charset = mysqli_character_set_name($link); printf ("Current character set is %s\n",$charset); /* close connection */ mysqli_close($link); ?>
Procedural style
string mysqli_get_client_info(mysqli link);
84
Returns a string that represents the MySQL client library version. Return Values A string that represents the MySQL client library version Examples
Procedural style
int mysqli_get_client_version(mysqli link);
Returns client version number as an integer. Return Values A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100. This is useful to quickly determine the version of the client library to know if some capability exits. Examples
85
Procedural style
bool mysqli_close(mysqli link);
Returns TRUE on success or FALSE on failure. Examples See mysqli_connect. See Also mysqli_connect mysqli_init mysqli_real_connect
86
Procedural style
bool mysqli_commit(mysqli link);
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "test"); /* check connection */ if (!$link) {
87
printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* set autocommit to off */ mysqli_autocommit($link, FALSE); mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage"); /* Insert some values */ mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)"); mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)"); /* commit transaction */ mysqli_commit($link); /* close connection */ mysqli_close($link); ?>
Procedural style
int mysqli_connect_errno();
Returns the last error code number from the last call to mysqli_connect.
Note
Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt. Return Values An error code value for the last call to mysqli_connect, if it failed. zero means no error occurred. Examples
88
<?php $mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db'); if ($mysqli->connect_errno) { die('Connect Error: ' . $mysqli->connect_errno); } ?>
Procedural style
<?php $link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error: ' . mysqli_connect_errno()); } ?>
Procedural style
string mysqli_connect_error();
Returns the last error message string from the last call to mysqli_connect. Return Values
89
A string that describes the error. NULL is returned if no error occurred. Examples
Procedural style
<?php $link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error: ' . mysqli_connect_error()); } ?>
Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)
Notes
Warning
The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error function if compatibility with earlier PHP versions is required. See Also mysqli_connect mysqli_connect_errno mysqli_errno mysqli_error mysqli_sqlstate
Procedural style
mysqli mysqli_connect(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"));
host
Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol. Prepending host by p: opens a persistent connection. mysqli_change_user is automatically called on connections opened from the connection pool.
username passwd
The MySQL user name. If not provided or NULL , the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not). If provided will specify the default database to be used when performing queries. Specifies the port number to attempt to connect to the MySQL server. Specifies the socket or named pipe that should be used.
Note
Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter. Return Values Returns an object which represents the connection to a MySQL Server. Changelog Version 5.3.0 Examples Description Added the ability of persistent connections.
91
<?php $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); /* * This is the "official" OO way to do it, * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } /* * Use this instead of $connect_error if you need to ensure * compatibility with PHP versions prior to 5.2.9 and 5.3.0. */ if (mysqli_connect_error()) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . $mysqli->host_info . "\n"; $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . mysqli_get_host_info($link) . "\n"; mysqli_close($link); ?>
Notes
Note
MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use. Libmysql uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init. 92
Note
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error function or the mysqli->connect_error property as in the preceding examples.
Note
If it is necessary to set options, such as the connection timeout, mysqli_real_connect must be used instead.
Note
Calling the constructor with no parameters is the same as calling mysqli_init.
Note
Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. See Also mysqli_real_connect mysqli_options mysqli_connect_errno mysqli_connect_error mysqli_close
Procedural style
bool mysqli_debug(string message);
Performs debugging operations using the Fred Fish debugging library. Parameters
93
Note
To use the mysqli_debug function you must compile the MySQL client library to support debugging. Examples
Procedural style
bool mysqli_dump_debug_info(mysqli link);
This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection. Parameters
94
Procedural style
int mysqli_errno(mysqli link);
Returns the last error code for the most recent MySQLi function call that can succeed or fail. Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt. Parameters
An error code value for the last call, if it failed. zero means no error occurred. Examples
Procedural style
<?php
95
$link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if (!mysqli_query($link, "SET a=1")) { printf("Errorcode: %d\n", mysqli_errno($link)); } /* close connection */ mysqli_close($link); ?>
Errorcode: 1193
Procedural style
string mysqli_error(mysqli link);
Returns the last error message for the most recent MySQLi function call that can succeed or fail. Parameters
Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if (!mysqli_query($link, "SET a=1")) { printf("Errormessage: %s\n", mysqli_error($link)); } /* close connection */ mysqli_close($link); ?>
Procedural style
int mysqli_field_count(mysqli link);
Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query. Parameters
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "test"); mysqli_query($link, "DROP TABLE IF EXISTS friends"); mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))"); mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')"); mysqli_real_query($link, "SELECT * FROM friends"); if (mysqli_field_count($link)) { /* this was a select/show or describe query */ $result = mysqli_store_result($link); /* process resultset */ $row = mysqli_fetch_row($result); /* free resultset */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
98
Procedural style
object mysqli_get_charset(mysqli link);
Returns a character set object providing several properties of the current active character set. Parameters
The function returns a character set object with the following properties: charset collation dir min_length max_length number state Examples Character set name Collation name Directory the charset description was fetched from (?) or "" for built-in character sets Minimum character length in bytes Maximum character length in bytes Internal character set number Character set status (?)
99
Procedural style
<?php $db = mysqli_init(); mysqli_real_connect($db, "localhost","root","","test"); var_dump($db->get_charset()); ?>
object(stdClass)#2 (7) { ["charset"]=> string(6) "latin1" ["collation"]=> string(17) "latin1_swedish_ci" ["dir"]=> string(0) "" ["min_length"]=> int(1) ["max_length"]=> int(1) ["number"]=> int(8) ["state"]=> int(801) }
Procedural style
string mysqli_get_client_info(mysqli link);
Returns a string that represents the MySQL client library version. Return Values A string that represents the MySQL client library version 100
Examples
2.7.19. mysqli_get_client_stats
Copyright 1997-2010 the PHP Documentation Group. mysqli_get_client_stats Returns client per-process statistics Description
array mysqli_get_client_stats();
Returns client per-process statistics. Available only with mysqlnd. Parameters Return Values Returns an array with client stats if success, FALSE otherwise. Examples
Array ( [bytes_sent] => 43 [bytes_received] => 80 [packets_sent] => 1 [packets_received] => 2 [protocol_overhead_in] => 8
101
[protocol_overhead_out] => 4 [bytes_received_ok_packet] => 11 [bytes_received_eof_packet] => 0 [bytes_received_rset_header_packet] => 0 [bytes_received_rset_field_meta_packet] => 0 [bytes_received_rset_row_packet] => 0 [bytes_received_prepare_response_packet] => 0 [bytes_received_change_user_packet] => 0 [packets_sent_command] => 0 [packets_received_ok] => 1 [packets_received_eof] => 0 [packets_received_rset_header] => 0 [packets_received_rset_field_meta] => 0 [packets_received_rset_row] => 0 [packets_received_prepare_response] => 0 [packets_received_change_user] => 0 [result_set_queries] => 0 [non_result_set_queries] => 0 [no_index_used] => 0 [bad_index_used] => 0 [slow_queries] => 0 [buffered_sets] => 0 [unbuffered_sets] => 0 [ps_buffered_sets] => 0 [ps_unbuffered_sets] => 0 [flushed_normal_sets] => 0 [flushed_ps_sets] => 0 [ps_prepared_never_executed] => 0 [ps_prepared_once_executed] => 0 [rows_fetched_from_server_normal] => 0 [rows_fetched_from_server_ps] => 0 [rows_buffered_from_client_normal] => 0 [rows_buffered_from_client_ps] => 0 [rows_fetched_from_client_normal_buffered] => 0 [rows_fetched_from_client_normal_unbuffered] => 0 [rows_fetched_from_client_ps_buffered] => 0 [rows_fetched_from_client_ps_unbuffered] => 0 [rows_fetched_from_client_ps_cursor] => 0 [rows_skipped_normal] => 0 [rows_skipped_ps] => 0 [copy_on_write_saved] => 0 [copy_on_write_performed] => 0 [command_buffer_too_small] => 0 [connect_success] => 1 [connect_failure] => 0 [connection_reused] => 0 [reconnect] => 0 [pconnect_success] => 0 [active_connections] => 1 [active_persistent_connections] => 0 [explicit_close] => 0 [implicit_close] => 0 [disconnect_close] => 0 [in_middle_of_command_close] => 0 [explicit_free_result] => 0 [implicit_free_result] => 0 [explicit_stmt_close] => 0 [implicit_stmt_close] => 0 [mem_emalloc_count] => 0 [mem_emalloc_ammount] => 0 [mem_ecalloc_count] => 0 [mem_ecalloc_ammount] => 0 [mem_erealloc_count] => 0 [mem_erealloc_ammount] => 0 [mem_efree_count] => 0 [mem_malloc_count] => 0 [mem_malloc_ammount] => 0 [mem_calloc_count] => 0 [mem_calloc_ammount] => 0 [mem_realloc_count] => 0 [mem_realloc_ammount] => 0 [mem_free_count] => 0 [proto_text_fetched_null] => 0 [proto_text_fetched_bit] => 0 [proto_text_fetched_tinyint] => 0 [proto_text_fetched_short] => 0 [proto_text_fetched_int24] => 0 [proto_text_fetched_int] => 0 [proto_text_fetched_bigint] => 0 [proto_text_fetched_decimal] => 0 [proto_text_fetched_float] => 0 [proto_text_fetched_double] => 0 [proto_text_fetched_date] => 0 [proto_text_fetched_year] => 0 [proto_text_fetched_time] => 0 [proto_text_fetched_datetime] => 0 [proto_text_fetched_timestamp] => 0 [proto_text_fetched_string] => 0 [proto_text_fetched_blob] => 0 [proto_text_fetched_enum] => 0
102
[proto_text_fetched_set] => 0 [proto_text_fetched_geometry] => 0 [proto_text_fetched_other] => 0 [proto_binary_fetched_null] => 0 [proto_binary_fetched_bit] => 0 [proto_binary_fetched_tinyint] => 0 [proto_binary_fetched_short] => 0 [proto_binary_fetched_int24] => 0 [proto_binary_fetched_int] => 0 [proto_binary_fetched_bigint] => 0 [proto_binary_fetched_decimal] => 0 [proto_binary_fetched_float] => 0 [proto_binary_fetched_double] => 0 [proto_binary_fetched_date] => 0 [proto_binary_fetched_year] => 0 [proto_binary_fetched_time] => 0 [proto_binary_fetched_datetime] => 0 [proto_binary_fetched_timestamp] => 0 [proto_binary_fetched_string] => 0 [proto_binary_fetched_blob] => 0 [proto_binary_fetched_enum] => 0 [proto_binary_fetched_set] => 0 [proto_binary_fetched_geometry] => 0 [proto_binary_fetched_other] => 0 )
Procedural style
int mysqli_get_client_version(mysqli link);
Returns client version number as an integer. Return Values A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100. This is useful to quickly determine the version of the client library to know if some capability exits. Examples
103
Procedural style
array mysqli_get_connection_stats(mysqli link);
Returns statistics about the client connection. Available only with mysqlnd. Parameters link Return Values Returns an array with connection stats if success, FALSE otherwise. Examples Procedural style only: A link identifier returned by mysqli_connect or mysqli_init
104
Array ( [bytes_sent] => 43 [bytes_received] => 80 [packets_sent] => 1 [packets_received] => 2 [protocol_overhead_in] => 8 [protocol_overhead_out] => 4 [bytes_received_ok_packet] => 11 [bytes_received_eof_packet] => 0 [bytes_received_rset_header_packet] => 0 [bytes_received_rset_field_meta_packet] => 0 [bytes_received_rset_row_packet] => 0 [bytes_received_prepare_response_packet] => 0 [bytes_received_change_user_packet] => 0 [packets_sent_command] => 0 [packets_received_ok] => 1 [packets_received_eof] => 0 [packets_received_rset_header] => 0 [packets_received_rset_field_meta] => 0 [packets_received_rset_row] => 0 [packets_received_prepare_response] => 0 [packets_received_change_user] => 0 [result_set_queries] => 0 [non_result_set_queries] => 0 [no_index_used] => 0 [bad_index_used] => 0 [slow_queries] => 0 [buffered_sets] => 0 [unbuffered_sets] => 0 [ps_buffered_sets] => 0 [ps_unbuffered_sets] => 0 [flushed_normal_sets] => 0 [flushed_ps_sets] => 0 [ps_prepared_never_executed] => 0 [ps_prepared_once_executed] => 0 [rows_fetched_from_server_normal] => 0 [rows_fetched_from_server_ps] => 0 [rows_buffered_from_client_normal] => 0 [rows_buffered_from_client_ps] => 0 [rows_fetched_from_client_normal_buffered] => 0 [rows_fetched_from_client_normal_unbuffered] => 0 [rows_fetched_from_client_ps_buffered] => 0 [rows_fetched_from_client_ps_unbuffered] => 0 [rows_fetched_from_client_ps_cursor] => 0 [rows_skipped_normal] => 0 [rows_skipped_ps] => 0 [copy_on_write_saved] => 0 [copy_on_write_performed] => 0 [command_buffer_too_small] => 0 [connect_success] => 1 [connect_failure] => 0 [connection_reused] => 0 [reconnect] => 0 [pconnect_success] => 0 [active_connections] => 1 [active_persistent_connections] => 0 [explicit_close] => 0 [implicit_close] => 0 [disconnect_close] => 0 [in_middle_of_command_close] => 0 [explicit_free_result] => 0 [implicit_free_result] => 0 [explicit_stmt_close] => 0 [implicit_stmt_close] => 0 [mem_emalloc_count] => 0 [mem_emalloc_ammount] => 0 [mem_ecalloc_count] => 0 [mem_ecalloc_ammount] => 0 [mem_erealloc_count] => 0 [mem_erealloc_ammount] => 0 [mem_efree_count] => 0 [mem_malloc_count] => 0 [mem_malloc_ammount] => 0 [mem_calloc_count] => 0 [mem_calloc_ammount] => 0 [mem_realloc_count] => 0 [mem_realloc_ammount] => 0 [mem_free_count] => 0 [proto_text_fetched_null] => 0 [proto_text_fetched_bit] => 0 [proto_text_fetched_tinyint] => 0 [proto_text_fetched_short] => 0 [proto_text_fetched_int24] => 0 [proto_text_fetched_int] => 0
105
[proto_text_fetched_bigint] => 0 [proto_text_fetched_decimal] => 0 [proto_text_fetched_float] => 0 [proto_text_fetched_double] => 0 [proto_text_fetched_date] => 0 [proto_text_fetched_year] => 0 [proto_text_fetched_time] => 0 [proto_text_fetched_datetime] => 0 [proto_text_fetched_timestamp] => 0 [proto_text_fetched_string] => 0 [proto_text_fetched_blob] => 0 [proto_text_fetched_enum] => 0 [proto_text_fetched_set] => 0 [proto_text_fetched_geometry] => 0 [proto_text_fetched_other] => 0 [proto_binary_fetched_null] => 0 [proto_binary_fetched_bit] => 0 [proto_binary_fetched_tinyint] => 0 [proto_binary_fetched_short] => 0 [proto_binary_fetched_int24] => 0 [proto_binary_fetched_int] => 0 [proto_binary_fetched_bigint] => 0 [proto_binary_fetched_decimal] => 0 [proto_binary_fetched_float] => 0 [proto_binary_fetched_double] => 0 [proto_binary_fetched_date] => 0 [proto_binary_fetched_year] => 0 [proto_binary_fetched_time] => 0 [proto_binary_fetched_datetime] => 0 [proto_binary_fetched_timestamp] => 0 [proto_binary_fetched_string] => 0 [proto_binary_fetched_blob] => 0 [proto_binary_fetched_enum] => 0 [proto_binary_fetched_set] => 0 [proto_binary_fetched_geometry] => 0 [proto_binary_fetched_other] => 0 )
Procedural style
string mysqli_get_host_info(mysqli link);
Returns a string describing the connection represented by the link parameter (including the server host name). Parameters 106
A character string representing the server hostname and the connection type. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* print host information */ printf("Host info: %s\n", mysqli_get_host_info($link)); /* close connection */ mysqli_close($link); ?>
107
Returns the version of the MySQL protocol used Description Object oriented style
mysqli { string protocol_version ; }
Procedural style
int mysqli_get_proto_info(mysqli link);
Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter. Parameters
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* print protocol version */ printf("Protocol version: %d\n", mysqli_get_proto_info($link)); /* close connection */ mysqli_close($link); ?>
Protocol version: 10
Procedural style
string mysqli_get_server_info(mysqli link);
Returns a string representing the version of the MySQL server that the MySQLi extension is connected to. Parameters
109
?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* print server version */ printf("Server version: %s\n", mysqli_get_server_info($link)); /* close connection */ mysqli_close($link); ?>
Procedural style
int mysqli_get_server_version(mysqli link);
The mysqli_get_server_version function returns the version of the server connected to (represented by the link parameter) as an integer. Parameters
110
An integer representing the server version. The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100). Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* print server version */ printf("Server version: %d\n", mysqli_get_server_version($link)); /* close connection */ mysqli_close($link); ?>
111
Procedural style
mysqli_warning mysqli_get_warnings(mysqli link);
Warning
This function is currently not documented; only its argument list is available.
Procedural style
string mysqli_info(mysqli link);
The mysqli_info function returns a string providing information about the last query executed. The nature of this string is provided below:
Note
112
Queries which do not fall into one of the preceding formats are not supported. In these situations, mysqli_info will return an empty string. Parameters
A character string representing additional information about the most recently executed query. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City"); /* INSERT INTO .. SELECT */ mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150"); printf("%s\n", mysqli_info($link)); /* close connection */ mysqli_close($link); ?>
Records: 150
Duplicates: 0
Warnings: 0
Procedural style
mysqli mysqli_init();
Note
Any subsequent calls to any mysqli function (except mysqli_options) will fail until mysqli_real_connect was called. Return Values Returns an object. Examples See mysqli_real_connect. See Also mysqli_options mysqli_close mysqli_real_connect mysqli_connect
114
Procedural style
mixed mysqli_insert_id(mysqli link);
The mysqli_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
Note
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id function. Parameters
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Note
If the number is greater than maximal int value, mysqli_insert_id will return a string. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TABLE myCity LIKE City"); $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)"; mysqli_query($link, $query); printf ("New Record has id %d.\n", mysqli_insert_id($link)); /* drop table */ mysqli_query($link, "DROP TABLE myCity"); /* close connection */ mysqli_close($link);
115
?>
Procedural style
bool mysqli_kill(mysqli link, int processid);
This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id function. To stop a running query you should use the SQL command KILL QUERY processid. Parameters
116
/* Kill connection */ $mysqli->kill($thread_id); /* This should produce an error */ if (!$mysqli->query("CREATE TABLE myCity LIKE City")) { printf("Error: %s\n", $mysqli->error); exit; } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* determine our thread id */ $thread_id = mysqli_thread_id($link); /* Kill connection */ mysqli_kill($link, $thread_id); /* This should produce an error */ if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n", mysqli_error($link)); exit; } /* close connection */ mysqli_close($link); ?>
Procedural style
bool mysqli_more_results(mysqli link);
117
Indicates if one or more result sets are available from a previous call to mysqli_multi_query. Parameters
Returns TRUE on success or FALSE on failure. Examples See mysqli_multi_query. See Also mysqli_multi_query mysqli_next_result mysqli_store_result mysqli_use_result
Procedural style
bool mysqli_multi_query(mysqli link, string query);
Executes one or multiple queries which are concatenated by a semicolon. To retrieve the resultset from the first query you can use mysqli_use_result or mysqli_store_result. All subsequent query results can be processed using mysqli_more_results and mysqli_next_result. Parameters
link query
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query, as a string. Data inside the query should be properly escaped.
Return Values
118
Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result first. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if (mysqli_multi_query($link, $query)) { do { /* store first result set */ if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } /* print divider */ if (mysqli_more_results($link)) { printf("-----------------\n"); } } while (mysqli_next_result($link)); } /* close connection */ mysqli_close($link); ?>
my_user@localhost -----------------
119
Procedural style
bool mysqli_next_result(mysqli link);
Prepares next result set from a previous call to mysqli_multi_query which can be retrieved by mysqli_store_result or mysqli_use_result. Parameters
Returns TRUE on success or FALSE on failure. Examples See mysqli_multi_query. See Also mysqli_multi_query mysqli_more_results mysqli_store_result mysqli_use_result
Copyright 1997-2010 the PHP Documentation Group. mysqli::options mysqli_options Set options Description Object oriented style
bool mysqli::options(int option, mixed value);
Procedural style
bool mysqli_options(mysqli link, int option, mixed value);
Used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options. mysqli_options should be called after mysqli_init and before mysqli_real_connect. Parameters
link option
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The option that you want to set. It can be one of the following values:
Note
121
MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use. Libmysql uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init. See Also mysqli_init mysqli_real_connect
Procedural style
bool mysqli_ping(mysqli link);
Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted. This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary. Parameters
122
printf ("Our connection is ok!\n"); } else { printf ("Error: %s\n", $mysqli->error); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* check if server is alive */ if (mysqli_ping($link)) { printf ("Our connection is ok!\n"); } else { printf ("Error: %s\n", mysqli_error($link)); } /* close connection */ mysqli_close($link); ?>
Procedural style
int mysqli_poll(array read, array error, array reject, int sec, int usec);
Warning
123
This function is currently not documented; only its argument list is available. Poll connections. Available only with mysqlnd. Parameters
Number of seconds to wait, must be non-negative. Number of microseconds to wait, must be non-negative.
Procedural style
mysqli_stmt mysqli_prepare(mysqli link, string query);
Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement. The parameter markers must be bound to application variables using mysqli_stmt_bind_param and/or mysqli_stmt_bind_result before executing the statement or fetching rows. Parameters
link query
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query, as a string.
Note
You should not add a terminating semicolon or \g to the statement. This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Note
The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements. Return Values mysqli_prepare returns a statement object or FALSE if an error occurred. Examples
125
/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $city = "Amersfoort"; /* create a prepared statement */ if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ $stmt->bind_param("s", $city); /* execute query */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($district); /* fetch value */ $stmt->fetch(); printf("%s is in district %s\n", $city, $district); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $city = "Amersfoort"; /* create a prepared statement */ if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt, "s", $city); /* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $district); /* fetch value */ mysqli_stmt_fetch($stmt); printf("%s is in district %s\n", $city, $district); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
126
Procedural style
mixed mysqli_query(mysqli link, string query, int resultmode);
Performs a query against the database. Functionally, using this function is identical to calling mysqli_real_query followed either by mysqli_use_result or mysqli_store_result.
Note
In the case where you pass a statement to mysqli_query that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). The behavior is as follows: mysqlnd on Linux returns an error code of 1153. The error message means got a packet bigger than max_allowed_packet bytes. mysqlnd on Windows returns an error code 2006. This error message means server has gone away. libmysql on all platforms returns an error code 2006. This error message means server has gone away.
Parameters
link query
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query string. Data inside the query should be properly escaped.
resultmode
Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll is then used to get results from such queries.
Return Values Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query will return a result object. For other successful queries mysqli_query will return TRUE . Changelog
127
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Create table doesn't return a resultset */ if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) { printf("Table myCity successfully created.\n"); } /* Select queries return a resultset */ if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) { printf("Select returned %d rows.\n", mysqli_num_rows($result)); /* free result set */ mysqli_free_result($result); } /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) { /* Note, that we can't execute any functions which interact with the server until result set was closed. All calls will return an 'out of sync' error */ if (!mysqli_query($link, "SET @a:='this will not work'")) { printf("Error: %s\n", mysqli_error($link)); } mysqli_free_result($result); } mysqli_close($link); ?>
128
Table myCity successfully created. Select returned 10 rows. Error: Commands out of sync; You can't run this command now
Procedural style
bool mysqli_real_connect(mysqli link, string host, string username, string passwd, string dbname, int port, string socket, int flags);
Establish a connection to a MySQL database engine. This function differs from mysqli_connect: mysqli_real_connect needs a valid object which has to be created by function mysqli_init. With the mysqli_options function you can set various options for connection. There is a flags parameter.
Parameters
link
host
Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol. The MySQL user name. If provided or NULL , the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not). If provided will specify the default database to be used when performing queries. Specifies the port number to attempt to connect to the MySQL server. Specifies the socket or named pipe that should be used.
username passwd
Note
Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter. flags With the parameter flags you can set different connection options:
MYSQLI_CLIENT_SSL
Note
For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query function. Return Values Returns TRUE on success or FALSE on failure. Examples
130
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . $mysqli->host_info . "\n"; $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_init(); if (!$link) { die('mysqli_init failed'); } if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed'); } if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'); } if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . mysqli_get_host_info($link) . "\n"; mysqli_close($link); ?>
Notes
Note
MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use. Libmysql uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init.
131
Procedural style
string mysqli_real_escape_string(mysqli link, string escapestr);
This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection. Parameters
link escapestr
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
132
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"); $city = "'s Hertogenbosch"; /* this query will fail, cause we didn't escape $city */ if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n", $mysqli->sqlstate); } $city = $mysqli->real_escape_string($city); /* this query with escaped $city will work */ if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted.\n", $mysqli->affected_rows); } $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City"); $city = "'s Hertogenbosch"; /* this query will fail, cause we didn't escape $city */ if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n", mysqli_sqlstate($link)); } $city = mysqli_real_escape_string($link, $city); /* this query with escaped $city will work */ if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted.\n", mysqli_affected_rows($link)); } mysqli_close($link); ?>
133
Procedural style
bool mysqli_real_query(mysqli link, string query);
Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result or mysqli_use_result functions. In order to determine if a given query should return a result set or not, see mysqli_field_count. Parameters
link query
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query, as a string. Data inside the query should be properly escaped.
Return Values Returns TRUE on success or FALSE on failure. See Also mysqli_query mysqli_store_result mysqli_use_result
Procedural style
mysqli_result mysqli_reap_async_query(mysql link);
Warning
This function is currently not documented; only its argument list is available. Get result from async query. Available only with mysqlnd. Parameters
link
Return Values Returns mysqli_result in success, FALSE otherwise. See Also mysqli_poll
Procedural style
bool mysqli_rollback(mysqli link);
135
printf("%d rows in table myCity.\n", $row[0]); /* Free result */ $result->close(); } /* Rollback */ $mysqli->rollback(); if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(); printf("%d rows in table myCity (after rollback).\n", $row[0]); /* Free result */ $result->close(); } /* Drop table myCity */ $mysqli->query("DROP TABLE myCity"); $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* disable autocommit */ mysqli_autocommit($link, FALSE); mysqli_query($link, "CREATE TABLE myCity LIKE City"); mysqli_query($link, "ALTER TABLE myCity Type=InnoDB"); mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50"); /* commit insert */ mysqli_commit($link); /* delete all rows */ mysqli_query($link, "DELETE FROM myCity"); if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result); printf("%d rows in table myCity.\n", $row[0]); /* Free result */ mysqli_free_result($result); } /* Rollback */ mysqli_rollback($link); if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result); printf("%d rows in table myCity (after rollback).\n", $row[0]); /* Free result */ mysqli_free_result($result); } /* Drop table myCity */ mysqli_query($link, "DROP TABLE myCity"); mysqli_close($link); ?>
136
Procedural style
bool mysqli_select_db(mysqli link, string dbname);
Selects the default database to be used when performing queries against the database connection.
Note
This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect. Parameters
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The database name.
137
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "test"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* return name of current default database */ if ($result = mysqli_query($link, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); printf("Default database is %s.\n", $row[0]); mysqli_free_result($result); } /* change db to world db */ mysqli_select_db($link, "world"); /* return name of current default database */ if ($result = mysqli_query($link, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); printf("Default database is %s.\n", $row[0]); mysqli_free_result($result); } mysqli_close($link); ?>
Procedural style
bool mysqli_set_charset(mysqli link, string charset);
Sets the default character set to be used when sending data from and to the database server. Parameters
138
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The charset to be set as default.
Note
To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).
Note
This is the preferred way to change the charset. Using mysqli::query to execute SET NAMES .. is not recommended. Examples
Procedural style
<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'test'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* change character set to utf8 */ if (!mysqli_set_charset($link, "utf8")) { printf("Error loading character set utf8: %s\n", mysqli_error($link)); } else { printf("Current character set: %s\n", mysqli_character_set_name($link)); } mysqli_close($link); ?>
139
See Also mysqli_character_set_name mysqli_real_escape_string List of character sets that MySQL supports
Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler. Parameters
Procedural style
bool mysqli_set_local_infile_handler(mysqli link, callback read_func);
Set callback function for LOAD DATA LOCAL INFILE command The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE. The returned data needs to match the format specified in the LOAD DATA Parameters
link read_func
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A callback function or object method taking the following parameters: stream &buffer buflen &errormsg A PHP stream associated with the SQL commands INFILE A string buffer to store the rewritten input into The maximum number of characters to be stored in the buffer If an error occurs you can store an error message in here
The callback function should return the number of characters stored in the buffer or a negative value if an error occurred. Return Values Returns TRUE on success or FALSE on failure. Examples
141
Procedural style
<?php $db = mysqli_init(); mysqli_real_connect($db, "localhost","root","","test"); function callme($stream, &$buffer, $buflen, &$errmsg) { $buffer = fgets($stream); echo $buffer; // convert to upper case and replace "," delimiter with [TAB] $buffer = strtoupper(str_replace(",", "\t", $buffer)); return strlen($buffer); } echo "Input:\n"; mysqli_set_local_infile_handler($db, "callme"); mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1"); mysqli_set_local_infile_default($db); $res = mysqli_query($db, "SELECT * FROM t1"); echo "\nResult:\n"; while ($row = mysqli_fetch_assoc($res)) { echo join(",", $row)."\n"; } ?>
Procedural style
string mysqli_sqlstate(mysqli link);
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no 142
error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.
Note
Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors. Parameters
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Table City already exists, so we should get an error */ if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) { printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link)); } mysqli_close($link); ?>
See Also
143
mysqli_errno mysqli_error
Procedural style
bool mysqli_ssl_set(mysqli string string string string string link, key, cert, ca, capath, cipher);
Used for establishing secure connections using SSL. It must be called before mysqli_real_connect. This function does nothing unless OpenSSL support is enabled. Note that MySQL Native Driver does not support SSL, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards. Parameters
Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The path name to the key file. The path name to the certificate file. The path name to the certificate authority file. The pathname to a directory that contains trusted SSL CA certificates in PEM format. A list of allowable ciphers to use for SSL encryption.
Any unused SSL parameters may be given as NULL Return Values This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect will return an error when you attempt to connect. See Also
144
mysqli_options mysqli_real_connect
Procedural style
string mysqli_stat(mysqli link);
mysqli_stat returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables. Parameters
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
145
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0 Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632 Memory in use: 8496K Max memory used: 8560K
Procedural style
mysqli_stmt mysqli_stmt_init(mysqli link);
Note
Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare was called. Parameters
Copyright 1997-2010 the PHP Documentation Group. mysqli::store_result mysqli_store_result Transfers a result set from the last query Description Object oriented style
mysqli_result mysqli::store_result();
Procedural style
mysqli_result mysqli_store_result(mysqli link);
Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek function. Parameters
Note
mysqli_store_result returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error doesn't return an empty string, if mysqli_errno returns a non zero value, or if mysqli_field_count returns a non zero value. Also possible reason for this function returning FALSE after successful call to mysqli_query can be too large result set (memory for it cannot be allocated). If mysqli_field_count returns a non-zero value, the statement should have produced a non-empty result set. Notes
Note
Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result function, when transferring large result sets using the mysqli_store_result this becomes particularly important. Examples See mysqli_multi_query. See Also mysqli_real_query mysqli_use_result
147
Procedural style
int mysqli_thread_id(mysqli link);
The mysqli_thread_id function returns the thread ID for the current connection which can then be killed using the mysqli_kill function. If the connection is lost and you reconnect with mysqli_ping, the thread ID will be other. Therefore you should get the thread ID only when you need it.
Note
The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned. To kill a running query you can use the SQL command KILL QUERY processid. Parameters
148
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* determine our thread id */ $thread_id = mysqli_thread_id($link); /* Kill connection */ mysqli_kill($link, $thread_id); /* This should produce an error */ if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n", mysqli_error($link)); exit; } /* close connection */ mysqli_close($link); ?>
Tells whether the client library is compiled as thread-safe. Return Values TRUE if the client library is thread-safe, otherwise FALSE .
Procedural style
mysqli_result mysqli_use_result(mysqli link);
Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query function on the database connection. Either this or the mysqli_store_result function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.
Note
The mysqli_use_result function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result. One should not use mysqli_use_result if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched. Return Values Returns an unbuffered result object or FALSE if an error occurred. Examples
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if (mysqli_multi_query($link, $query)) { do { /* store first result set */ if ($result = mysqli_use_result($link)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } /* print divider */ if (mysqli_more_results($link)) { printf("-----------------\n"); } } while (mysqli_next_result($link)); } /* close connection */ mysqli_close($link); ?>
Returns the number of warnings from the last query in the connection.
Note
For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count]. Parameters
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TABLE myCity LIKE City"); /* a remarkable long city name in Wales */ $query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR', 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')"; mysqli_query($link, $query); if (mysqli_warning_count($link)) { if ($result = mysqli_query($link, "SHOW WARNINGS")) { $row = mysqli_fetch_row($result); printf("%s (%d): %s\n", $row[0], $row[1], $row[2]); mysqli_free_result($result); } } /* close connection */ mysqli_close($link); ?>
152
153
int mysqli_stmt_errno(mysqli_stmt stmt); string mysqli_stmt_error(mysqli_stmt stmt); bool mysqli_stmt::execute(); bool mysqli_stmt::fetch(); int mysqli_stmt_field_count(mysqli_stmt stmt); void mysqli_stmt::free_result(); object mysqli_stmt::get_warnings(mysqli_stmt stmt); mixed mysqli_stmt_insert_id(mysqli_stmt stmt); int mysqli_stmt_num_rows(mysqli_stmt stmt); int mysqli_stmt_param_count(mysqli_stmt stmt); mixed mysqli_stmt::prepare(string query); bool mysqli_stmt::reset(); mysqli_result mysqli_stmt::result_metadata(); bool mysqli_stmt::send_long_data(int param_nr, string data); string mysqli_stmt_sqlstate(mysqli_stmt stmt); bool mysqli_stmt::store_result(); }
Procedural style
int mysqli_stmt_affected_rows(mysqli_stmt stmt);
154
Returns the number of rows affected by INSERT, UPDATE, or DELETE query. This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows instead. Parameters
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error. NULL indicates an invalid argument was supplied to the function.
Note
If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value. Examples
155
/* execute statement */ mysqli_stmt_execute($stmt); printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt)); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
rows inserted: 17
Procedural style
int mysqli_stmt_attr_get(mysqli_stmt stmt, int attr);
Procedural style only: A statement identifier returned by mysqli_stmt_init. The attribute that you want to get.
Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.
Procedural style
bool mysqli_stmt_attr_set(mysqli_stmt stmt, int attr, int mode);
Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes. Parameters
stmt attr
Procedural style only: A statement identifier returned by mysqli_stmt_init. The attribute that you want to set. It can have one of the following values:
MYSQLI_STMT_ATTR_PREFETCH_ROWS
If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute. If there is already an open cursor from a previous mysqli_stmt_execute call, it closes the cursor before opening a new one. mysqli_stmt_reset also closes any open cursor before preparing the statement for reexecution. mysqli_stmt_free_result closes any open cursor. If you open a cursor for a prepared statement, mysqli_stmt_store_result is unnecessary. mode The value to assign to the attribute.
157
mysqli_stmt_bind_param Binds variables to a prepared statement as parameters Description Object oriented style
bool mysqli_stmt::bind_param(string types, mixed var1, mixed ...);
Procedural style
bool mysqli_stmt_bind_param(mysqli_stmt stmt, string types, mixed var1, mixed ...);
Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare.
Note
If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data to send the data in packets.
Note
Care must be taken when using mysqli_stmt_bind_param in conjunction with call_user_func_array. Note that mysqli_stmt_bind_param requires parameters to be passed by reference, whereas call_user_func_array can accept as a parameter a list of variables that can represent references or values. Parameters
stmt types
Procedural style only: A statement identifier returned by mysqli_stmt_init. A string that contains one or more characters which specify the types for the corresponding bind variables:
158
<?php $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent); $code = 'DEU'; $language = 'Bavarian'; $official = "F"; $percent = 11.2; /* execute prepared statement */ $stmt->execute(); printf("%d Row inserted.\n", $stmt->affected_rows); /* close statement and connection */ $stmt->close(); /* Clean up table CountryLanguage */ $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'"); printf("%d Row deleted.\n", $mysqli->affected_rows); /* close connection */ $mysqli->close(); ?>
mysqli_stmt_error
Procedural style
bool mysqli_stmt_bind_result(mysqli_stmt stmt, mixed var1, mixed ...);
Binds columns in the result set to variables. When mysqli_stmt_fetch is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....
Note
Note that all columns must be bound after mysqli_stmt_execute and prior to calling mysqli_stmt_fetch. Depending on column types bound variables can silently change to the corresponding PHP type. A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch is called. Parameters
Procedural style only: A statement identifier returned by mysqli_stmt_init. The variable to be bound.
160
/* fetch values */ while ($stmt->fetch()) { printf("%s %s\n", $col1, $col2); } /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close(); ?>
See Also mysqli_stmt_bind_param mysqli_stmt_execute mysqli_stmt_fetch mysqli_prepare mysqli_stmt_prepare mysqli_stmt_init mysqli_stmt_errno mysqli_stmt_error
161
Procedural style
bool mysqli_stmt_close(mysqli_stmt stmt);
Closes a prepared statement. mysqli_stmt_close also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed. Parameters
Procedural style
void mysqli_stmt_data_seek(mysqli_stmt stmt, int offset);
Seeks to an arbitrary result pointer in the statement result set. mysqli_stmt_store_result must be called prior to mysqli_stmt_data_seek. Parameters
162
stmt offset
Procedural style only: A statement identifier returned by mysqli_stmt_init. Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows - 1).
163
Countrycode: NGA
Procedural style
int mysqli_stmt_errno(mysqli_stmt stmt);
Returns the error code for the most recently invoked statement function that can succeed or fail. Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt. Parameters
164
printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $mysqli->query("CREATE TABLE myCountry LIKE Country"); $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry"); /* execute query */ $stmt->execute(); printf("Error: %d.\n", $stmt->errno); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close(); ?>
Error: 1146.
Procedural style
string mysqli_stmt_error(mysqli_stmt stmt);
Returns a containing the error message for the most recently invoked statement function that can succeed or fail. Parameters
A string that describes the error. An empty string if no error occurred. Examples
166
if ($stmt = mysqli_prepare($link, $query)) { /* drop table */ mysqli_query($link, "DROP TABLE myCountry"); /* execute query */ mysqli_stmt_execute($stmt); printf("Error: %s.\n", mysqli_stmt_error($stmt)); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
Procedural style
bool mysqli_stmt_execute(mysqli_stmt stmt);
Executes a query that has been previously prepared using the mysqli_prepare function. When executed any parameter markers which exist will automatically be replaced with the appropriate data. If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows function. Likewise, if the query yields a result set the mysqli_stmt_fetch function is used.
Note
When using mysqli_stmt_execute, the mysqli_stmt_fetch function must be used to fetch the data prior to performing any additional queries. Parameters
stmt
167
168
while ($row = mysqli_fetch_row($result)) { printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); } /* free result set */ mysqli_free_result($result); } /* remove table */ mysqli_query($link, "DROP TABLE myCity"); /* close connection */ mysqli_close($link); ?>
Procedural style
bool mysqli_stmt_fetch(mysqli_stmt stmt);
Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result.
Note
Note that all columns must be bound by the application before calling mysqli_stmt_fetch.
Note
Data are transferred unbuffered without calling mysqli_stmt_store_result which can decrease performance (but reduces memory cost). Parameters
stmt
169
Return Values
Examples
170
Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA)
Procedural style
int mysqli_stmt_field_count(mysqli_stmt stmt);
Warning
This function is currently not documented; only its argument list is available.
171
Procedural style
void mysqli_stmt_free_result(mysqli_stmt stmt);
Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result. Parameters
Procedural style
object mysqli_stmt_get_warnings(mysqli_stmt stmt);
Warning
This function is currently not documented; only its argument list is available.
172
int insert_id ; }
Procedural style
mixed mysqli_stmt_insert_id(mysqli_stmt stmt);
Warning
This function is currently not documented; only its argument list is available.
Procedural style
int mysqli_stmt_num_rows(mysqli_stmt stmt);
Returns the number of rows in the result set. The use of mysqli_stmt_num_rows depends on whether or not you used mysqli_stmt_store_result to buffer the entire result set in the statement handle. If you use mysqli_stmt_store_result, mysqli_stmt_num_rows may be called immediately. Parameters
173
exit(); } $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; if ($stmt = $mysqli->prepare($query)) { /* execute query */ $stmt->execute(); /* store result */ $stmt->store_result(); printf("Number of rows: %d.\n", $stmt->num_rows); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close(); ?>
174
Procedural style
int mysqli_stmt_param_count(mysqli_stmt stmt);
Returns the number of parameter markers present in the prepared statement. Parameters
175
Procedural style
bool mysqli_stmt_prepare(mysqli_stmt stmt, string query);
Prepares the SQL query pointed to by the null-terminated string query. The parameter markers must be bound to application variables using mysqli_stmt_bind_param and/or mysqli_stmt_bind_result before executing the statement or fetching rows.
Note
In the case where you pass a statement to mysqli_stmt_prepare that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). The behavior is as follows: mysqlnd on Linux returns an error code of 1153. The error message means got a packet bigger than max_allowed_packet bytes. mysqlnd on Windows returns an error code 2006. This error message means server has gone away. libmysql on all platforms returns an error code 2006. This error message means server has gone away.
Parameters
stmt query
Procedural style only: A statement identifier returned by mysqli_stmt_init. The query, as a string. It must consist of a single SQL statement. You can include one or more parameter markers in the SQL statement by embedding question 176
Note
You should not add a terminating semicolon or \g to the statement.
Note
The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements. Return Values Returns TRUE on success or FALSE on failure. Examples
177
/* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $district); /* fetch value */ mysqli_stmt_fetch($stmt); printf("%s is in district %s\n", $city, $district); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
Procedural style
bool mysqli_stmt_reset(mysqli_stmt stmt);
Resets a prepared statement on client and server to state after prepare. It resets the statement on the server, data sent using mysqli_stmt_send_long_data, unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it). To prepare a statement with another query use function mysqli_stmt_prepare. Parameters
Procedural style
mysqli_result mysqli_stmt_result_metadata(mysqli_stmt stmt);
If a statement passed to mysqli_prepare is one that produces a result set, mysqli_stmt_result_metadata returns the result object that can be used to process the meta information such as total number of fields and individual field information.
Note
This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as: mysqli_num_fields mysqli_fetch_field mysqli_fetch_field_direct mysqli_fetch_fields mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result
The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result
Note
The result set returned by mysqli_stmt_result_metadata contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch. Parameters
stmt
180
Procedural style
bool mysqli_stmt_send_long_data(mysqli_stmt stmt, int param_nr, string data);
Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes. Parameters
Procedural style only: A statement identifier returned by mysqli_stmt_init. Indicates which parameter to associate the data with. Parameters are numbered beginning with 0. A string containing data to be sent.
Procedural style
string mysqli_stmt_sqlstate(mysqli_stmt stmt);
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html. Parameters
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. Notes
Note
Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors. Examples
Procedural style
<?php
182
/* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TABLE myCountry LIKE Country"); mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = mysqli_prepare($link, $query)) { /* drop table */ mysqli_query($link, "DROP TABLE myCountry"); /* execute query */ mysqli_stmt_execute($stmt); printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt)); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
Error: 42S02.
Procedural style
bool mysqli_stmt_store_result(mysqli_stmt stmt);
You must call mysqli_stmt_store_result for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch call returns buffered data.
Note
It is unnecessary to call mysqli_stmt_store_result for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata returns NULL. 183
Parameters
Procedural style
<?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; if ($stmt = mysqli_prepare($link, $query)) { /* execute query */ mysqli_stmt_execute($stmt); /* store result */ mysqli_stmt_store_result($stmt); printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt)); /* free result */ mysqli_stmt_free_result($stmt); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?>
184
185
Procedural style
int mysqli_field_tell(mysqli_result result);
Returns the position of the field cursor used for the last mysqli_fetch_field call. This value can be used as an argument to mysqli_field_seek. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
186
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = mysqli_query($link, $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { /* get fieldpointer offset */ $currentfield = mysqli_field_tell($result); printf("Column %d:\n", $currentfield); printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags); printf("Type: %d\n\n", $finfo->type); } mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Column 1: Name: Table: max. Len: Flags: Type: Column 2: Name: Table: max. Len: Flags: Type:
187
Procedural style
bool mysqli_data_seek(mysqli_result result, int offset);
The mysqli_data_seek function seeks to an arbitrary result pointer specified by the offset in the result set. Parameters
result offset
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows - 1).
Note
This function can only be used with buffered results attained from the use of the mysqli_store_result or mysqli_query functions. Examples
Procedural style
<?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (!$link) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER BY Name"; if ($result = mysqli_query($link, $query)) { /* seek to row no. 400 */ mysqli_data_seek($result, 399); /* fetch row */
188
$row = mysqli_fetch_row($result); printf ("City: %s Countrycode: %s\n", $row[0], $row[1]); /* free result set*/ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Countrycode: NGA
Procedural style
mixed mysqli_fetch_all(mysqli_result result, int resulttype= =MYSQLI_NUM);
mysqli_fetch_all fetches all result rows and returns the result set as an associative array, a numeric array, or both. Parameters
result resulttype
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC , MYSQLI_NUM , or MYSQLI_BOTH .
189
Return Values Returns an array of associative or numeric arrays holding result rows. MySQL Native Driver Only Available only with mysqlnd. As mysqli_fetch_all returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array, which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all should only be used in those situations where the fetched result set will be sent to another layer for processing. See Also mysqli_fetch_array mysqli_query
Procedural style
mixed mysqli_fetch_array(mysqli_result result, int resulttype= =MYSQLI_BOTH);
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter. mysqli_fetch_array is an extended version of the mysqli_fetch_row function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array function can also store the data in associative indices, using the field names of the result set as keys.
Note
Field names returned by this function are case-sensitive.
Note
This function sets NULL fields to the PHP NULL value. If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used. Parameters
result
mysqli_store_result or mysqli_use_result. resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC , MYSQLI_NUM , or MYSQLI_BOTH . By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc, while MYSQLI_NUM will behave identically to the mysqli_fetch_row function. The final option MYSQLI_BOTH will create a single array with the attributes of both. Return Values Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3"; $result = mysqli_query($link, $query); /* numeric array */ $row = mysqli_fetch_array($result, MYSQLI_NUM); printf ("%s (%s)\n", $row[0], $row[1]); /* associative array */ $row = mysqli_fetch_array($result, MYSQLI_ASSOC); printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]); /* associative and numeric array */ $row = mysqli_fetch_array($result, MYSQLI_BOTH); printf ("%s (%s)\n", $row[0], $row["CountryCode"]); /* free result set */ mysqli_free_result($result); /* close connection */ mysqli_close($link); ?>
Procedural style
array mysqli_fetch_assoc(mysqli_result result);
Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note
Field names returned by this function are case-sensitive.
Note
This function sets NULL fields to the PHP NULL value. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Return Values Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row or add alias names.
192
Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5"; if ($result = mysqli_query($link, $query)) { /* fetch associative array */ while ($row = mysqli_fetch_assoc($result)) { printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]); } /* free result set */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
Copyright 1997-2010 the PHP Documentation Group. mysqli_result::fetch_field_direct mysqli_fetch_field_direct Fetch meta-data for a single field Description Object oriented style
object mysqli_result::fetch_field_direct(int fieldnr);
Procedural style
object mysqli_fetch_field_direct(mysqli_result result, int fieldnr);
Returns an object which contains field definition information from the specified result set. Parameters
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. The field number. This value must be in the range from 0 to number of fields - 1.
Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.
194
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5"; if ($result = $mysqli->query($query)) { /* Get field information for column 'SurfaceArea' */ $finfo = $result->fetch_field_direct(1); printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags); printf("Type: %d\n", $finfo->type); $result->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5"; if ($result = mysqli_query($link, $query)) { /* Get field information for column 'SurfaceArea' */ $finfo = mysqli_fetch_field_direct($result, 1); printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags); printf("Type: %d\n", $finfo->type); mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
195
mysqli_fetch_field Returns the next field in the result set Description Object oriented style
object mysqli_result::fetch_field();
Procedural style
object mysqli_fetch_field(mysqli_result result);
Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Return Values Returns an object which contains field definition information or FALSE if no field information is available.
196
while ($finfo = $result->fetch_field()) { printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags); printf("Type: %d\n\n", $finfo->type); } $result->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = mysqli_query($link, $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags); printf("Type: %d\n\n", $finfo->type); } mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Name: Table: max. Len: Flags: Type: Name: Table: max. Len: Flags: Type:
197
Returns an array of objects representing the fields in a result set Description Object oriented style
array mysqli_result::fetch_fields();
Procedural style
array mysqli_fetch_fields(mysqli_result result);
This function serves an identical purpose to the mysqli_fetch_field function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Return Values Returns an array of objects which contains field definition information or FALSE if no field information is available.
198
printf("Table: printf("max. Len: printf("Flags: printf("Type: } $result->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = mysqli_query($link, $query)) { /* Get field information for all columns */ $finfo = mysqli_fetch_fields($result); foreach ($finfo as $val) { printf("Name: %s\n", $val->name); printf("Table: %s\n", $val->table); printf("max. Len: %d\n", $val->max_length); printf("Flags: %d\n", $val->flags); printf("Type: %d\n\n", $val->type); } mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Name: Table: max. Len: Flags: Type: Name: Table: max. Len: Flags: Type:
Procedural style
object mysqli_fetch_object(mysqli_result result, string class_name, array params);
The mysqli_fetch_object will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. Note that mysqli_fetch_object sets the properties of the object before calling the object constructor. Parameters
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned. An optional array of parameters to pass to the constructor for class_name objects.
Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.
Note
Field names returned by this function are case-sensitive.
Note
This function sets NULL fields to the PHP NULL value. Changelog Version 5.0.0 Examples Description Added the ability to return as a different object.
200
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5"; if ($result = mysqli_query($link, $query)) { /* fetch associative array */ while ($obj = mysqli_fetch_object($result)) { printf ("%s (%s)\n", $obj->Name, $obj->CountryCode); } /* free result set */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
201
Procedural style
mixed mysqli_fetch_row(mysqli_result result);
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Return Values mysqli_fetch_row returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.
Note
This function sets NULL fields to the PHP NULL value. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5"; if ($result = mysqli_query($link, $query)) { /* fetch associative array */ while ($row = mysqli_fetch_row($result)) { printf ("%s (%s)\n", $row[0], $row[1]); } /* free result set */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
202
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
Procedural style
int mysqli_num_fields(mysqli_result result);
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
203
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) { /* determine number of fields in result set */ $field_cnt = $result->field_count; printf("Result set has %d fields.\n", $field_cnt); /* close result set */ $result->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) { /* determine number of fields in result set */ $field_cnt = mysqli_num_fields($result); printf("Result set has %d fields.\n", $field_cnt); /* close result set */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
204
Procedural style
bool mysqli_field_seek(mysqli_result result, int fieldnr);
Sets the field cursor to the given offset. The next call to mysqli_fetch_field will retrieve the field definition of the column associated with that offset.
Note
To seek to the beginning of a row, pass an offset value of zero. Parameters
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. The field number. This value must be in the range from 0 to number of fields - 1.
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = mysqli_query($link, $query)) { /* Get field information for 2nd column */ mysqli_field_seek($result, 1); $finfo = mysqli_fetch_field($result); printf("Name: %s\n", $finfo->name); printf("Table: %s\n", $finfo->table); printf("max. Len: %d\n", $finfo->max_length); printf("Flags: %d\n", $finfo->flags);
205
Procedural style
void mysqli_free_result(mysqli_result result);
Note
You should always free your result with mysqli_free_result, when your result object is not needed anymore. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
206
Return Values No value is returned. See Also mysqli_query mysqli_stmt_store_result mysqli_store_result mysqli_use_result
Procedural style
array mysqli_fetch_lengths(mysqli_result result);
The mysqli_fetch_lengths function returns an array containing the lengths of every column of the current row within the result set. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Return Values An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred. mysqli_fetch_lengths is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result. Examples
207
} $query = "SELECT * from Country ORDER BY Code LIMIT 1"; if ($result = $mysqli->query($query)) { $row = $result->fetch_row(); /* display column lengths */ foreach ($result->lengths as $i => $val) { printf("Field %2d has Length %2d\n", $i+1, $val); } $result->close(); } /* close connection */ $mysqli->close(); ?>
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT * from Country ORDER BY Code LIMIT 1"; if ($result = mysqli_query($link, $query)) { $row = mysqli_fetch_row($result); /* display column lengths */ foreach (mysqli_fetch_lengths($result) as $i => $val) { printf("Field %2d has Length %2d\n", $i+1, $val); } mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>
Field Field Field Field Field Field Field Field Field Field Field Field Field Field Field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
has has has has has has has has has has has has has has has
Length 3 Length 5 Length 13 Length 9 Length 6 Length 1 Length 6 Length 4 Length 6 Length 6 Length 5 Length 44 Length 7 Length 3 Length 2
208
Procedural style
int mysqli_num_rows(mysqli_result result);
Returns the number of rows in the result set. The use of mysqli_num_rows depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows will not return the correct number of rows until all the rows in the result have been retrieved. Parameters
result
Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.
Note
If the number of rows is greater than maximal int value, the number will be returned as a string. Examples
Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = mysqli_num_rows($result); printf("Result set has %d rows.\n", $row_cnt); /* close result set */
209
The Client API header version The Client version The MySQLi Driver version Wether MySQLi Embedded support is enabled Allow or prevent reconnect (see the mysqli.reconnect INI directive) 210
report_mode
Set to MYSQLI_REPORT_OFF , MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors), MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes). See also mysqli_report.
Procedural style
void mysqli_embedded_server_end();
Warning
This function is currently not documented; only its argument list is available.
Procedural style
bool mysqli_embedded_server_start(bool start, array arguments, array groups);
Warning
This function is currently not documented; only its argument list is available.
211
2.11.1. mysqli_warning::__construct
Copyright 1997-2010 the PHP Documentation Group. mysqli_warning::__construct The __construct purpose Description
mysqli_warning::__construct();
Warning
This function is currently not documented; only its argument list is available. Parameters This function has no parameters. Return Values
2.11.2. mysqli_warning::next
Copyright 1997-2010 the PHP Documentation Group. mysqli_warning::next The next purpose 212
Description
public void mysqli_warning::next();
Warning
This function is currently not documented; only its argument list is available. Parameters This function has no parameters. Return Values
2.12.1. mysqli_bind_param
Copyright 1997-2010 the PHP Documentation Group. mysqli_bind_param Alias for mysqli_stmt_bind_param Description This function is an alias of mysqli_stmt_bind_param. Notes
Note
mysqli_bind_param is deprecated and will be removed. See Also mysqli_stmt_bind_param
2.12.2. mysqli_bind_result
Copyright 1997-2010 the PHP Documentation Group. mysqli_bind_result Alias for mysqli_stmt_bind_result Description This function is an alias of mysqli_stmt_bind_result. Notes
Note
mysqli_bind_result is deprecated and will be removed. 213
2.12.3. mysqli_client_encoding
Copyright 1997-2010 the PHP Documentation Group. mysqli_client_encoding Alias of mysqli_character_set_name Description This function is an alias of mysqli_character_set_name. See Also mysqli_real_escape_string
2.12.4. mysqli_connect
Copyright 1997-2010 the PHP Documentation Group. mysqli_connect Alias of mysqli::__construct Description This function is an alias of: mysqli::__construct
Procedural style
bool mysqli_disable_reads_from_master(mysqli link);
Warning
This function is currently not documented; only its argument list is available. 214
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.6. mysqli_disable_rpl_parse
Copyright 1997-2010 the PHP Documentation Group. mysqli_disable_rpl_parse Disable RPL parse Description
bool mysqli_disable_rpl_parse(mysqli link);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.7. mysqli_enable_reads_from_master
Copyright 1997-2010 the PHP Documentation Group. mysqli_enable_reads_from_master Enable reads from master Description
bool mysqli_enable_reads_from_master(mysqli link);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.8. mysqli_enable_rpl_parse
Copyright 1997-2010 the PHP Documentation Group. mysqli_enable_rpl_parse Enable RPL parse Description
bool mysqli_enable_rpl_parse(mysqli link);
Warning
215
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.9. mysqli_escape_string
Copyright 1997-2010 the PHP Documentation Group. mysqli_escape_string Alias of mysqli_real_escape_string Description This function is an alias of: mysqli_real_escape_string.
2.12.10. mysqli_execute
Copyright 1997-2010 the PHP Documentation Group. mysqli_execute Alias for mysqli_stmt_execute Description This function is an alias of mysqli_stmt_execute. Notes
Note
mysqli_execute is deprecated and will be removed. See Also mysqli_stmt_execute
2.12.11. mysqli_fetch
Copyright 1997-2010 the PHP Documentation Group. mysqli_fetch Alias for mysqli_stmt_fetch Description This function is an alias of mysqli_stmt_fetch. Notes
Note
mysqli_fetch is deprecated and will be removed.
216
2.12.12. mysqli_get_cache_stats
Copyright 1997-2010 the PHP Documentation Group. mysqli_get_cache_stats Returns client Zval cache statistics Description
array mysqli_get_cache_stats();
Warning
This function is currently not documented; only its argument list is available. Returns client Zval cache statistics. Available only with mysqlnd. Parameters Return Values Returns an array with client Zval cache stats if success, FALSE otherwise. Examples
Array ( [bytes_sent] => 43 [bytes_received] => 80 [packets_sent] => 1 [packets_received] => 2 [protocol_overhead_in] => 8 [protocol_overhead_out] => 4 [bytes_received_ok_packet] => 11 [bytes_received_eof_packet] => 0 [bytes_received_rset_header_packet] => 0 [bytes_received_rset_field_meta_packet] => 0 [bytes_received_rset_row_packet] => 0 [bytes_received_prepare_response_packet] => 0 [bytes_received_change_user_packet] => 0 [packets_sent_command] => 0 [packets_received_ok] => 1 [packets_received_eof] => 0 [packets_received_rset_header] => 0 [packets_received_rset_field_meta] => 0 [packets_received_rset_row] => 0 [packets_received_prepare_response] => 0 [packets_received_change_user] => 0 [result_set_queries] => 0
217
[non_result_set_queries] => 0 [no_index_used] => 0 [bad_index_used] => 0 [slow_queries] => 0 [buffered_sets] => 0 [unbuffered_sets] => 0 [ps_buffered_sets] => 0 [ps_unbuffered_sets] => 0 [flushed_normal_sets] => 0 [flushed_ps_sets] => 0 [ps_prepared_never_executed] => 0 [ps_prepared_once_executed] => 0 [rows_fetched_from_server_normal] => 0 [rows_fetched_from_server_ps] => 0 [rows_buffered_from_client_normal] => 0 [rows_buffered_from_client_ps] => 0 [rows_fetched_from_client_normal_buffered] => 0 [rows_fetched_from_client_normal_unbuffered] => 0 [rows_fetched_from_client_ps_buffered] => 0 [rows_fetched_from_client_ps_unbuffered] => 0 [rows_fetched_from_client_ps_cursor] => 0 [rows_skipped_normal] => 0 [rows_skipped_ps] => 0 [copy_on_write_saved] => 0 [copy_on_write_performed] => 0 [command_buffer_too_small] => 0 [connect_success] => 1 [connect_failure] => 0 [connection_reused] => 0 [reconnect] => 0 [pconnect_success] => 0 [active_connections] => 1 [active_persistent_connections] => 0 [explicit_close] => 0 [implicit_close] => 0 [disconnect_close] => 0 [in_middle_of_command_close] => 0 [explicit_free_result] => 0 [implicit_free_result] => 0 [explicit_stmt_close] => 0 [implicit_stmt_close] => 0 [mem_emalloc_count] => 0 [mem_emalloc_ammount] => 0 [mem_ecalloc_count] => 0 [mem_ecalloc_ammount] => 0 [mem_erealloc_count] => 0 [mem_erealloc_ammount] => 0 [mem_efree_count] => 0 [mem_malloc_count] => 0 [mem_malloc_ammount] => 0 [mem_calloc_count] => 0 [mem_calloc_ammount] => 0 [mem_realloc_count] => 0 [mem_realloc_ammount] => 0 [mem_free_count] => 0 [proto_text_fetched_null] => 0 [proto_text_fetched_bit] => 0 [proto_text_fetched_tinyint] => 0 [proto_text_fetched_short] => 0 [proto_text_fetched_int24] => 0 [proto_text_fetched_int] => 0 [proto_text_fetched_bigint] => 0 [proto_text_fetched_decimal] => 0 [proto_text_fetched_float] => 0 [proto_text_fetched_double] => 0 [proto_text_fetched_date] => 0 [proto_text_fetched_year] => 0 [proto_text_fetched_time] => 0 [proto_text_fetched_datetime] => 0 [proto_text_fetched_timestamp] => 0 [proto_text_fetched_string] => 0 [proto_text_fetched_blob] => 0 [proto_text_fetched_enum] => 0 [proto_text_fetched_set] => 0 [proto_text_fetched_geometry] => 0 [proto_text_fetched_other] => 0 [proto_binary_fetched_null] => 0 [proto_binary_fetched_bit] => 0 [proto_binary_fetched_tinyint] => 0 [proto_binary_fetched_short] => 0 [proto_binary_fetched_int24] => 0 [proto_binary_fetched_int] => 0 [proto_binary_fetched_bigint] => 0 [proto_binary_fetched_decimal] => 0 [proto_binary_fetched_float] => 0 [proto_binary_fetched_double] => 0 [proto_binary_fetched_date] => 0 [proto_binary_fetched_year] => 0 [proto_binary_fetched_time] => 0 [proto_binary_fetched_datetime] => 0
218
[proto_binary_fetched_timestamp] => 0 [proto_binary_fetched_string] => 0 [proto_binary_fetched_blob] => 0 [proto_binary_fetched_enum] => 0 [proto_binary_fetched_set] => 0 [proto_binary_fetched_geometry] => 0 [proto_binary_fetched_other] => 0 )
2.12.13. mysqli_get_metadata
Copyright 1997-2010 the PHP Documentation Group. mysqli_get_metadata Alias for mysqli_stmt_result_metadata Description This function is an alias of mysqli_stmt_result_metadata. Notes
Note
mysqli_get_metadata is deprecated and will be removed. See Also mysqli_stmt_result_metadata
2.12.14. mysqli_master_query
Copyright 1997-2010 the PHP Documentation Group. mysqli_master_query Enforce execution of a query on the master in a master/slave setup Description
bool mysqli_master_query(mysqli link, string query);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.15. mysqli_param_count
219
Copyright 1997-2010 the PHP Documentation Group. mysqli_param_count Alias for mysqli_stmt_param_count Description This function is an alias of mysqli_stmt_param_count. Notes
Note
mysqli_param_count is deprecated and will be removed. See Also mysqli_stmt_param_count
2.12.16. mysqli_report
Copyright 1997-2010 the PHP Documentation Group. mysqli_report Enables or disables internal report functions Description
bool mysqli_report(int flags);
mysqli_report is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index). Parameters
flags
220
Description Changing the reporting mode is now be per-request, rather than per-process.
Examples
2.12.17. mysqli_rpl_parse_enabled
Copyright 1997-2010 the PHP Documentation Group. mysqli_rpl_parse_enabled Check if RPL parse is enabled Description
int mysqli_rpl_parse_enabled(mysqli link);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.18. mysqli_rpl_probe
Copyright 1997-2010 the PHP Documentation Group. mysqli_rpl_probe 221
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
Procedural style
int mysqli_rpl_query_type(mysqli link, string query);
Returns MYSQLI_RPL_MASTER , MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.20. mysqli_send_long_data
Copyright 1997-2010 the PHP Documentation Group. mysqli_send_long_data Alias for mysqli_stmt_send_long_data Description 222
Note
mysqli_send_long_data is deprecated and will be removed. See Also mysqli_stmt_send_long_data
Procedural style
bool mysqli_send_query(mysqli link, string query);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
2.12.22. mysqli_set_opt
Copyright 1997-2010 the PHP Documentation Group. mysqli_set_opt Alias of mysqli_options Description This function is an alias of mysqli_options.
2.12.23. mysqli_slave_query
Copyright 1997-2010 the PHP Documentation Group. 223
Description
bool mysqli_slave_query(mysqli link, string query);
Warning
This function is currently not documented; only its argument list is available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
224
3.1. Overview
Copyright 1997-2010 the PHP Documentation Group. MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0. The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol. With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library. MySQL Native Driver is written in C as a PHP extension. What it is not Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API. Why use it? Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library. The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past. Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications. Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory. Special features MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below: Improved persistent connections The special function mysqli_fetch_all Performance statistics calls: mysqli_get_cache_stats, mysqli_get_client_stats, mysqli_get_connection_stats
225
The performance statistics facility can prove to be very useful in identifying performance bottlenecks. MySQL Native Driver also allows for persistent connections when used with the mysqli extension. SSL Support MySQL Native Driver has supported SSL since PHP version 5.3.3 Compressed Protocol Support As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, that are configured to use MySQL Native Driver, can also take advantage of this feature. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd. Named Pipes Support Named pipes support for Windows was added in PHP version 5.3.4.
3.2. Installation
Copyright 1997-2010 the PHP Documentation Group. Installation on Unix By default the MySQL database extensions are configured to use MySQL Client Library. In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code. For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:
./configure --with-mysql=mysqlnd \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ [other options]
Installation on Windows In the official PHP distributions from 5.3 onwards, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.
mysqlnd.collect_memory_statist "0" ics mysqlnd.debug mysqlnd.net_read_timeout mysqlnd.net_cmd_buffer_size mysqlnd.net_read_buffer_size "0" "31536000" 5.3.0 - "2048", 5.3.1 - "4096" "32768"
For further details and definitions of the PHP_INI_* modes, see the configuration.changes.modes.
226
mysqlnd.collect_statisti Enables the collection of various client statistics which can be accessed through cs boolean mysqli_get_client_stats, mysqli_get_connection_stats, mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well. This configuration setting enables all MySQL Native Driver statistics except those relating to memory management. mysqlnd.collect_memory_s Enable the collection of various memory statistics which can be accessed through tatistics boolean mysqli_get_client_stats, mysqli_get_connection_stats, mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well. This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics. mysqlnd.debug string Records communication from all extensions using mysqlnd to the specified log file. The format of the directive is mysqlnd.debug = "option1[,parameter_option1][:option2[,parameter_option2]]". The options for the format string are as follows: A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash. a[,file] - Appends trace output to the specified file. d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros. f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected. F - Marks each debugger output line with the name of the source file containing the macro causing the output. i - Marks each debugger output line with the PID of the current process. L - Marks each debugger output line with the name of the source file line number of the macro causing the output. n - Marks each debugger output line with the current function nesting depth o[,file] - Similar to a[,file] but overwrites old file, and does not append. O[,file] - Similar to A[,file] but overwrites old file, and does not append. t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200. x - This option activates profiling.
Example:
d:t:x:O,/tmp/mysqlnd.trace
Note
This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and 227
PHP was built using Microsoft Visual C version 9 and above. mysqlnd.net_read_timeout mysqlnd and the MySQL Client Library, libmysql use different networking APIs. mysqlnd integer uses PHP streams, whereas libmysql uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message 2006 MySQL Server has gone away. The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout. The value is configurable through a new php.ini setting: mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by any extension (ext/mysql, ext/mysqli, PDO_MySQL) that uses mysqlnd. mysqlnd tells PHP Streams to use mysqlnd.net_read_timeout. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt. mysqlnd.net_cmd_buffer_s mysqlnd allocates an internal command/network buffer of ize long mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, command_buffer_too_small will be incremented by one. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, you should consider increasing the default size to avoid re-allocations. The default buffer size is 2048 bytes in PHP 5.3.0. In later versions the default is 4096 bytes. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size). It is recommended that the buffer size be set to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence, mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message, or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields() and the meta data come from a string column with a very long default value (>1900 bytes). As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes. The value can also be set using mysqli_option(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size). mysqlnd.net_read_buffer_ Maximum read chunk size in bytes when reading the body of a MySQL command packet. The size long MySQL client server protocol encapsulates all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. mysqlnd reads the body in chunks of MIN(header.size, mysqlnd.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call read() multiple times. The value can also be set using mysqli_optionS(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size).
Copyright 1997-2010 the PHP Documentation Group. Using Persistent Connections If mysqli is used with mysqlnd, when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server. This ensures that re-authentication of the connection takes place. As there is some overhead associated with the COM_CHANGE_USER call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable. Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT. For example:
Or alternatively:
shell# shell# shell# shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" configure --whatever-option make clean make
Note that only mysqli on mysqlnd uses COM_CHANGE_USER. Other extension-driver combinations use COM_PING on initial use of a persistent connection.
3.5. Statistics
Copyright 1997-2010 the PHP Documentation Group. Using Statistical Data MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of three main types: Client statistics Connection statistics Zval cache statistics
If you are using the mysqli extension, these statistics can be obtained through three API calls: mysqli_get_client_stats mysqli_get_connection_stats mysqli_get_cache_stats
Note
Statistics are aggregated among all extensions that use MySQL Native Driver. For example, when compiling both ext/ mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics. Accessing Client Statistics To access client statistics, you need to call mysqli_get_client_stats. The function call does not require any parameters. 229
The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value. Client statistics can also be accessed by calling the phpinfo function. Accessing Connection Statistics To access connection statistics call mysqli_get_connection_stats. This takes the database connection handle as the parameter. The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value. Accessing Zval Cache Statistics The MySQL Native Driver also collects statistics from its internal Zval cache. These statistics can be accessed by calling mysqli_get_cache_stats. The Zval cache statistics obtained may lead to a tweaking of php.ini settings related to the Zval cache, resulting in better performance. Buffered and Unbuffered Result Sets Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client. Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. Load does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed. Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result to enable buffered result sets. Statistics returned by MySQL Native Driver The following tables show a list of statistics returned by the mysqli_get_client_stats, mysqli_get_connection_stats and mysqli_get_cache_stats functions. Network Statistic bytes_sent Scope Connection Description Notes
Number of bytes sent from PHP Can be used to check the effito the MySQL server ciency of the compression protocol Number of bytes received from MySQL server Can be used to check the efficiency of the compression protocol
bytes_received
Connection
Number of MySQL Client Serv- Used for debugging Client Server protocol packets sent er protocol implementation Number of MySQL Client Serv- Used for debugging Client Server protocol packets received er protocol implementation MySQL Client Server protocol Used for debugging Client Servoverhead in bytes for incoming er protocol implementation traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_in = packets_received * 4 MySQL Client Server protocol Used for debugging Client Servoverhead in bytes for outgoing er protocol implementation traffic. Currently only the Packet 230
protocol_overhead_out
Connection
Statistic
Scope
Notes
bytes_received_ok_pac ket
Connection
Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed.
Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok
Connection
Number of MySQL Client Serv- Used for debugging CS protocol er protocol OK packets received. implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message. Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message. Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE, INSERT, UPDATE, SELECT, error message). Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_pa cket
Connection
packets_received_eof
Connection
bytes_received_rset_h eader_packet
Connection
Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_hea der
Connection
Number of MySQL Client Serv- Used for debugging CS protocol er protocol result set header implementation. Note that the packets. total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Total size in bytes of MySQL Client Server protocol result set meta data (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_f ield_meta_packet
Connection
packets_received_rset_fie ld_meta
Connection
Number of MySQL Client Serv- Only useful for debugging CS er protocol result set meta data protocol implementation. Note (field information) packets. that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an 231 Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header
bytes_received_rset_r ow_packet
Connection
Statistic
Scope
Description
Notes
EOF packet. You can reverse packet (4 bytes, see protocol engineer the number of error and overhead). EOF packets by substracting rows_fetched_from_ser ver_normal and rows_fetched_from_ser ver_ps from bytes_received_rset_r ow_packet. packets_received_rset_row Connection Number of MySQL Client Server protocol result set row data packets and their total size in bytes. Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepar e_response_packet
Connection
Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occurred if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepar e_response_packet != packets_received_prepare_ response * 12. See also ps_prepared_never_exe cuted, ps_prepared_once_exec uted. Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. Number of MySQL Client Server protocol COM_CHANGE_USER packets
packets_received_prepare_ response
Connection
Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead). Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change _user_packet
Connection
packets_received_change_u ser
Connection
packets_sent_command
Connection
Number of MySQL Client Serv- Only useful for debugging CS er protocol commands sent from protocol implementation. 232
Statistic
Scope
Description PHP to MySQL. There is no way to know which specific commands and how many of them have been sent. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. The only error recoded is command_buffer_too_small (see below).
Notes
bytes_received_real_d ata_normal
Connection
Number of bytes of payload fetched by the PHP client from mysqlnd using the text protocol.
This is the size of the actual data contained in result sets that do not originate from prepared statements and which have been fetched by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. An example of a code sequence that will increase the value is as follows:
Every fetch operation will increase the value. The statistic will not be increased if the result set is only buffered on the client, but not fetched, such as in the following example:
This statistic is available as of PHP version 5.3.4. bytes_received_real_d ata_ps Connection Number of bytes of the payload fetched by the PHP client from mysqlnd using the prepared statement protocol. This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client.
233
Statistic
Scope
Description
Notes See also bytes_received_real_da ta_normal. This statistic is available as of PHP version 5.3.4.
Result Set Statistic result_set_queries Scope Connection Description Number of queries that have generated a result set. Examples of queries that generate a result set: SELECT, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. Number of queries that did not generate a result set. Examples of queries that do not generate a result set: INSERT, UPDATE, LOAD DATA, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. Number of queries that have generated a result set but did not use an index (see also mysqld start option log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPO RT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPO RT_INDEX ^ MYSQLI_REPORT_STRICT). Number of queries that have generated a result set and did not use a good index (see also mysqld start option log-slow-queries). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPO RT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPO RT_INDEX ^ MYSQLI_REPORT_STRICT) Notes You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_querie s
Connection
You may use it an an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used
Connection
bad_index_used
Connection
slow_queries
Connection
SQL statements that took more Not reported through than long_query_time mysqli_report seconds to execute and required at least min_examined_row_limi t rows to be examined. Number of buffered result sets returned by normal queries. 234 Examples of API calls that will buffer result sets on the client:
buffered_sets
Connection
Statistic
Scope
235
Statistic
Scope
Description
Notes . Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage reports a higer memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets
Connection
Number of unbuffered result sets returned by normal (non prepared statement) queries. Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. Number of unbuffered result sets returned by prepared statements. Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets.
Examples of API calls that will not buffer result sets on the client: mysqli_use_result Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_resu lt By default prepared statements are unbuffered. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush: Faulty client application Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed Client application has
ps_buffered_sets
Connection
ps_unbuffered_sets
Connection
flushed_normal_sets
Connection
236
Statistic
Scope
Description
flushed_ps_sets
Connection
Number of result sets from prepared statements with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets.
Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush: Faulty client application Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed Client application has stopped unexpectedly
ps_prepared_never_exe cuted
Connection
Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it. One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and cache results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to normal queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts. See also packets_received_rset_row
ps_prepared_once_exec uted
Connection
Connection
Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them 237
Statistic
Scope
Description or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly.
Notes
Connection
Total number of succesfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement. Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement. Total number of rows fetch by the client from a cursor created by a prepared statement. Reserved for future use (currently not supported) With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage. 238
Connection
rows_fetched_from_cli Connection ent_normal_unbuffered, rows_fetched_from_cli ent_ps_unbuffered rows_fetched_from_cli ent_ps_cursor rows_skipped_normal, rows_skipped_ps copy_on_write_saved, copy_on_write_perform ed Connection
Connection Process
Scope
Description
Notes The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_ INIT_COMMAND , ...)
Connection, Process (only dur- Total number of freed result ing prepared statement cleanup) sets.
proto_text_fetched_nu ll, proto_text_fetched_bi t, proto_text_fetched_ti nyint proto_text_fetched_sh ort, proto_text_fetched_in t24, proto_text_fetched_in t proto_text_fetched_bi gint, proto_text_fetched_de cimal, proto_text_fetched_fl oat proto_text_fetched_do uble, proto_text_fetched_da te, proto_text_fetched_ye ar proto_text_fetched_ti me, proto_text_fetched_da tetime, proto_text_fetched_ti mestamp proto_text_fetched_st ring, proto_text_fetched_bl ob, proto_text_fetched_en um proto_text_fetched_se t, proto_text_fetched_ge ometry, proto_text_fetched_ot her
Connection
Total number of columns of a Mapping from C API / MySQL certain type fetched from a nor- meta data type to statistics mal query (MySQL text proname: tocol). MYSQL_TYPE_NULL proto_text_fetched_null MYSQL_TYPE_BIT proto_text_fetched_bit MYSQL_TYPE_TINY proto_text_fetched_tinyint MYSQL_TYPE_SHORT proto_text_fetched_short MYSQL_TYPE_INT24 proto_text_fetched_int24 MYSQL_TYPE_LONG proto_text_fetched_int MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIM AL proto_text_fetched_decimal MYSQL_TYPE_FLOAT proto_text_fetched_float MYSQL_TYPE_DOUBLE proto_text_fetched_double MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE proto_text_fetched_date MYSQL_TYPE_YEAR proto_text_fetched_year MYSQL_TYPE_TIME proto_text_fetched_time MYSQL_TYPE_DATETIME proto_text_fetched_datetime MYSQL_TYPE_TIMESTAM Pproto_text_fetched_timestam p MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRIN
239
Statistic
Scope
Description
Notes G, MYSQL_TYPE_VARCHAR proto_text_fetched_string MYSQL_TYPE_TINY_BLO B, MYSQL_TYPE_MEDIUM_B LOB, MYSQL_TYPE_LONG_BLO B, MYSQL_TYPE_BLOB proto_text_fetched_blob MYSQL_TYPE_ENUM proto_text_fetched_enum MYSQL_TYPE_SET proto_text_fetched_set MYSQL_TYPE_GEOMETRY proto_text_fetched_geometr y Any MYSQL_TYPE_* not listed before (there should be none) proto_text_fetched_other
Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL. proto_binary_fetched_ null, proto_binary_fetched_ bit, proto_binary_fetched_ tinyint proto_binary_fetched_ short, proto_binary_fetched_ int24, proto_binary_fetched_ int, proto_binary_fetched_ bigint, proto_binary_fetched_ decimal, proto_binary_fetched_ float, proto_binary_fetched_ double, proto_binary_fetched_ date, proto_binary_fetched_ year, proto_binary_fetched_ time, proto_binary_fetched_ datetime, Connection Total number of columns of a For type mapping see certain type fetched from a pre- proto_text_* described in pared statement (MySQL binary the preceding text. protocol).
240
Statistic proto_binary_fetched_ timestamp, proto_binary_fetched_ string, proto_binary_fetched_ blob, proto_binary_fetched_ enum, proto_binary_fetched_ set, proto_binary_fetched_ geometry, proto_binary_fetched_ other
Scope
Description
Notes
Connection Statistic connect_success, connect_failure reconnect Scope Connection Description Total number of successful / failed connection attempt. Total number of (real_)connect attempts made on an already opened connection handle. Notes Reused connections and all other kinds of connections are included. The code sequence $link = new mysqli(...); $link->real_connect(.. .) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
Process
pconnect_success
Connection
Total number of successful per- Note that connect_success sistent connection attempts. holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success. Total number of active persistent and non-persistent connections. Total number of active persistent connections. The total number of active nonpersistent connections is active_connections - active_persistent_connect ions. Examples of code snippets that cause an explicit close :
active_connections
Connection
active_persistent_connec tions
Connection
explicit_close
Connection
implicit_close
Connection
Statistic
Scope
Description
Notes $link = new mysqli(...); $link->real_connect (...) unset($link) Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options Persistent connection: ping/ change_user fails and ext/ mysqli closes the connection end of script execution: close connections that have not been closed by the user
disconnect_close
Connection
Connection failures indicated by the C API call mysql_real_connect during an attempt to establish a connection. A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA). Total number of init command executions, for example, mysqli_options(MYSQLI _INIT_COMMAND , ...).
It is called disconnect_close because the connection handle passed to the C API call will be closed. Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
in_middle_of_command_ close
Process
init_command_executed _count
Connection
init_command_failed_c ount
Connection
COM_* Commands Statistic com_quit, com_init_db, com_query, com_field_list, com_create_db, com_drop_db, com_refresh, com_shutdown, com_statistics, com_process_info, com_connect, com_process_kill, Scope Connection Description Total number of attempts to send a certain COM_* command from PHP to MySQL. Notes The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure mysqlnd emits a PHP warning Error while sending
242
Statistic com_debug, com_ping, com_time, com_delayed_insert, com_change_user, com_binlog_dump, com_table_dump, com_connect_out, com_register_slave, com_stmt_prepare, com_stmt_execute, com_stmt_send_long_da ta, com_stmt_close, com_stmt_reset, com_stmt_set_option, com_stmt_fetch, com_daemon
Scope
Description
Notes %s packet. PID=%d. Usage examples: Check if PHP sends certain commands to MySQL, for example, check if a client sends COM_PROCESS_KILL Calculate the average number of prepared statement executions by comparing COM_EXECUTE with COM_PREPARE Check if PHP has run any non-prepared SQL statements by checking if COM_QUERY is zero Identify PHP scripts that run an excessive number of SQL statements by checking COM_QUERY and COM_EXECUTE
Miscellaneous Statistic explicit_stmt_close, implicit_stmt_close mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count command_buffer_too_small Scope Process Process Description Total number of close prepared statements. Memory management calls. Notes A close is always considered explicit but for a failed prepare. Development only.
Connection
Number of network command buffer extensions while sending mysqlnd allocates an internal command/network buffer of commands from PHP to mysqlnd.net_cmd_buffer MySQL. _size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the 243
Statistic
Scope
Description
Notes command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer _size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid reallocations. The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer _size or using mysqli_options(MYSQLI_ OPT_NET_CMD_BUFFER_SIZ E, int size). It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer _size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields) and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists - it should happen rarely. As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.
connection_reused
244
3.6. Notes
Copyright 1997-2010 the PHP Documentation Group. This section provides a collection of miscellaneous notes on MySQL Native Driver usage. Using mysqlnd means using PHP streams for underlying connectivity. For mysqlnd, the PHP streams documentation (book.stream) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.
Monitoring Query Logging Query Analysis Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. This extension inspects queries and executes only those that are allowed according to a ruleset.
Performance Caching. An example of this is the PECL/mysqlnd_qc (Query Cache) extension. Throttling Sharding. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. This extension will attempt to split a SELECT statement into n-parts, using SELECT ... LIMIT part_1, SELECT LIMIT part_n. It sends the queries to distinct MySQL servers and merges the result at the client.
245
MySQL Native Driver Plugins Available There are a number of mysqlnd plugins already available. These include: PECL/mysqlnd_mc - Multi Connect plugin. PECL/mysqlnd_ms - Master Slave plugin. PECL/mysqlnd_qc - Query Cache plugin. PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin. PECL/mysqlnd_sip - SQL Injection Protection plugin. PECL/mysqlnd_uh - User Handler plugin.
MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications. However, MySQL Proxy does have some disadvantages: MySQL Proxy is a new component and technology to master and deploy. MySQL Proxy requires knowledge of the Lua scripting language.
MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A mysqlnd plugin can be written in C. It is also possible to write plugins in PHP using PECL/mysqlnd_uh. MySQL Proxy runs as a daemon - a background process. MySQL Proxy can recall earlier decisions, as all state can be retained. However, a mysqlnd plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can also share one-time computed results among multiple application servers. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. Another daemon would need to be used for this purpose, such as Memcache. This gives MySQL Proxy an advantage in this case. MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to those that can be achieved by manipulating the communication protocol. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well. Mysqlnd plugins work on top of the C API, which mirrors the libmysql client and Connector/C APIs. This C API is basically a wrapper around the MySQL Client Server protocol, or wire protocol, as it is sometimes called. You can intercept all C API calls. PHP makes use of the C API, therefore you can hook all PHP calls, without the need to program at the level of the wire protocol. Mysqlnd implements the wire protocol. Plugins can therefore parse, reverse engineer, manipulate and even replace the communication 246
protocol. However, this is usually not required. As plugins allow you to create implementations that use two levels (C API and wire protocol), they have greater flexibility than MySQL Proxy. If a mysqlnd plugin is implemented using the C API, any subsequent changes to the wire protocol do not require changes to the plugin itself.
Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION, which is a string of the format mysqlnd 5.0.7-dev - 091210 - $Revision: 300535, or through MYSQLND_VERSION_ID, which is an integer such as 50007. Developers can calculate the version number as follows: Version (part) Major*10000 Minor*100 Patch MYSQLND_VERSION_ID Example 5*10000 = 50000 0*100 = 0 7=7 50007
During development, developers should refer to the mysqlnd version number for compatibility and version tests, as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.
247
C Object Oriented Paradigm At the code level, mysqlnd uses a C pattern for implementing object orientation. In C you use a struct to represent an object. Members of the struct represent object properties. Struct members pointing to functions represent methods. Unlike with other languages such as C++ or Java, there are no fixed rules on inheritance in the C object oriented paradigm. However, there are some conventions that need to be followed that will be discussed later. The PHP Life Cycle When considering the PHP life cycle there are two basic cycles: PHP engine startup and shutdown cycle Request cycle
When the PHP engine starts up it will call the module initialization (MINIT) function of each registered extension. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension. During the lifetime of the PHP engine it will receive a number of requests. Each request constitutes another life cycle. On each request the PHP engine will call the request initialization function of each extension. The extension can perform any variable setup and resource allocation required for request processing. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required. How a plugin works A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. This is achieved by obtaining the mysqlnd function table, backing it up, and replacing it by a custom function table, which calls the functions of the plugin as required. The following code shows how the mysqlnd function table is replaced:
/* a place to store orginal function table */ struct st_mysqlnd_conn_methods org_methods; void minit_register_hooks(TSRMLS_D) { /* active function table */ struct st_mysqlnd_conn_methods * current_methods = mysqlnd_conn_get_methods(); /* backup original function table */ memcpy(&org_methods, current_methods, sizeof(struct st_mysqlnd_conn_methods); /* install new methods */ current_methods->query = MYSQLND_METHOD(my_conn_class, query); }
Connection function table manipulations must be done during Module Initialization (MINIT). The function table is a global shared resource. In an multi-threaded environment, with a TSRM build, the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.
Note
Do not use any fixed-size logic when manipulating the mysqlnd function table: new methods may be added at the end of the function table. The function table may change at any time in the future. Calling parent methods If the original function table entries are backed up, it is still possible to call the original function table entries - the parent methods. In some cases, such as for Connection::stmt_init(), it is vital to call the parent method prior to any other activity in the derived method.
MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn, const char *query, unsigned int query_len TSRMLS_DC) {
248
php_printf("my_conn_class::query(query = %s)\n", query); query = "SELECT 'query rewritten' FROM DUAL"; query_len = strlen(query); return org_methods.query(conn, query, query_len); /* return with call to parent */ }
Extending properties A mysqlnd object is represented by a C struct. It is not possible to add a member to a C struct at run time. Users of mysqlnd objects cannot simply add properties to the objects. Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data. mysqlnd reserves space for one void * pointer per plugin. The following table shows how to calculate the position of the pointer for a specific plugin: Memory address 0 n n + (m x sizeof(void*)) Contents Beginning of the mysqlnd object C struct End of the mysqlnd object C struct void* to object data of the m-th plugin
If you plan to subclass any of the mysqlnd object constructors, which is allowed, you must keep this in mind! The following code shows extending properties:
/* any data we want to associate */ typedef struct my_conn_properties { unsigned long query_counter; } MY_CONN_PROPERTIES; /* plugin id */ unsigned int my_plugin_id; void minit_register_hooks(TSRMLS_D) { /* obtain unique plugin ID */ my_plugin_id = mysqlnd_plugin_register(); /* snip - see Extending Connection: methods */ } static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) { MY_CONN_PROPERTIES** props; props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data( conn, my_plugin_id); if (!props || !(*props)) { *props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent); (*props)->query_counter = 0; } return props; }
The plugin developer is responsible for the management of plugin data memory. Use of the mysqlnd memory allocator is recommended for plugin data. These functions are named using the convention: mnd_*loc(). The mysqlnd allocator has some useful features, such as the ability to use a debug allocator in a non-debug build. When and how to subclass When to subclass? Connection (MYSQLND) Resultset (MYSQLND_RES) MINIT MINIT or later Each instance has its own private function table? No Yes How to subclass? mysqlnd_conn_get_methods() mysqlnd_result_get_methods() or object method function table manipulation mysqlnd_result_metadata_get_ methods()
No
249
No Yes
mysqlnd_stmt_get_methods() mysqlnd_net_get_methods() or object method function table manipulation mysqlnd_protocol_get_methods( ) or object method function table manipulation
MINIT or later
Yes
You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table. Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. To avoid chaos, in particular in threaded environments, such function tables must only be manipulated during MINIT. Other classes use copies of a globally shared function table. The class function table copy is created together with the object. Each object uses its own function table. This gives you two options: you can manipulate the default function table of an object at MINIT, and you can additionally refine methods of an object without impacting other instances of the same class. The advantage of the shared function table approach is performance. There is no need to copy a function table for each and every object. Constructors Allocation, construction, reset Connection (MYSQLND) Resultset(MYSQLND_RES) Allocation: Connection::result_init() Reset and re-initialized during: Result::use_result() Result::store_result Yes, but call parent! Result::read_result_metadata() Connection::list_fields() Statement::get_result() Statement::prepare() (Metadata only) Statement::resultMetaData() mysqlnd_init() Can be modified? No Yes, but call parent! Caller mysqlnd_connect()
Resultset Meta Connection::result_meta_init() (MYSQLND_RES_METADAT A) Statement (MYSQLND_STMT) Connection::stmt_init() Network (MYSQLND_NET) Wire protocol (MYSQLND_PROTOCOL) mysqlnd_net_init() mysqlnd_protocol_init()
It is strongly recommended that you do not entirely replace a constructor. The constructors perform memory allocations. The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. If you do not care about warnings and insist on hooking the constructors, you should at least call the parent constructor before doing anything in your constructor. Regardless of all warnings, it can be useful to subclass constructors. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables, such as Resultset, Network, Wire Protocol. Destruction Derived method must call parent? Connection Resultset Resultset Meta yes, after method execution yes, after method execution yes, after method execution 250 Destructor free_contents(), end_psession() free_result() free()
yes, after method execution yes, after method execution yes, after method execution
The destructors are the appropriate place to free properties, mysqlnd_plugin_get_plugin_<object>_data(). The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. However, they are the best possible place for you to hook in and free your plugin data. As with constructors you may replace the methods entirely but this is not recommended. If multiple methods are listed in the above table you will need to hook all of the listed methods and free your plugin data in whichever method is called first by mysqlnd. The recommended method for plugins is to simply hook the methods, free your memory and call the parent implementation immediately following this.
Caution
Due to a bug in PHP versions 5.3.0 to 5.3.3, plugins do not associate plugin data with a persistent connection. This is because ext/mysql and ext/mysqli do not trigger all the necessary mysqlnd end_psession() method calls and the plugin may therefore leak memory. This has been fixed in PHP 5.3.4.
There is no formal definition of what a plugin is and how a plugin mechanism works. Components often found in plugins mechanisms are: A plugin manager A plugin API Application services (or modules) 251
The mysqlnd plugin concept employs these features, and additionally enjoys an open architecture. No Restrictions A plugin has full access to the inner workings of mysqlnd. There are no security limits or restrictions. Everything can be overwritten to implement friendly or hostile algorithms. It is recommended you only deploy plugins from a trusted source. As discussed previously, plugins can use pointers freely. These pointers are not restricted in any way, and can point into another plugin's data. Simple offset arithmetic can be used to read another plugin's data. It is recommended that you write cooperative plugins, and that you always call the parent method. The plugins should always cooperate with mysqlnd itself. Issues: an example of chaining and cooperation Extension ext/mysqlnd ext/mysqlnd_cache mysqlnd.query() pointer mysqlnd.query() mysqlnd_cache.query() 1. 2. ext/mysqlnd_monitor mysqlnd_monitor.query() 1. 2. 3. mysqlnd_monitor.query() mysqlnd_cache.query() mysqlnd.query mysqlnd_cache.query() mysqlnd.query call stack if calling parent mysqlnd.query
In this scenario, a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded. Both subclass Connection::query(). Plugin registration happens at MINIT using the logic shown previously. PHP calls extensions in alphabetical order by default. Plugins are not aware of each other and do not set extension dependencies. By default the plugins call the parent implementation of the query method in their derived version of the method. PHP Extension Recap This is a recap of what happens when using an example plugin, ext/mysqlnd_plugin, which exposes the mysqlnd C plugin API to PHP: Any PHP MySQL application tries to establish a connection to 192.168.2.29 The PHP application will either use ext/mysql, ext/mysqli or PDO_MYSQL. All three PHP MySQL extensions use mysqlnd to establish the connection to 192.168.2.29. Mysqlnd calls its connect method, which has been subclassed by ext/mysqlnd_plugin. ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user. The userspace hook changes the connection host IP from 192.168.2.29 to 127.0.0.1 and returns the connection established by parent::connect(). ext/mysqlnd_plugin performs the equivalent of parent::connect(127.0.0.1) by calling the original mysqlnd method for establishing a connection. ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. ext/mysqlnd_plugin returns as well.
252
Whatever PHP MySQL extension had been used by the application, it receives a connection to 127.0.0.1. The PHP MySQL extension itself returns to the PHP application. The circle is closed.
/* my_mysqlnd_plugin.c */ enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) { /* ... */ } enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) { /* ... */ }
Process: 1. 2. 3. 4. 5. PHP: user registers plugin callback PHP: user calls any PHP MySQL API to connect to MySQL C: ext/*mysql* calls mysqlnd method C: mysqlnd ends up in ext/mysqlnd_plugin C: ext/mysqlnd_plugin a. b. Calls userspace callback Or orginal mysqlnd method, if userspace callback not set
You need to carry out the following: 1. 2. 3. Write a class "mysqlnd_plugin_connection" in C Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()" Call userspace proxy methods from C (optimization - zend_interfaces.h) 253
Userspace object methods can either be called using call_user_function() or you can operate at a level closer to the Zend Engine and use zend_call_method(). Optimization: calling methods from C using zend_call_method The following code snippet shows the prototype for the zend_call_method function, taken from zend_interfaces.h.
ZEND_API zval* zend_call_method( zval **object_pp, zend_class_entry *obj_ce, zend_function **fn_proxy, char *function_name, int function_name_len, zval **retval_ptr_ptr, int param_count, zval* arg1, zval* arg2 TSRMLS_DC );
Zend API supports only two arguments. You may need more, for example:
enum_func_status (*func_mysqlnd_conn__connect)( MYSQLND *conn, const char *host, const char * user, const char * passwd, unsigned int passwd_len, const char * db, unsigned int db_len, unsigned int port, const char * socket, unsigned int mysql_flags TSRMLS_DC );
To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters. You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros. Calling PHP userspace This code snippet shows the optimized method for calling a userspace function from C:
/* my_mysqlnd_plugin.c */ MYSQLND_METHOD(my_conn_class,connect)( MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) { enum_func_status ret = FAIL; zval * global_user_conn_proxy = fetch_userspace_proxy(); if (global_user_conn_proxy) { /* call userspace proxy */ ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/); } else { /* or original mysqlnd method = do nothing, be transparent */ ret = org_methods.connect(conn, host, user, passwd, passwd_len, db, db_len, port, socket, mysql_flags TSRMLS_CC); } return ret; }
254
MYSQLND_METHOD(my_conn_class, connect)( MYSQLND *conn, /* ...*/) { /* ... */ if (global_user_conn_proxy) { /* ... */ zval* zv_conn; ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn); MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/); zval_ptr_dtor(&zv_conn); /* ... */ } /* ... */ }
The first argument of many mysqlnd methods is a C "object". For example, the first argument of the connect() method is a pointer to MYSQLND. The struct MYSQLND represents a mysqlnd connection object. The mysqlnd connection object pointer can be compared to a standard I/O file handle. Like a standard I/O file handle a mysqlnd connection object shall be linked to the userspace using the PHP resource variable type. From C to userspace and back
class proxy extends mysqlnd_plugin_connection { public function connect($conn, $host, ...) { /* "pre" hook */ printf("Connecting to host = '%s'\n", $host); debug_print_backtrace(); return parent::connect($conn); } public function query($conn, $query) { /* "post" hook */ $ret = parent::query($conn, $query); printf("Query = '%s'\n", $query); return $ret; } } mysqlnd_plugin_set_conn_proxy(new proxy());
PHP users must be able to call the parent implementation of an overwritten method. As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks. Buildin class: mysqlnd_plugin_connection::connect()
/* my_mysqlnd_plugin_classes.c */ PHP_METHOD("mysqlnd_plugin_connection", connect) { /* ... simplified! ... */ zval* mysqlnd_rsrc; MYSQLND* conn; char* host; int host_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mysqlnd_rsrc, &host, &host_len) == FAILURE) { RETURN_NULL(); } ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1, "Mysqlnd Connection", le_mysqlnd_plugin_conn); if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC)) RETVAL_TRUE; else RETVAL_FALSE; }
255
Warning
Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions. The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driverspecific attributes with another driver may result in unexpected behaviour. PDO::getAttribute may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers. PDO::MYSQL_ATTR_USE_BUFF If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered ERED_QUERY (integer) versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll instead.
PDO::MYSQL_ATTR_LOCAL_IN Enable LOAD LOCAL INFILE. FILE (integer) Note, this constant can only be used in the driver_options array when constructing a new database handle. PDO::MYSQL_ATTR_INIT_COM Command to execute when connecting to the MySQL server. Will automatically be re-executed MAND (integer) when reconnecting. Note, this constant can only be used in the driver_options array when constructing a new database handle. PDO::MYSQL_ATTR_READ_DEF Read options from the named option file instead of from my.cnf. This option is not available if AULT_FILE (integer) mysqlnd is used, because mysqlnd does not read the mysql configuration files. PDO::MYSQL_ATTR_READ_DEF Read options from the named group from my.cnf or the file specified with AULT_GROUP (integer) MYSQL_READ_DEFAULT_FILE . This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files. PDO::MYSQL_ATTR_MAX_BUFF Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against ER_SIZE (integer) mysqlnd. PDO::MYSQL_ATTR_DIRECT_Q Perform direct queries, don't use prepared statements. UERY (integer)
256
WS (integer)
Return the number of found (matched) rows, not the number of changed rows.
PDO::MYSQL_ATTR_IGNORE_S Permit spaces after function names. Makes all functions names reserved words. PACE (integer) PDO::MYSQL_ATTR_COMPRESS Enable network communication compression. This is not supported when compiled against (integer) mysqlnd. The behaviour of these functions is affected by settings in php.ini.
For further details and definitions of the PHP_INI_* modes, see the configuration.changes.modes. Here's a short explanation of the configuration directives.
pdo_mysql.default_socket Sets a Unix domain socket. This value can either be set at compile time if a domain socket is string found at configure. This ini setting is Unix only. pdo_mysql.debug boolean Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.
257
The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:
mysql:host=localhost;dbname=testdb
Notes
Unix only:
When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysql then the location of the socket file is at libmysql's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.
258
Chapter 5. Connector/PHP
The MySQL Connector/PHP is a version of the mysql and mysqli extensions for PHP optimized for the Windows operating system. Later versions of the main PHP mysql/mysqli drivers are compatible with Windows and a separate, Windows specific driver is no longer required. For PHP for all platforms, including Windows, you should use the mysql or mysqli extensions shipped with the PHP sources. See Preface.
259
Those with PHP4 legacy code can make use of a compatibility layer for the old and new MySQL libraries, such as this one: http://www.coggeshall.org/oss/mysql2i.
260
2.
Edit the Makefile and search for a line that starts with EXTRA_LIBS. It might look like this (all on one line):
EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lresolv -lm -ldl -lnsl -lxml2 -lz -lm -lxml2 -lz -lm -lmysqlclient -lz -lcrypt -lnsl -lm -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt
Remove all duplicates, so that the line looks like this (all on one line):
EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lresolv -lm -ldl -lnsl -lxml2
3.
261