MySQL and PHP

MySQL and PHP Reference
Abstract This manual describes the PHP extensions and interfaces that can be used with MySQL. Document generated on: 2012-02-18 (revision: 29125)
Copyright © 1997, 2012, Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065. This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. MySQL is a trademark of Oracle Corporation and/or its affiliates, and shall not be used without Oracle's express written authorization. Other names may be trademarks of their respective owners. This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services. This document in any form, software or printed matter, contains proprietary information that is the exclusive property of Oracle. Your access to and use of this material is subject to the terms and conditions of your Oracle Software License and Service Agreement, which has been executed and with which you agree to comply. This document and information contained herein may not be disclosed, copied, reproduced, or distributed to anyone outside Oracle without prior written consent of Oracle or as specifically provided below. This document is not part of your license agreement nor can it be incorporated into any contractual agreement with Oracle or its subsidiaries or affiliates. This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the following terms: You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual content is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the documentation in a manner similar to how Oracle disseminates it (that is, electronically for download on a Web site with the software) or on a CD-ROM or similar medium, provided however that the documentation is disseminated together with the software on the same medium. Any other use, such as any dissemination of printed copies or use of this documentation, in whole or in part, in another publication, requires the prior written consent from an authorized representative of Oracle. Oracle and/or its affiliates reserve any and all rights to this documentation not expressly granted above. For more information on the terms of this license, or for details on how the MySQL documentation is built and produced, please visit MySQL Contact & Questions. For additional licensing information, including licenses for third-party libraries used by MySQL products, see Preface and Legal Notice. For help with using MySQL, please visit either the MySQL Forums or MySQL Mailing Lists where you can discuss your issues with other MySQL users. For additional documentation on MySQL products, including translations of the documentation into other languages, and downloadable versions in variety of formats, including HTML and PDF formats, see the MySQL Documentation Library.

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 provides three different MySQL API extensions: • Chapter 1, MySQL Extension (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. To use this extension with MySQL 4.1, you will likely configure the MySQL server to use the --old-passwords option (see Client does not support authentication protocol). 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. Chapter 4, MySQL Functions (PDO_MYSQL) (MySQL (PDO)) Not its own API, but instead it's a MySQL driver for the PHP database abstraction layer PDO (PHP Data Objects). The PDO MySQL driver sits in the layer below PDO itself, and provides MySQLspecific functionality. This extension is available as of PHP 5.1.

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

Chapter 1. MySQL Extension (mysql)
Copyright 1997-2012 the PHP Documentation Group. These functions allow you to access MySQL database servers. More information about MySQL can be found at http://www.mysql.com/. Documentation for MySQL can be found at http://dev.mysql.com/doc/. For an overview of MySQL database connectivity terms and products see Section 2.2, “Overview”.

1.1. Installing/Configuring
Copyright 1997-2012 the PHP Documentation Group.

1.1.1. Requirements
Copyright 1997-2012 the PHP Documentation Group. In order to have these functions available, you must compile PHP with MySQL support.

1.1.2. Installation
Copyright 1997-2012 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. Installation on Linux Systems
Copyright 1997-2012 the PHP Documentation Group. Note: [DIR] is the path to the MySQL client library files (headers and libraries), which can be downloaded from MySQL.

Table 1.1. ext/mysql compile time support matrix
PHP Version 4.x.x Default libmysql Configure Options: mysqlnd Not Available Configure Options: libmysql Changelog

--without-mysql to MySQL enabled by dedisable fault, MySQL client libraries are bundled MySQL is no longer en-with-mysql=[DIR] abled by default, and the MySQL client libraries are no longer bundled mysqlnd is now available -with-mysql=[DIR]

5.0.x, 5.1.x, 5.2.x

libmysql

Not Available

5.3.x

libmysql

withmysql=mysqlnd --with-mysql

5.4.x

mysqlnd

mysqlnd is now the de-with-mysql=[DIR] fault

1

1.2.2.allow_local_infile mysql. you have to install external (not bundled) libmysql with compiled charset support.2./php_mysql.3.1.MySQL Extension (mysql) 1. A file named libmysql. PHP 5. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this.0+ Copyright 1997-2012 the PHP Documentation Group.3.x Copyright 1997-2012 the PHP Documentation Group. Also. The MySQL Native Driver is enabled by default.dll).1.1.x. so the php_mysql. Include php_mysql. An example extension_dir value for PHP 5 is c:\php\ext Note If when starting the web server an error similar to the following occurs: "Unable to load dynamic library '. 1.x. 1.2. Warning Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension.1.0. MySQL Configuration Options Name mysql.dll cannot be found by the system. The behaviour of these functions is affected by settings in php. 1. See the recode extension for more information.dll to the Windows system directory also works (because the system directory is by default in the system's PATH). PHP needs access to the MySQL client library.1. PHP 5.2. As with enabling any PHP extension (such as php_mysql. 5.dll and/or libmysql.2. Although copying libmysql.ini.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.dll DLL must be enabled inside of php.2. but libmysql.dll'". See also the Manual Windows Installation Instructions.1. it's not recommended.max_persistent Default "1" "1" "-1" 2 Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM Changelog .3.dll. the PHP directive extension_dir should be set to the directory where the PHP extensions are located. Installation on Windows Systems Copyright 1997-2012 the PHP Documentation Group. Note If you need charsets other than latin (default). 1. 5. PHP 4 Copyright 1997-2012 the PHP Documentation Group. Runtime Configuration Copyright 1997-2012 the PHP Documentation Group. The PHP MySQL extension is compiled into PHP.3.dll is no longer required or used.2.2. MySQL is no longer enabled by default.2. Table 1.2.2.1.allow_persistent mysql. MySQL Installation Notes Copyright 1997-2012 the PHP Documentation Group.ini.1. this is because php_mysql.

the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant. The constants below are defined by this extension. Doesn't apply in SQL safe mode. The maximum number of persistent MySQL connections per process.max_persistent integer mysql. The default password to use when connecting to the database server if no other password is specified.max_links mysql.trace_mode boolean mysql.allow_local_infile integer mysql. (Introduced in PHP 4. from PHP's perspective.modes.connect_timeout Default "-1" "0" NULL NULL NULL NULL NULL "60" Changeable 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 Available since PHP 4.default_user string mysql. Here's a short explanation of the configuration directives.2.default_socket mysql.0) The default TCP port number to use when connecting to the database server if no other port is specified. non free result sets.4.3.trace_mode is enabled.max_links integer mysql. Resource Types Copyright 1997-2012 the PHP Documentation Group. warnings for table/index scans. the second a resource which holds the result of a query.1. Doesn't apply in SQL safe mode.0. The first one is the link identifier for a database connection. and will only be available when the extension has either been compiled into PHP or 3 .default_port mysql. see the http://www.default_password string mysql.2. the port will be obtained from the MYSQL_TCP_PORT environment variable.default_socket string mysql.default_host string mysql. When mysql.php. Available since PHP 4.3.allow_persistent boolean mysql.3. Connect timeout in seconds. Trace mode. local files with LOAD DATA statements Whether to allow persistent connections to MySQL.0.0.connect_timeout integer 1. If no default is specified. and SQL-Errors will be displayed. Win32 will only use the MYSQL_PORT constant. On Linux this timeout is also used for waiting for the first answer from the server. For further details and definitions of the PHP_INI_* modes. The default server host to use when connecting to the database server if no other host is specified. The default user name to use when connecting to the database server if no other name is specified. including persistent connections. The default socket name to use when connecting to a local database server if no other socket name is specified. There are two resource types used in the MySQL module.default_host mysql.default_password mysql. in that order.net/manual/en/configuration.trace_mode mysql.default_user mysql.default_port string Allow accessing.1. mysql. mysql. Predefined Constants Copyright 1997-2012 the PHP Documentation Group.MySQL Extension (mysql) Name mysql.3. The maximum number of MySQL connections per process.changes. Available since PHP 4. 1. PHP_INI_SYSTEM in PHP <= 4. Doesn't apply in SQL safe mode.

foreach ($line as $col_value) { echo "\t\t<td>$col_value</td>\n".3. mysql_select_db('my_database') or die('Could not select database'). 1. print resulting rows and disconnect from a MySQL database.1. mysql_error()). // Performing SQL query $query = 'SELECT * FROM my_table'. 1. The following constants are defined: Table 1. MySQL extension overview example Copyright 1997-2012 the PHP Documentation Group. Example 1.3. MySQL fetch constants Constant MYSQL_ASSOC MYSQL_BOTH MYSQL_NUM Description Columns are returned into the array having the fieldname as the array index. MySQL extension overview example <?php // Connecting. } echo "\t</tr>\n". mysql_error()). Version 3. 'mysql_password') or die('Could not connect: ' .1.3. } echo "</table>\n". This flag is only available with version 4. This simple example shows how to connect. // Printing results in HTML echo "<table>\n". while ($line = mysql_fetch_array($result. Columns are returned into the array having both a numerical index and the fieldname as the array index.0 it is possible to specify additional client flags for the mysql_connect and mysql_pconnect functions.3.MySQL Extension (mysql) dynamically loaded at runtime.x of the MySQL client library or newer. Examples Copyright 1997-2012 the PHP Documentation Group.4. Use SSL encryption. MYSQL_ASSOC)) { echo "\t<tr>\n". the first field in the result. This index starts with 0. // Free resultset mysql_free_result($result). $result = mysql_query($query) or die('Query failed: ' . The following constants are defined: Table 1.x is bundled both with PHP 4 and Windows binaries of PHP 5. Since PHP 4. execute a query. echo 'Connected successfully'. 'mysql_user'. 4 . The function mysql_fetch_array uses a constant for the different types of result arrays. MySQL client constants Constant MYSQL_CLIENT_COMPRESS MYSQL_CLIENT_IGNORE_SPACE MYSQL_CLIENT_INTERACTIVE MYSQL_CLIENT_SSL Description Use compression protocol Allow space after function names Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection. Columns are returned into the array having a numerical index to the fields. selecting database $link = mysql_connect('mysql_host'.23.

and -1 if the last query failed. it will try to create one as if mysql_connect was called with no arguments. last opened connection is used. functions return FALSE . This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched.1. If it is not provided. MySQL Functions Copyright 1997-2012 the PHP Documentation Group. all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4. When using UPDATE. If the link identifier is not specified. only the number of rows that were literally affected by the query. If it doesn't exist. This function returns the number of deleted records plus the number of inserted records. MySQL will not update columns where the new value is the same as the old value. ?> 1.MySQL Extension (mysql) // Closing connection mysql_close($link). Note Most MySQL functions accept link_identifier as the last optional parameter. If no such link is found. 'mysql_user'. Examples Example 1. mysql_affected_rows example <?php $link = mysql_connect('localhost'. an E_WARNING level error is generated. mysql_affected_rows Copyright 1997-2012 the PHP Documentation Group. 'mysql_password'). 5 . 1. the last link opened by mysql_connect is assumed.4. UPDATE. If it is not successful.4. If the last query was a DELETE query with no WHERE clause. Parameters link_identifier The MySQL connection.ini. The REPLACE statement first deletes the record with the same primary key and then inserts the new record. Get the number of affected rows by the last INSERT. Return Values Returns the number of affected rows on success.1. If no connection is found or established. • mysql_affected_rows Get number of affected rows in previous MySQL operation Description int mysql_affected_rows(resource link_identifier). REPLACE or DELETE query associated with link_identifier.2. connection is tried to establish with default parameters defined in php.2.

/* with a where clause that is never true. printf ("Updated records: %d\n". mysql_error()). if (!$link) { die('Could not connect: ' . /* Update records */ mysql_query("UPDATE mytable SET used=1 WHERE id < 10"). or DELETE query. /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'). mysql_error()). you need to call mysql_affected_rows after your INSERT. mysql_affected_rows()). 'mysql_user'. mysql_query("COMMIT"). mysql_affected_rows example using transactions <?php $link = mysql_connect('localhost'. } mysql_select_db('mydb'). ?> The above example will output something similar to: Updated Records: 10 Notes Transactions If you are using transactions. mysql_affected_rows()). printf("Records deleted: %d\n". mysql_affected_rows()). UPDATE. printf("Records deleted: %d\n". Cascaded Foreign Keys mysql_affected_rows does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints. See Also mysql_num_rows mysql_info 6 . it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'). 'mysql_password').3. ?> The above example will output something similar to: Records deleted: 10 Records deleted: 0 Example 1. it is possible to use mysql_num_rows. not after the COMMIT. } mysql_select_db('mydb'). SELECT Statements To retrieve the number of rows returned by a SELECT.MySQL Extension (mysql) if (!$link) { die('Could not connect: ' .

3. it will try to create one as if mysql_connect was called with no arguments. the last link opened by mysql_connect is assumed. ?> The above example will output something similar to: The current character set is: latin1 See Also mysql_set_charset mysql_real_escape_string 1.4. 'mysql_password'). Retrieves the character_set variable from MySQL. • mysql_close Close MySQL connection 7 . Parameters link_identifier The MySQL connection.4. mysql_client_encoding example <?php $link = mysql_connect('localhost'. $charset = mysql_client_encoding($link). Return Values Returns the default character set name for the current connection. If no connection is found or established. an E_WARNING level error is generated. echo "The current character set is: $charset\n". 'mysql_user'. mysql_close Copyright 1997-2012 the PHP Documentation Group.MySQL Extension (mysql) 1.4.2. mysql_client_encoding Copyright 1997-2012 the PHP Documentation Group. If no such link is found. Examples Example 1. • mysql_client_encoding Returns the name of the character set Description string mysql_client_encoding(resource link_identifier). If the link identifier is not specified.

an E_WARNING level error is generated. the last link opened by mysql_connect is assumed.MySQL Extension (mysql) Description bool mysql_close(resource link_identifier). if (!$link) { die('Could not connect: ' . as non-persistent open links are automatically closed at the end of the script's execution. mysql_close example <?php $link = mysql_connect('localhost'. mysql_close closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. • mysql_connect 8 . mysql_error()). Using mysql_close isn't usually necessary. the last opened link is used.4. See also freeing resources. 'mysql_password').4. 'mysql_user'. Parameters link_identifier The MySQL connection. If no connection is found or established. If link_identifier isn't specified. ?> The above example will output: Connected successfully Notes Note mysql_close will not close persistent links created by mysql_pconnect. If the link identifier is not specified. } echo 'Connected successfully'. Return Values Returns TRUE on success or FALSE on failure. Examples Example 1. mysql_close($link).5. See Also mysql_connect mysql_free_result 1. mysql_connect Copyright 1997-2012 the PHP Documentation Group.

Parameters server The MySQL server. “MySQL client constants” for further information. but instead.3. e. In SQL safe mode.default_host is undefined (default).6. no new link will be established. then the default value is 'localhost:3306'. username password new_link The username. In SQL safe mode. Opens or reuses a connection to a MySQL server. this parameter is ignored and value 'localhost:3306' is always used.g. Added the new_link parameter. Default value is defined by mysql. int client_flags= =0). this parameter is ignored and the name of the user that owns the server process is used.0 Examples Description Added the client_flags parameter. ":/path/to/socket" for the localhost.default_password"). client_flags Return Values Returns a MySQL link identifier on success or FALSE on failure. this parameter is ignored and empty password is used. even if mysql_connect was called before with the same parameters. 'mysql_password'). In SQL safe mode.3. string password= =ini_get("mysql. string username= =ini_get("mysql. Read the section about Table 1.default_password. mysql_error()). bool new_link= =false. The new_link parameter modifies this behavior and makes mysql_connect always open a new link. In SQL safe mode. Default value is defined by mysql. } 9 . MYSQL_CLIENT_SSL .default_host"). The password. mysql_connect example <?php $link = mysql_connect('localhost'. It can also include a port number. the link identifier of the already opened link will be returned.g. MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . "hostname:port" or a path to a local socket e. Changelog Version 4.0 4.MySQL Extension (mysql) Open a connection to a MySQL Server Description resource mysql_connect(string server= =ini_get("mysql.default_user").default_user. If a second call is made to mysql_connect with the same arguments. 'mysql_user'. this parameter is ignored. this parameter is ignored. The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling). In SQL safe mode. if (!$link) { die('Could not connect: ' . MYSQL_CLIENT_COMPRESS . If the PHP directive mysql. Example 1.2.

0. } echo 'Connected successfully'. 'mysql_password'). 'mysql_password'). 'mysql_password'). if (!$link) { die('Could not connect: ' . the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). mysql_close($link). 'mysql_user'. unless it's closed earlier by explicitly calling mysql_close.com and port 3307 $link = mysql_connect('example. // we connect to localhost at port 3307 $link = mysql_connect('127. } echo 'Connected successfully'. If the MySQL client library tries to connect to the wrong local socket. 'mysql_user'. ?> Notes Note Whenever you specify "localhost" or "localhost:port" as server. use "127.8.0.7.1:3307'. ?> Example 1.1" instead of "localhost".MySQL Extension (mysql) echo 'Connected successfully'.0. mysql_close($link). if (!$link) { die('Could not connect: ' .sock'.g. if (!$link) { die('Could not connect: ' . 10 . mysql_error()). } echo 'Connected successfully'. mysql_connect example using ":/path/to/socket" syntax <?php // we connect to localhost and socket e. If you want to use TCP/IP. mysql_close($link). mysql_connect example using hostname:port syntax <?php // we connect to example. mysql_close($link). 'mysql_user'. 'mysql_password').default_host string in your PHP configuration and leave the server field blank. mysql_close($link). Note You can suppress the error message on failure by prepending a @ to the function name. mysql_error()). Note The link to the server will be closed as soon as the execution of the script ends. mysql_error()). 'mysql_user'.0. // variant 2: with localhost $link = mysql_connect('localhost:/tmp/mysql.com:3307'. /tmp/mysql.sock // variant 1: omit localhost $link = mysql_connect(':/tmp/mysql'. you should set the correct path as mysql. mysql_error()). } echo 'Connected successfully'. ?> Example 1. if (!$link) { die('Could not connect: ' .

9. On Windows.5. it will try to create one as if mysql_connect was called with no arguments.MySQL Extension (mysql) Note Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. "\n". Parameters database_name link_identifier The name of the database being created. mysql_create_db Copyright 1997-2012 the PHP Documentation Group. if (mysql_query($sql. Return Values Returns TRUE on success or FALSE on failure. mysql_error()). if (!$link) { die('Could not connect: ' . an E_WARNING level error is generated. } ?> 11 . 'mysql_password'). The MySQL connection. It is preferable to use mysql_query to issue an sql CREATE DATABASE statement instead. <?php $link = mysql_connect('localhost'. If no connection is found or established. • mysql_create_db Create a MySQL database Description bool mysql_create_db(string database_name. mysql_create_db alternative example The function mysql_create_db is deprecated. See Also mysql_pconnect mysql_close 1. If no such link is found. if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. mysql_create_db attempts to create a new database on the server associated with the specified link identifier. the last link opened by mysql_connect is assumed. resource link_identifier). Examples Example 1.4. } else { echo 'Error creating database: ' . $link)) { echo "Database my_db created successfully\n". 'mysql_user'. mysql_error() . } $sql = 'CREATE DATABASE my_db'. If the link identifier is not specified.

See Also mysql_query mysql_select_db 1. such as mysql_fetch_assoc. The desired row number of the new result pointer. 'mysql_password'). mysql_data_seek Copyright 1997-2012 the PHP Documentation Group.1.x client library. • mysql_data_seek Move internal result pointer Description bool mysql_data_seek(resource result. This result comes from a call to mysql_query.10.6. Returns TRUE on success or FALSE on failure. would return that row. 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. 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 . mysql_data_seek example <?php $link = mysql_connect('localhost'.MySQL Extension (mysql) The above example will output something similar to: Database my_db created successfully Notes Note For backward compatibility. row_number starts at 0. Parameters result row_number Return Values The result resource that is being evaluated. 12 . 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.4. The row_number should be a value in the range from 0 to mysql_num_rows . The next call to a MySQL fetch function. Examples Example 1. 'mysql_user'.

$i--) { if (!mysql_data_seek($result. See Also mysql_query mysql_num_rows mysql_fetch_row mysql_fetch_assoc mysql_fetch_array mysql_fetch_object 1. mysql_error() . 13 . Retrieve the database name from a call to mysql_list_dbs. ' ' . if (!$result) { die('Query failed: ' . } if (!($row = mysql_fetch_assoc($result))) { continue. The index into the result set. } /* fetch rows in reverse order */ for ($i = mysql_num_rows($result) . Parameters result row The result pointer from a call to mysql_list_dbs. $i >= 0. $row['first_name'] . first_name FROM friends'. mysql_db_name Copyright 1997-2012 the PHP Documentation Group. "\n". ?> Notes Note The function mysql_data_seek can be used in conjunction only with mysql_query. } echo $row['last_name'] . $i)) { echo "Cannot seek to row $i: " . continue. • mysql_db_name Retrieves database name from the call to mysql_list_dbs Description string mysql_db_name(resource result. $result = mysql_query($query). not with mysql_unbuffered_query.MySQL Extension (mysql) if (!$link) { die('Could not connect: ' .1. mysql_error()). } $query = 'SELECT last_name. mysql_error()). mixed field). int row. if (!$db_selected) { die('Could not select database: ' .7. } $db_selected = mysql_select_db('sample_db'). mysql_error()). } mysql_free_result($result). "<br />\n".4.

4. $i) . Examples Example 1. while ($i < $cnt) { echo mysql_db_name($db_list. use mysql_error to determine the nature of the error. $link = mysql_connect('dbhost'. $cnt = mysql_num_rows($db_list). Parameters database The name of the database that will be selected.8. 'username'. and executes a query on it. Returns the database name on success. string query. and FALSE on failure. • mysql_db_query Selects a database and executes a query on it Description resource mysql_db_query(string database. $db_list = mysql_list_dbs($link). If FALSE is returned.3. } ?> Notes Note For backward compatibility. mysql_db_query selects a database. resource link_identifier). "\n". Warning This function has been DEPRECATED as of PHP 5.MySQL Extension (mysql) field Return Values The field name. $i++.0. Relying on this feature is highly discouraged. 'password'). the following deprecated alias may be used: mysql_dbname See Also mysql_list_dbs mysql_tablename 1. mysql_db_query Copyright 1997-2012 the PHP Documentation Group. mysql_db_name example <?php error_reporting(E_ALL). 14 . $i = 0.11.

table syntax in their sql queries or mysql_select_db instead of this function. } while ($row = mysql_fetch_assoc($result)) { echo $row['foo']. echo 'MySQL Error: ' . mysql_db_query alternative example <?php if (!$link = mysql_connect('mysql_host'. the last link opened by mysql_connect is assumed. mysql_error(). If no such link is found. $result = mysql_query($sql. If no connection is found or established.0 4. link_identifier The MySQL connection. In other words. The function also returns TRUE / FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure. 'mysql_user'. This function is deprecated. Examples Example 1. could not query the database\n". Return Values Returns a positive MySQL result resource to the query result. an E_WARNING level error is generated. exit. exit. Changelog Version 5. } $sql = 'SELECT foo FROM bar WHERE id = 42'.3. ?> Notes Note Be aware that this function does NOT switch back to the database you were connected before. you would have to manually switch back. $link)) { echo 'Could not select database'. If the link identifier is not specified. do not use this function. Data inside the query should be properly escaped.6 Description This function now throws an E_DEPRECATED notice.0. if (!$result) { echo "DB Error. 'mysql_password')) { echo 'Could not connect to mysql'. you can't use this function to temporarily run a sql query on another database. See Also mysql_query mysql_select_db 15 . } mysql_free_result($result). or FALSE on error.MySQL Extension (mysql) query The MySQL query.12. exit. Users are strongly encouraged to use the database. Use mysql_select_db and mysql_query instead. $link). } if (!mysql_select_db('mysql_dbname'. it will try to create one as if mysql_connect was called with no arguments.

Examples Example 1.13. mysql_drop_db Copyright 1997-2012 the PHP Documentation Group. mysql_drop_db alternative example <?php $link = mysql_connect('localhost'. resource link_identifier). the last link opened by mysql_connect is assumed. the following deprecated alias may be used: mysql_dropdb See Also 16 . • mysql_drop_db Drop (delete) a MySQL database Description bool mysql_drop_db(string database_name. 'mysql_password'). This function is deprecated.9. mysql_error()). it is preferable to use mysql_query to issue an sql DROP DATABASE statement instead.MySQL Extension (mysql) 1.4. If no connection is found or established. it will try to create one as if mysql_connect was called with no arguments. an E_WARNING level error is generated. 'mysql_user'. $link)) { echo "Database my_db was successfully dropped\n". } $sql = 'DROP DATABASE my_db'. If the link identifier is not specified. Note For backward compatibility. } ?> Notes Warning This function will not be available if the MySQL extension was built against a MySQL 4. If no such link is found. } else { echo 'Error dropping database: ' . mysql_drop_db attempts to drop (remove) an entire database from the server associated with the specified link identifier. Parameters database_name link_identifier The name of the database that will be deleted. "\n". The MySQL connection. if (mysql_query($sql. Return Values Returns TRUE on success or FALSE on failure. if (!$link) { die('Could not connect: ' .x client library. mysql_error() .

Examples Example 1. Return Values Returns the error number from the last MySQL function. mysql_error($link). } mysql_select_db("kossu". use mysql_errno to retrieve the error code. } ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu. so if you want to use it.MySQL Extension (mysql) mysql_query 1. If the link identifier is not specified. make sure you check the value before calling another MySQL function.14.nonexistenttable' doesn't exist See Also 17 .4. Returns the error number from the last MySQL function. "\n". Errors coming back from the MySQL database backend no longer issue warnings. if (!mysql_select_db("nonexistentdb". "mysql_password"). "mysql_user". Instead. $link). If no connection is found or established. the last link opened by mysql_connect is assumed. mysql_errno Copyright 1997-2012 the PHP Documentation Group. "\n". $link)) { echo mysql_errno($link) . it will try to create one as if mysql_connect was called with no arguments. mysql_errno example <?php $link = mysql_connect("localhost". $link)) { echo mysql_errno($link) . ": " .10. ": " . if (!mysql_query("SELECT * FROM nonexistenttable". • mysql_errno Returns the numerical value of the error message from previous MySQL operation Description int mysql_errno(resource link_identifier). an E_WARNING level error is generated. If no such link is found. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error and mysql_errno). mysql_error($link) . or 0 (zero) if no error occurred. Parameters link_identifier The MySQL connection.

make sure you check the value before calling another MySQL function. "mysql_user". Return Values Returns the error text from the last MySQL function. "\n". mysql_query("SELECT * FROM nonexistenttable".MySQL Extension (mysql) mysql_error MySQL error codes 1. it will try to create one as if mysql_connect was called with no arguments. echo mysql_errno($link) . Errors coming back from the MySQL database backend no longer issue warnings. If no connection is found or established. mysql_error Copyright 1997-2012 the PHP Documentation Group. ": " . • mysql_error Returns the text of the error message from previous MySQL operation Description string mysql_error(resource link_identifier). $link). If no such link is found. an E_WARNING level error is generated. use mysql_error to retrieve the error text. $link).11. If the link identifier is not specified. Parameters link_identifier The MySQL connection. ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error and mysql_errno). mysql_error example <?php $link = mysql_connect("localhost". "\n". so if you want to use it. or '' (empty string) if no error occurred. mysql_error($link). Examples Example 1.15. ": " . $link). "mysql_password").nonexistenttable' doesn't exist See Also mysql_errno MySQL error codes 18 . mysql_select_db("kossu". Returns the error text from the last MySQL function.4. the last link opened by mysql_connect is assumed. Instead. echo mysql_errno($link) . mysql_select_db("nonexistentdb". mysql_error($link) .

mysql_escape_string does not take a connection argument and does not respect the current charset setting. This function is deprecated.4.3.12. so that it is safe to place it in a mysql_query. printf("Escaped string: %s\n". Parameters unescaped_string Return Values Returns the escaped string. $escaped_item).0 The string that is to be escaped. do not use this function. Warning This function has been DEPRECATED as of PHP 5.0 4.0. 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.3. Instead. This function will escape the unescaped_string. ?> The above example will output: Escaped string: Zak\'s Laptop 19 . use mysql_real_escape_string.MySQL Extension (mysql) 1. Relying on this feature is highly discouraged. mysql_escape_string Copyright 1997-2012 the PHP Documentation Group.16. $escaped_item = mysql_escape_string($item). Changelog Version 5. Examples Example 1. • mysql_escape_string Escapes a string for use in a mysql_query Description string mysql_escape_string(string unescaped_string). This function became deprecated. Description This function now throws an E_DEPRECATED notice.3. mysql_escape_string example <?php $item = "Zak's Laptop".

17. If two or more columns of the result have the same field names. This result comes from a call to mysql_query. you only get associative indices (as mysql_fetch_assoc works). and MYSQL_BOTH . Return Values Returns an array of strings that corresponds to the fetched row. Using MYSQL_ASSOC .13. you only get number indices (as mysql_fetch_row works). using MYSQL_NUM .field AS foo. Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. you cannot access the contents with the original column name. By using MYSQL_BOTH (default). or both Description array mysql_fetch_array(resource result.18. The type of returned array depends on how result_type is defined. MYSQL_NUM . or FALSE if there are no more rows.MySQL Extension (mysql) Notes Note mysql_escape_string does not escape % and _. table2 Example 1. See Also mysql_real_escape_string addslashes The magic_quotes_gpc directive. the last column will take precedence. Examples Example 1. table2. you'll get an array with both associative and number indices.field AS bar FROM table1. int result_type= =MYSQL_BOTH). Query with aliased duplicate field names SELECT table1. For aliased columns.4. you must use the numeric index of the column or make an alias for the column. mysql_fetch_array Copyright 1997-2012 the PHP Documentation Group. To access the other column(s) of the same name. Parameters result result_type The result resource that is being evaluated. mysql_fetch_array with MYSQL_NUM 20 . The type of array that is to be fetched. a numeric array. 1. It's a constant and can take the following values: MYSQL_ASSOC . • mysql_fetch_array Fetch a result row as an associative array.

MYSQL_ASSOC)) { printf("ID: %s Name: %s". MYSQL_NUM)) { printf("ID: %s Name: %s". "mysql_user". mysql_error()). } mysql_free_result($result). MYSQL_BOTH)) { printf ("ID: %s Name: %s". "mysql_password") or die("Could not connect: " . See Also mysql_fetch_row mysql_fetch_assoc 21 . $row[0]. while ($row = mysql_fetch_array($result. $result = mysql_query("SELECT id. name FROM mytable"). $row["name"]). Note This function sets NULL fields to the PHP NULL value. $row["name"]). ?> Example 1. mysql_error()). mysql_error()).19. while ($row = mysql_fetch_array($result. $row[0]. while ($row = mysql_fetch_array($result. mysql_fetch_array with MYSQL_ASSOC <?php mysql_connect("localhost". name FROM mytable"). "mysql_user". ?> Notes Performance An important thing to note is that using mysql_fetch_array is not significantly slower than using mysql_fetch_row. mysql_select_db("mydb").20. "mysql_password") or die("Could not connect: " . } mysql_free_result($result). } mysql_free_result($result).MySQL Extension (mysql) <?php mysql_connect("localhost". name FROM mytable"). mysql_select_db("mydb"). Note Field names returned by this function are case-sensitive. $result = mysql_query("SELECT id. while it provides a significant added value. mysql_fetch_array with MYSQL_BOTH <?php mysql_connect("localhost". "mysql_user". mysql_select_db("mydb"). $result = mysql_query("SELECT id. $row[1]). "mysql_password") or die("Could not connect: " . $row["id"]. ?> Example 1.

21. no need to use a loop // Note: If you put extract($row). It only returns an associative array. This result comes from a call to mysql_query. or FALSE if there are no more rows. userstatus FROM sometable WHERE userstatus = 1". Examples Example 1. mysql_fetch_assoc is equivalent to calling mysql_fetch_array with MYSQL_ASSOC for the optional second parameter. exit.MySQL Extension (mysql) mysql_data_seek mysql_query 1. exit. mysql_error(). "mysql_password"). you either need to access the result with numeric indices by using mysql_fetch_row or add alias names. To access the other column(s) of the same name. and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]. See the example at the mysql_fetch_array description about aliases. mysql_error(). exit. exit. inside the following loop. you'll // then create $userid. "mysql_user". if (!$conn) { echo "Unable to connect to DB: " . If two or more columns of the result have the same field names. } if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . if (!$result) { echo "Could not successfully run query ($sql) from DB: " . } // While a row of data exists. the last column will take precedence. Parameters result Return Values The result resource that is being evaluated. put that row in $row as an associative array // Note: If you're expecting just one row. } $sql = "SELECT id as userid. echo $row["fullname"]. echo $row["userstatus"]. $result = mysql_query($sql). Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. Returns an associative array of strings that corresponds to the fetched row. • mysql_fetch_assoc Fetch a result row as an associative array Description array mysql_fetch_assoc(resource result). fullname. An expanded mysql_fetch_assoc example <?php $conn = mysql_connect("localhost".14. nothing to print so am exiting". $fullname. mysql_fetch_assoc Copyright 1997-2012 the PHP Documentation Group.4. } 22 . mysql_error(). } if (mysql_num_rows($result) == 0) { echo "No rows found.

The numerical field offset.column name table . See Also mysql_fetch_row mysql_fetch_array mysql_data_seek mysql_query mysql_error 1. • mysql_fetch_field Get column information from a result and return as an object Description object mysql_fetch_field(resource result. while it provides a significant added value. Note Field names returned by this function are case-sensitive. This function can be used to obtain information about fields in the provided query result. int field_offset= =0).4. mysql_fetch_field Copyright 1997-2012 the PHP Documentation Group. The field_offset starts at 0.name of the table the column belongs to 23 . This result comes from a call to mysql_query. If the field offset is not specified. Returns an object containing field information. Parameters result field_offset The result resource that is being evaluated. Note This function sets NULL fields to the PHP NULL value. Return Values Returns an object containing field information. the next field that was not yet retrieved by this function is retrieved.MySQL Extension (mysql) 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.15. The properties of the object are: • • name .

1 if the column cannot be NULL primary_key . if (!$result) { die('Query failed: ' . 'mysql_user'.MySQL Extension (mysql) • • • • • • • • • • max_length .1 if the column is a unique key multiple_key .1 if the column is a primary key unique_key . while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />\n". $result = mysql_query('select * from table'). $i++. } mysql_free_result($result).22. mysql_fetch_field example <?php $conn = mysql_connect('localhost'.1 if the column is unsigned zerofill . } echo "<pre> blob: $meta->blob max_length: $meta->max_length multiple_key: $meta->multiple_key name: $meta->name not_null: $meta->not_null numeric: $meta->numeric primary_key: $meta->primary_key table: $meta->table type: $meta->type unique_key: $meta->unique_key unsigned: $meta->unsigned zerofill: $meta->zerofill </pre>". ?> Notes Note Field names returned by this function are case-sensitive. } mysql_select_db('database').1 if the column is a non-unique key numeric . mysql_error()). $i). $meta = mysql_fetch_field($result. mysql_error()). See Also 24 .1 if the column is zero-filled Examples Example 1.1 if the column is a BLOB type . 'mysql_password'). if (!$conn) { die('Could not connect: ' .1 if the column is numeric blob . if (!$meta) { echo "No information available<br />\n".the type of the column unsigned . } /* get column metadata */ $i = 0.maximum length of the column not_null .

print_r($lengths).email FROM people WHERE id = '42'"). mysql_fetch_lengths Copyright 1997-2012 the PHP Documentation Group. } $row = mysql_fetch_assoc($result). This result comes from a call to mysql_query. exit.16. and mysql_fetch_object in an array. ?> The above example will output something similar to: Array ( [id] => 42 [email] => user@example. Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL. print_r($row). mysql_fetch_assoc. An array of lengths on success or FALSE on failure. mysql_error(). Examples Example 1. starting at offset 0.com ) Array ( [0] => 2 [1] => 16 ) 25 . mysql_fetch_lengths stores the lengths of each result column in the last row returned by mysql_fetch_row. if (!$result) { echo 'Could not run query: ' . A mysql_fetch_lengths example <?php $result = mysql_query("SELECT id.MySQL Extension (mysql) mysql_field_seek 1.4. mysql_fetch_array. Parameters result Return Values The result resource that is being evaluated.23. $lengths = mysql_fetch_lengths($result). • mysql_fetch_lengths Get the length of each output in a result Description array mysql_fetch_lengths(resource result).

string class_name. array params). while ($row = mysql_fetch_object($result)) { echo $row->user_id. Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.0. "user". This result comes from a call to mysql_query. If not specified. mysql_fetch_object example <?php mysql_connect("hostname". Returns an object with string properties that correspond to the fetched row. set the properties of and return. mysql_fetch_object Copyright 1997-2012 the PHP Documentation Group. Parameters result class_name params Return Values The result resource that is being evaluated.0 Examples Description Added the ability to return as a different object.17. ?> 26 . } mysql_free_result($result). echo $row->fullname.MySQL Extension (mysql) See Also mysql_field_len mysql_fetch_row strlen 1. or FALSE if there are no more rows. An optional array of parameters to pass to the constructor for class_name objects. • mysql_fetch_object Fetch a result row as an object Description object mysql_fetch_object(resource result. a stdClass object is returned.24. Example 1. $result = mysql_query("select * from mytable"). mysql_select_db("mydb"). Changelog Version 5.4. The name of the class to instantiate. "password").

instead of an array. ?> Notes Performance Speed-wise. the function is identical to mysql_fetch_array.4. and not by their offsets (numbers are illegal property names). } mysql_connect("hostname". with one difference . Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_select_db("mydb").an object is returned. Note Field names returned by this function are case-sensitive. "password"). Parameters 27 . var_dump($obj). • mysql_fetch_row Get a result row as an enumerated array Description array mysql_fetch_row(resource result). and almost as quick as mysql_fetch_row (the difference is insignificant). Note mysql_fetch_object is similar to mysql_fetch_array.MySQL Extension (mysql) Example 1. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_row mysql_data_seek mysql_query 1. mysql_fetch_row Copyright 1997-2012 the PHP Documentation Group.25. Note This function sets NULL fields to the PHP NULL value. that means that you can only access the data by the field names. 'foo'). $result = mysql_query("select name from mytable limit 1"). $obj = mysql_fetch_object($result. "user". mysql_fetch_object example <?php class foo { public $name.18. Indirectly.

4.26. Returns an numerical array of strings that corresponds to the fetched row. or FALSE if there are no more rows. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_result 1. exit. mysql_error(). This result comes from a call to mysql_query. echo $row[0]. The flags are reported as a single word per flag separated by a single space.19. // 42 echo $row[1]. mysql_field_flags returns the field flags of the specified field. mysql_fetch_row fetches one row of data from the result associated with the specified result identifier.MySQL Extension (mysql) result Return Values The result resource that is being evaluated. // the email value ?> Notes Note This function sets NULL fields to the PHP NULL value. Examples Example 1. • mysql_field_flags Get the flags associated with the specified field in a result Description string mysql_field_flags(resource result. int field_offset). if (!$result) { echo 'Could not run query: ' . Each result column is stored in an array offset. } $row = mysql_fetch_row($result). The row is returned as an array. Parameters 28 . Fetching one row with mysql_fetch_row <?php $result = mysql_query("SELECT id. starting at offset 0.email FROM people WHERE id = '42'"). mysql_field_flags Copyright 1997-2012 the PHP Documentation Group. so that you can split the returned value using explode.

"auto_increment" and "timestamp". mysql_field_len Copyright 1997-2012 the PHP Documentation Group. Examples Example 1. The following flags are reported. "zerofill". "multiple_key". print_r(explode(' '. "binary". "blob". 0). $flags)).4. If field_offset does not exist. The numerical field offset.email FROM people WHERE id = '42'"). A mysql_field_flags example <?php $result = mysql_query("SELECT id.MySQL Extension (mysql) result field_offset The result resource that is being evaluated. • mysql_field_len Returns the length of the specified field 29 . "unsigned". The field_offset starts at 0. "unique_key". Return Values Returns a string of flags associated with the result or FALSE on failure.20. "enum".27. "primary_key". echo $flags. mysql_error(). the following deprecated alias may be used: mysql_fieldflags See Also mysql_field_type mysql_field_len 1. } $flags = mysql_field_flags($result. exit. This result comes from a call to mysql_query. an error of level E_WARNING is also issued. ?> The above example will output something similar to: not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment ) Notes Note For backward compatibility. if your version of MySQL is current enough to support them: "not_null". if (!$result) { echo 'Could not run query: ' .

The field_offset starts at 0. Examples Example 1.4. The numerical field offset. mysql_field_len example <?php $result = mysql_query("SELECT id.28. if (!$result) { echo 'Could not run query: ' . If field_offset does not exist.email FROM people WHERE id = '42'"). 0). This result comes from a call to mysql_query. the following deprecated alias may be used: mysql_fieldlen See Also mysql_fetch_lengths strlen 1. ?> Notes Note For backward compatibility. mysql_field_name Copyright 1997-2012 the PHP Documentation Group. exit. int field_offset). $length = mysql_field_len($result. 30 . mysql_field_len returns the length of the specified field. • mysql_field_name Get the name of the specified field in a result Description string mysql_field_name(resource result. an error of level E_WARNING is also issued. Return Values The length of the specified field index on success or FALSE on failure.MySQL Extension (mysql) Description int mysql_field_len(resource result. Parameters result field_offset The result resource that is being evaluated.21. echo $length. int field_offset). mysql_error(). } // Will get the length of the id field as specified in the database // schema.

MySQL Extension (mysql) mysql_field_name returns the name of the specified field index. Examples Example 1. 'mysql_user'. The numerical field offset. if (!$db_selected) { die("Could not set $dbname: " . Parameters result field_offset The result resource that is being evaluated. $db_selected = mysql_select_db($dbname. $link). } $res = mysql_query('select * from users'. ?> The above example will output: user_id password Notes Note Field names returned by this function are case-sensitive. } $dbname = 'mydb'. $link). "\n". mysql_error()). This result comes from a call to mysql_query. mysql_field_name example <?php /* The users table consists of three fields: * user_id * username * password. an error of level E_WARNING is also issued. */ $link = mysql_connect('localhost'. echo mysql_field_name($res. Note For backward compatibility. 2). if (!$link) { die('Could not connect to MySQL server: ' . mysql_error()). echo mysql_field_name($res. 'mysql_password').29. Return Values The name of the specified field index on success or FALSE on failure. The field_offset starts at 0. If field_offset does not exist. 0) . the following deprecated alias may be used: mysql_fieldname See Also mysql_field_type mysql_field_len 1.22.4. mysql_field_seek 31 .

Return Values Returns TRUE on success or FALSE on failure. The field_offset starts at 0. • mysql_field_table Get name of the table the specified field is in Description string mysql_field_table(resource result.MySQL Extension (mysql) Copyright 1997-2012 the PHP Documentation Group.4. If field_offset does not exist. Parameters result field_offset The result resource that is being evaluated. This result comes from a call to mysql_query. an error of level E_WARNING is also issued. If field_offset does not exist. Parameters result field_offset The result resource that is being evaluated. an error of level E_WARNING is also issued. the field offset specified in mysql_field_seek will be returned. 32 . Return Values The name of the table on success. This result comes from a call to mysql_query. The numerical field offset. Seeks to the specified field offset. Returns the name of the table that the specified field is in. If the next call to mysql_fetch_field doesn't include a field offset. int field_offset). mysql_field_table Copyright 1997-2012 the PHP Documentation Group. • mysql_field_seek Set result pointer to a specified field offset Description bool mysql_field_seek(resource result.23. See Also mysql_fetch_field 1. The field_offset starts at 0. The numerical field offset. int field_offset).

4. } ?> Notes Note For backward compatibility.MySQL Extension (mysql) Examples Example 1. $i). "blob". $i). $field = mysql_field_name($result. mysql_field_type Copyright 1997-2012 the PHP Documentation Group. country.*. This result comes from a call to mysql_query. • mysql_field_type Get the type of the specified field in a result Description string mysql_field_type(resource result. $i < mysql_num_fields($result). The field_offset starts at 0.30. Parameters result field_offset The result resource that is being evaluated.24.country_id = countr // get the result from the DB $result = mysql_query($query). int field_offset). "string". mysql_field_type is similar to the mysql_field_name function. The numerical field offset. ++$i) { $table = mysql_field_table($result.* FROM account.name = 'Portugal' AND account. A mysql_field_table example <?php $query = "SELECT account. an error of level E_WARNING is also issued. "real". echo "$table: $field\n". the following deprecated alias may be used: mysql_fieldtable See Also mysql_list_tables 1. and others as detailed in the MySQL documentation. Return Values The returned field type will be one of "int". If field_offset does not exist. // Lists the table name and then the field name for ($i = 0. but the field type is returned instead. Examples 33 . country WHERE country. The arguments are identical.

• mysql_free_result Free result memory Description bool mysql_free_result(resource result). "mysql_password"). the following deprecated alias may be used: mysql_fieldtype See Also mysql_field_name mysql_field_len 1. mysql_close(). " record(s)\n". $i). $len = mysql_field_len($result. $name . mysql_select_db("mysql"). $rows = mysql_num_rows($result). $table . "mysql_username". $name = mysql_field_name($result. " fields and " . $result = mysql_query("SELECT * FROM func"). $flags = mysql_field_flags($result. " " .MySQL Extension (mysql) Example 1.31. echo "Your '" . mysql_free_result Copyright 1997-2012 the PHP Documentation Group. All associated result memory is automatically freed at the end of the script's execution. ?> The above example will output something similar to: 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. } mysql_free_result($result). echo "The table has the following fields:\n".4. $fields . " " .25. "\n". $flags . $i). $i). " " . $table = mysql_field_table($result. Parameters 34 . for ($i=0. $fields = mysql_num_fields($result). $rows . mysql_free_result will free all memory associated with the result identifier result. $i < $fields. 0). mysql_field_type example <?php mysql_connect("localhost". "' table has " . echo $type . $i). $len . 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. $i++) { $type = mysql_field_type($result.

EXPLAIN. } /* Use the result. /* Now we free up the result and continue on with our script */ mysql_free_result($result). This result comes from a call to mysql_query. the following deprecated alias may be used: mysql_freeresult See Also mysql_query is_resource 1.32. mysql_get_client_info returns a string that represents the client library version. mysql_error(). an error of level E_WARNING will be emitted. A mysql_free_result example <?php $result = mysql_query("SELECT id. echo $row['email']. If a non-resource is used for the result. mysql_get_client_info Copyright 1997-2012 the PHP Documentation Group.26. exit. It's worth noting that mysql_query only returns a resource for SELECT.email FROM people WHERE id = '42'"). if (!$result) { echo 'Could not run query: ' . • mysql_get_client_info Get MySQL client info Description string mysql_get_client_info(). Returns TRUE on success or FALSE on failure. Examples 35 . Examples Example 1. assuming we're done with it afterwards */ $row = mysql_fetch_assoc($result). echo $row['id']. ?> Notes Note For backward compatibility. Return Values The MySQL client version.4.MySQL Extension (mysql) result Return Values The result resource that is being evaluated. SHOW. and DESCRIBE queries.

it will try to create one as if mysql_connect was called with no arguments. mysql_get_client_info()).MySQL Extension (mysql) Example 1. mysql_get_client_info example <?php printf("MySQL client info: %s\n". 'mysql_password'). the last link opened by mysql_connect is assumed. including the server host name. mysql_get_host_info Copyright 1997-2012 the PHP Documentation Group. Describes the type of connection in use for the connection.4. mysql_get_host_info example <?php $link = mysql_connect('localhost'.39 See Also mysql_get_host_info mysql_get_proto_info mysql_get_server_info 1.23. • mysql_get_host_info Get MySQL host info Description string mysql_get_host_info(resource link_identifier).34. If no connection is found or established. Examples Example 1. Parameters link_identifier The MySQL connection. } 36 . ?> The above example will output something similar to: MySQL client info: 3. an E_WARNING level error is generated. If no such link is found.27. 'mysql_user'. mysql_error()). Return Values Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure.33. If the link identifier is not specified. if (!$link) { die('Could not connect: ' .

'mysql_password').MySQL Extension (mysql) printf("MySQL host info: %s\n". Parameters link_identifier The MySQL connection. mysql_get_proto_info()).4.35. Retrieves the MySQL protocol. If no connection is found or established. mysql_get_proto_info Copyright 1997-2012 the PHP Documentation Group. an E_WARNING level error is generated. Examples Example 1. the last link opened by mysql_connect is assumed. mysql_error()). Return Values Returns the MySQL protocol on success or FALSE on failure. ?> The above example will output something similar to: 37 . If no such link is found. • mysql_get_proto_info Get MySQL protocol info Description int mysql_get_proto_info(resource link_identifier). if (!$link) { die('Could not connect: ' .28. ?> The above example will output something similar to: MySQL host info: Localhost via UNIX socket See Also mysql_get_client_info mysql_get_proto_info mysql_get_server_info 1. If the link identifier is not specified. 'mysql_user'. } printf("MySQL protocol version: %s\n". mysql_get_host_info()). mysql_get_proto_info example <?php $link = mysql_connect('localhost'. it will try to create one as if mysql_connect was called with no arguments.

36.0. mysql_error()). Examples Example 1.29. If the link identifier is not specified.1-alpha 38 . it will try to create one as if mysql_connect was called with no arguments. Parameters link_identifier The MySQL connection. mysql_get_server_info()). Return Values Returns the MySQL server version on success or FALSE on failure. If no such link is found. ?> The above example will output something similar to: MySQL server version: 4. } printf("MySQL server version: %s\n". 'mysql_password'). if (!$link) { die('Could not connect: ' . If no connection is found or established. an E_WARNING level error is generated. • mysql_get_server_info Get MySQL server info Description string mysql_get_server_info(resource link_identifier). 'mysql_user'. mysql_get_server_info Copyright 1997-2012 the PHP Documentation Group. the last link opened by mysql_connect is assumed.MySQL Extension (mysql) MySQL protocol version: 10 See Also mysql_get_client_info mysql_get_host_info mysql_get_server_info 1.4. Retrieves the MySQL server version. mysql_get_server_info example <?php $link = mysql_connect('localhost'.

their values will correspond to the query...).. Statements that are not listed will return FALSE .). Return Values Returns information about the statement on success.).. VALUES statement only if multiple value lists are specified in the statement. INSERT INTO . Relevant MySQL Statements Statements that return string values... String format: Records: 37 Duplicates: 0 Warnings: 0 LOAD DATA INFILE .. VALUES (.. 39 .37. SELECT .. See the example below for which statements provide information.(....4. an E_WARNING level error is generated... mysql_info Copyright 1997-2012 the PHP Documentation Group. If no such link is found. Examples Example 1.. String format: Records: 23 Duplicates: 0 Warnings: 0 INSERT INTO . the last link opened by mysql_connect is assumed. Parameters link_identifier The MySQL connection. String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0 ALTER TABLE String format: Records: 60 Duplicates: 0 Warnings: 0 UPDATE String format: Rows matched: 65 Changed: 65 Warnings: 0 Notes Note mysql_info returns a non. The numbers are only for illustrating purpose.(. If no connection is found or established. Returns detailed information about the last query. If the link identifier is not specified. and what the returned value may look like.. or FALSE on failure. it will try to create one as if mysql_connect was called with no arguments.FALSE value for the INSERT ...MySQL Extension (mysql) See Also mysql_get_client_info mysql_get_host_info mysql_get_proto_info phpversion 1.30. • mysql_info Get information about the most recent query Description string mysql_info(resource link_identifier).

an E_WARNING level error is generated.MySQL Extension (mysql) See Also mysql_affected_rows mysql_insert_id mysql_stat 1. • mysql_insert_id Get the ID generated in the last query Description int mysql_insert_id(resource link_identifier). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. mysql_error()). printf("Last inserted record has id %d\n".38. 0 if the previous query does not generate an AUTO_INCREMENT value. ?> 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). Parameters link_identifier The MySQL connection. If no such link is found. For more information about PHP's maximum integer values. 'mysql_password').31. Instead. Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). mysql_insert_id()). it will try to create one as if mysql_connect was called with no arguments. or FALSE if no MySQL connection was established. } mysql_select_db('mydb'). If the link identifier is not specified. 40 . please see the integer documentation. use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. Examples Example 1.4. mysql_insert_id Copyright 1997-2012 the PHP Documentation Group. Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success. mysql_query("INSERT INTO mytable (product) values ('kossu')"). if (!$link) { die('Could not connect: ' . 'mysql_user'. If no connection is found or established. mysql_insert_id example <?php $link = mysql_connect('localhost'. the last link opened by mysql_connect is assumed.

See Also mysql_query mysql_info 1. If the link identifier is not specified. Parameters link_identifier The MySQL connection.39. 41 . while ($row = mysql_fetch_assoc($res)) { echo $row['Database'] . such as mysql_fetch_array.4. Note The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value. 'mysql_user'. Return Values Returns a result pointer resource on success. 'mysql_user'. the last link opened by mysql_connect is assumed. Examples Example 1. mysql_list_dbs Copyright 1997-2012 the PHP Documentation Group. mysql_list_dbs example <?php // Usage without mysql_list_dbs() $link = mysql_connect('localhost'.MySQL Extension (mysql) 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. Use the mysql_tablename function to traverse this result pointer. or any function for result tables.4. and is not reset between queries. $res = mysql_query("SHOW DATABASES"). Returns a result pointer containing the databases available from the current mysql daemon. 'mysql_password'). If no connection is found or established. or FALSE on failure. it will try to create one as if mysql_connect was called with no arguments. • mysql_list_dbs List databases available on a MySQL server Description resource mysql_list_dbs(resource link_identifier). If no such link is found. 'mysql_password').0. } // Deprecated as of PHP 5. "\n". $db_list = mysql_list_dbs($link).4. Warning This function has been DEPRECATED as of PHP 5.0 $link = mysql_connect('localhost'. an E_WARNING level error is generated. Relying on this function is highly discouraged.32.

If the link identifier is not specified.33. If no connection is found or established. If no such link is found. mysql_list_fields Copyright 1997-2012 the PHP Documentation Group. or FALSE on failure. the last link opened by mysql_connect is assumed. } ?> The above example will output something similar to: database1 database2 database3 Notes Note For backward compatibility. it will try to create one as if mysql_connect was called with no arguments. Return Values A result pointer resource on success. resource link_identifier). • mysql_list_fields List MySQL table fields Description resource mysql_list_fields(string database_name. The name of the table that's being queried. 42 . The MySQL connection. Retrieves information about the given table name. string table_name. an E_WARNING level error is generated.4. the following deprecated alias may be used: mysql_listdbs See Also mysql_db_name mysql_select_db 1. It is preferable to use mysql_query to issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead. Parameters database_name table_name link_identifier The name of the database that's being queried. "\n". This function is deprecated.MySQL Extension (mysql) while ($row = mysql_fetch_object($db_list)) { echo $row->Database .

mysql_field_len. mysql_field_name and mysql_field_type. • mysql_list_processes List MySQL processes Description 43 . exit. mysql_error(). Alternate to deprecated mysql_list_fields <?php $result = mysql_query("SHOW COLUMNS FROM sometable"). if (!$result) { echo 'Could not run query: ' .4.34. Examples Example 1. } } ?> The above example will output something similar to: 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.40. mysql_list_processes Copyright 1997-2012 the PHP Documentation Group.MySQL Extension (mysql) The returned result can be used with mysql_field_flags. the following deprecated alias may be used: mysql_listfields See Also mysql_field_flags mysql_info 1. } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row).

$row["Id"]. 'mysql_user'. the last link opened by mysql_connect is assumed. while ($row = mysql_fetch_assoc($result)){ printf("%s %s %s %s %s\n". $row["Time"]). $row["db"]. Retrieves the current MySQL server threads. 44 . mysql_list_tables Copyright 1997-2012 the PHP Documentation Group. If the link identifier is not specified. If no connection is found or established. $row["Command"].4. Retrieves a list of table names from a MySQL database. it will try to create one as if mysql_connect was called with no arguments. resource link_identifier). 'mysql_password').41. $row["Host"]. If no such link is found. $result = mysql_list_processes($link). } mysql_free_result($result). an E_WARNING level error is generated. Examples Example 1. • mysql_list_tables List tables in a MySQL database Description resource mysql_list_tables(string database. Return Values A result pointer resource on success or FALSE on failure. mysql_list_processes example <?php $link = mysql_connect('localhost'. ?> The above example will output something similar to: 1 localhost test Processlist 0 4 localhost mysql sleep 5 See Also mysql_thread_id mysql_stat 1.MySQL Extension (mysql) resource mysql_list_processes(resource link_identifier). Parameters link_identifier The MySQL connection.35.

echo 'MySQL Error: ' . Changelog Version 4.MySQL Extension (mysql) This function is deprecated. } $sql = "SHOW TABLES FROM $dbname". if (!$result) { echo "DB Error. 'mysql_user'. If the link identifier is not specified. mysql_error(). exit. it will try to create one as if mysql_connect was called with no arguments. could not list tables\n". the following deprecated alias may be used: mysql_listtables See Also mysql_list_dbs mysql_tablename 45 . } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}\n". or any function for result tables. ?> Notes Note For backward compatibility. Example 1. Parameters database link_identifier The name of the database The MySQL connection.3. If no connection is found or established. such as mysql_fetch_array. It is preferable to use mysql_query to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. } mysql_free_result($result). mysql_list_tables alternative example <?php $dbname = 'mysql_dbname'. if (!mysql_connect('mysql_host'. Use the mysql_tablename function to traverse this result pointer. If no such link is found. Return Values A result pointer resource on success or FALSE on failure.42. the last link opened by mysql_connect is assumed. exit.7 Examples Description This function became deprecated. an E_WARNING level error is generated. 'mysql_password')) { echo 'Could not connect to mysql'. $result = mysql_query($sql).

Returns the number of fields in the result set resource on success or FALSE on failure. if (!$result) { echo 'Could not run query: ' . the following deprecated alias may be used: mysql_numfields See Also mysql_select_db mysql_query mysql_fetch_field mysql_num_rows 1.4. mysql_num_rows Copyright 1997-2012 the PHP Documentation Group.email === two fields */ echo mysql_num_fields($result). This result comes from a call to mysql_query. • mysql_num_rows 46 . ?> Notes Note For backward compatibility.MySQL Extension (mysql) 1.4.36. exit.37. Examples Example 1. mysql_num_fields Copyright 1997-2012 the PHP Documentation Group. A mysql_num_fields example <?php $result = mysql_query("SELECT id.email FROM people WHERE id = '42'"). mysql_error(). Retrieves the number of fields from a query. Parameters result Return Values The result resource that is being evaluated. } /* returns 2 because id. • mysql_num_fields Get number of fields in result Description int mysql_num_fields(resource result).43.

$result = mysql_query("SELECT * FROM table1". mysql_select_db("database". $num_rows = mysql_num_rows($result). REPLACE or DELETE query. Retrieves the number of rows from a result set.44. mysql_num_rows will not return the correct value until all the rows in the result set have been retrieved. Note For backward compatibility.4. Examples Example 1. use mysql_affected_rows. $link). "mysql_password"). 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. To retrieve the number of rows affected by a INSERT. echo "$num_rows Rows\n". The number of rows in a result set on success or FALSE on failure. mysql_pconnect Copyright 1997-2012 the PHP Documentation Group.38. This command is only valid for statements like SELECT or SHOW that return an actual result set. $link). ?> Notes Note If you use mysql_unbuffered_query. mysql_num_rows example <?php $link = mysql_connect("localhost". UPDATE.MySQL Extension (mysql) Get number of rows in result Description int mysql_num_rows(resource result). This result comes from a call to mysql_query. • mysql_pconnect 47 . Parameters result Return Values The result resource that is being evaluated. "mysql_user".

the link will remain open for future use (mysql_close will not close links established by mysql_pconnect). string username= =ini_get("mysql. an identifier for it will be returned instead of opening a new connection. that these kind of links only work if you are using a module version of PHP.default_host").3. It can also include a port number. then the default value is 'localhost:3306' username password client_flags The username. The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling). 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. Default value is an empty password. e. the connection to the SQL server will not be closed when the execution of the script ends. Changelog Version 4. when connecting.g. If the PHP directive mysql.g. mysql_pconnect acts very much like mysql_connect with two major differences. Default value is the name of the user that owns the server process. The password. Parameters server The MySQL server. Establishes a persistent connection to a MySQL server.0 Notes Description Added the client_flags parameter. or FALSE on failure. First.default_password"). See the Persistent Database Connections section for more information. Note 48 . Second. MYSQL_CLIENT_COMPRESS . "hostname:port" or a path to a local socket e. ":/path/to/socket" for the localhost.default_user"). Note Note. This type of link is therefore called 'persistent'.default_host is undefined (default). MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . Instead. username and password. int client_flags). string password= =ini_get("mysql. the function would first try to find a (persistent) link that's already open with the same host.MySQL Extension (mysql) Open a persistent connection to a MySQL server Description resource mysql_pconnect(string server= =ini_get("mysql. Return Values Returns a MySQL persistent link identifier on success. MYSQL_CLIENT_SSL . If one is found.

If no such link is found. Note Since MySQL 5. exiting. Examples Example 1. exit. • mysql_ping Ping a server connection or reconnect if there is no connection Description bool mysql_ping(resource link_identifier). exiting after query #1'.13. /* So the connection is still alive. A mysql_ping example <?php set_time_limit(0). Checks whether or not the connection to the server is working. $db = mysql_select_db('mydb'). to check whether or not the server has closed the connection and reconnect if necessary.4. automatic reconnection feature is disabled.MySQL Extension (mysql) You can suppress the error message on failure by prepending a @ to the function name. exit. otherwise FALSE . it will try to create one as if mysql_connect was called with no arguments. If the link identifier is not specified.0. Parameters link_identifier The MySQL connection. See Also mysql_connect Persistent Database Connections 1. mysql_ping Copyright 1997-2012 the PHP Documentation Group. If no connection is found or established. 'mypass').39. the last link opened by mysql_connect is assumed. $conn = mysql_connect('localhost'. let's run another query */ $result2 = mysql_query($sql2). if not. if (!$result) { echo 'Query #1 failed. } mysql_free_result($result). This function can be used by scripts that remain idle for a long while. Return Values Returns TRUE if the connection to the server MySQL server is working. an E_WARNING level error is generated. } /* Make sure the connection is still alive. If it has gone down. an automatic reconnection is attempted.45. try to reconnect */ if (!mysql_ping($conn)) { echo 'Lost connection. ?> 49 . /* Assuming this query will take a long time */ $result = mysql_query($sql).'. 'mysqluser'.

REPLACE. 50 . If no connection is found or established. link_identifier The MySQL connection. 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. Return Values For SELECT. 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. • mysql_query Send a MySQL query Description resource mysql_query(string query. The returned result resource should be passed to mysql_fetch_array.4. Examples Example 1. DELETE. or UPDATE statement. etc. INSERT. DESCRIBE.MySQL Extension (mysql) See Also mysql_thread_id mysql_list_processes 1. INSERT.46. UPDATE. If the link identifier is not specified. DROP. mysql_query returns a resource on success. the last link opened by mysql_connect is assumed. an E_WARNING level error is generated. Invalid Query The following query is syntactically invalid. EXPLAIN and other statements returning resultset. mysql_query returns TRUE on success or FALSE on error. mysql_query will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. Parameters query An SQL query The query string should not end with a semicolon. resource link_identifier). or FALSE on error. it will try to create one as if mysql_connect was called with no arguments. For other type of SQL statements. so mysql_query fails and returns FALSE . Data inside the query should be properly escaped. If no such link is found. mysql_query Copyright 1997-2012 the PHP Documentation Group.40. and other functions for dealing with result tables. SHOW. to access the returned data.

address. // Perform Query $result = mysql_query($query). Valid Query The following query is valid. } // Use result // Attempting to print $result won't allow access to information in the resource // One of the mysql result functions must be used // See also mysql_result(). echo $row['lastname'].= 'Whole query: ' . while ($row = mysql_fetch_assoc($result)) { echo $row['firstname']. <?php // This could be supplied by a user. • mysql_real_escape_string Escapes special characters in a string for use in an SQL statement 51 . and the error. mysql_real_escape_string($firstname). etc. $message . see mysql_real_escape_string() $query = sprintf("SELECT firstname.41. Useful for debugging. if (!$result) { die('Invalid query: ' . lastname. } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result). mysql_fetch_array(). mysql_error()). ?> See Also mysql_connect mysql_error mysql_real_escape_string mysql_result mysql_fetch_assoc mysql_unbuffered_query 1. // Check result // This shows the actual query sent to MySQL. // Formulate Query // This is the best way to perform an SQL query // For more examples.47. } ?> Example 1. mysql_fetch_row().4. if (!$result) { $message = 'Invalid query: ' .MySQL Extension (mysql) <?php $result = mysql_query('SELECT * WHERE 1=1'). $lastname = 'fox'. mysql_real_escape_string Copyright 1997-2012 the PHP Documentation Group. echo $row['address']. "\n". for example $firstname = 'fred'. mysql_error() . die($message). echo $row['age']. so mysql_query returns a resource. mysql_real_escape_string($lastname)). $query. age FROM friends WHERE firstname='%s' AND lastname='%s'".

Return Values Returns the escaped string. Parameters unescaped_string link_identifier The string that is to be escaped. or FALSE on error.MySQL Extension (mysql) Description string mysql_real_escape_string(string unescaped_string. Escapes special characters in the unescaped_string.48. which prepends backslashes to the following characters: \x00. mysql_real_escape_string($password)). // This means the query sent to MySQL would be: echo $query. If the link identifier is not specified. " and \x1a. \. it could be anything the user wanted! For example: $_POST['username'] = 'aidan'. // Query $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'". the last link opened by mysql_connect is assumed. resource link_identifier). ?> Example 1. Simple mysql_real_escape_string example <?php // Connect $link = mysql_connect('mysql_host'. an E_WARNING level error is generated. If binary data is to be inserted. If no such link is found. this function must be used.49. If no connection is found or established. mysql_real_escape_string($user). \n. it will try to create one as if mysql_connect was called with no arguments. '. ?> The query sent to MySQL: SELECT * FROM users WHERE user='aidan' AND password='' OR ''='' 52 . An example SQL Injection Attack <?php // We didn't check $_POST['password']. // Query database to check if there are any matching users $query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'". mysql_query($query). This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. 'mysql_password') OR die(mysql_error()). The MySQL connection. $_POST['password'] = "' OR ''='". taking into account the current character set of the connection so that it is safe to place it in a mysql_query. \r. 'mysql_user'. Examples Example 1. mysql_real_escape_string calls MySQL's library function mysql_real_escape_string.

The row number from the result that's being retrieved. you should consider using one of the functions that fetch an entire row (specified below). If link_identifier isn't defined. Parameters result row The result resource that is being evaluated. See Also mysql_client_encoding addslashes stripslashes The magic_quotes_gpc directive The magic_quotes_runtime directive 1.42. • mysql_result Get result data Description string mysql_result(resource result. GRANT. the last MySQL connection is used. When working on large result sets. Retrieves the contents of one cell from a MySQL result set.fieldname argument. first apply stripslashes to the data. Note mysql_real_escape_string does not escape % and _. Note If magic_quotes_gpc is enabled.4. mysql_result Copyright 1997-2012 the PHP Documentation Group. mixed field= =0). This result comes from a call to mysql_query. and FALSE is returned. note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename. they're MUCH quicker than mysql_result. As these functions return the contents of multiple cells in one function call. int row. Row numbers start at 0. Notes Note A MySQL connection is required before using mysql_real_escape_string otherwise an error of level E_WARNING is generated. the query is vulnerable to SQL Injection Attacks. or REVOKE. 53 . Note If this function is not used to escape data. Using this function on data which has already been escaped will escape the data twice.MySQL Extension (mysql) This would allow anyone to log in without a valid password. These are wildcards in MySQL if combined with LIKE. Also.

2). 54 . • mysql_select_db Select a MySQL database Description bool mysql_select_db(string database_name. 'mysql_password'). mysql_error()). mysql_error()). mysql_select_db Copyright 1997-2012 the PHP Documentation Group. } if (!mysql_select_db('database_name')) { die('Could not select database: ' . or the field's table dot field name (tablename. If the column name has been aliased ('select foo as bar from. Examples Example 1. If undefined. 'mysql_user'. Every subsequent call to mysql_query will be made on the active database.. the field's name. } echo mysql_result($result. mysql_result example <?php $link = mysql_connect('localhost'.').. Return Values The contents of one cell from a MySQL result set on success.fieldname). ?> Notes Note Calls to mysql_result should not be mixed with calls to other functions that deal with the result set. // outputs third employee's name mysql_close($link). It can be the field's offset.4.43.employee'). resource link_identifier). } $result = mysql_query('SELECT name FROM work.50. See Also mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object 1.MySQL Extension (mysql) field The name or offset of the field being retrieved. if (!$result) { die('Could not query:' . use the alias instead of the column name. the first field is retrieved. mysql_error()). or FALSE on failure. if (!$link) { die('Could not connect: ' . Sets the current active database on the server that's associated with the specified link identifier.

'mysql_password'). Examples Example 1.MySQL Extension (mysql) Parameters database_name link_identifier The name of the database that is to be selected. resource link_identifier). } // make foo the current db $db_selected = mysql_select_db('foo'. mysql_select_db example <?php $link = mysql_connect('localhost'. If the link identifier is not specified. the following deprecated alias may be used: mysql_selectdb See Also mysql_connect mysql_pconnect mysql_query 1. Sets the default character set for the current connection.51. If no connection is found or established. 55 . mysql_error()).44. an E_WARNING level error is generated. mysql_set_charset Copyright 1997-2012 the PHP Documentation Group. mysql_error()). it will try to create one as if mysql_connect was called with no arguments. $link). The MySQL connection. If no such link is found. if (!$db_selected) { die ('Can\'t use foo : ' . } ?> Notes Note For backward compatibility. Return Values Returns TRUE on success or FALSE on failure. • mysql_set_charset Sets the client character set Description bool mysql_set_charset(string charset.4. if (!$link) { die('Not connected : ' . 'mysql_user'. the last link opened by mysql_connect is assumed.

open tables. If no such link is found.MySQL Extension (mysql) Parameters charset link_identifier A valid character set name.. If no connection is found or established. Return Values Returns TRUE on success or FALSE on failure. queries. If the link identifier is not specified.0. Parameters link_identifier The MySQL connection.7 or later. See Also mysql_client_encoding List of character sets that MySQL supports 1. The MySQL connection. Notes Note This function requires MySQL 5. it will try to create one as if mysql_connect was called with no arguments. If no such link is found. For a complete list of other status variables.45. the last link opened by mysql_connect is assumed. Note This is the preferred way to change the charset. Examples 56 . • mysql_stat Get current system status Description string mysql_stat(resource link_identifier).4. you have to use the SHOW STATUS SQL command. Using mysql_query to execute SET NAMES . Return Values Returns a string with the status for uptime. If link_identifier is invalid. NULL is returned. an E_WARNING level error is generated. is not recommended. If no connection is found or established. flush tables and queries per second. If the link identifier is not specified. mysql_stat Copyright 1997-2012 the PHP Documentation Group. an E_WARNING level error is generated. mysql_stat returns the current server status. it will try to create one as if mysql_connect was called with no arguments. threads. the last link opened by mysql_connect is assumed.

mysql_stat example <?php $link = mysql_connect('localhost'. mysql_stat($link)). Alternative mysql_stat example <?php $link = mysql_connect('localhost'. mysql_tablename Copyright 1997-2012 the PHP Documentation Group. $row['Value'] .MySQL Extension (mysql) Example 1.53. $status = explode(' '. See Also mysql_get_server_info mysql_list_processes 1.595 Example 1. 'mysql_password'). $link).. 'mysql_password'). 'mysql_user'.46. 'mysql_user'. • mysql_tablename 57 . ' = ' . } ?> The above example will output something similar to: 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/ . print_r($status).4. $result = mysql_query('SHOW STATUS'. while ($row = mysql_fetch_assoc($result)) { echo $row['Variable_name'] . ?> The above example will output something similar to: Array ( [0] [1] [2] [3] [4] [5] [6] [7] ) => => => => => => => => Uptime: 5380 Threads: 2 Questions: 1321299 Slow queries: 0 Opens: 26 Flush tables: 1 Open tables: 17 Queries per second avg: 245.. "\n".52.

?> Notes Note The mysql_num_rows function may be used to determine the number of tables in the result pointer. mysql_tablename example <?php mysql_connect("localhost". Use the mysql_tablename function to traverse this result pointer. The integer index (row/table number) The name of the table on success or FALSE on failure. mysql_thread_id Copyright 1997-2012 the PHP Documentation Group. mysql_tablename($result. 58 . "mysql_user". "\n". $i < $num_rows. or any function for result tables. $result = mysql_list_tables("mydb").47. $i). } mysql_free_result($result).4. for ($i = 0.54. Examples Example 1. such as mysql_fetch_array. $num_rows = mysql_num_rows($result). Retrieves the table name from a result. See Also mysql_list_tables mysql_field_table mysql_db_name 1. It is preferable to use mysql_query to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. Parameters result i Return Values A result pointer resource that's returned from mysql_list_tables.MySQL Extension (mysql) Get table name of field Description string mysql_tablename(resource result. "mysql_password"). This function is deprecated. int i). $i++) { echo "Table: ".

an E_WARNING level error is generated. Return Values The thread ID on success or FALSE on failure. and a reconnect with mysql_ping is executed. If the connection is lost.4. mysql_thread_id example <?php $link = mysql_connect('localhost'. it will try to create one as if mysql_connect was called with no arguments. the thread ID will change. if ($thread_id){ printf("current thread id is %d\n".48. Description 59 . $thread_id). Retrieves the current thread ID. } ?> The above example will output something similar to: current thread id is 73 See Also mysql_ping mysql_list_processes 1. • mysql_unbuffered_query Send an SQL query to MySQL without fetching and buffering the result rows.MySQL Extension (mysql) • mysql_thread_id Return the current thread ID Description int mysql_thread_id(resource link_identifier). 'mysql_user'. If no such link is found. This means only retrieve the thread ID when needed. If the link identifier is not specified. Parameters link_identifier The MySQL connection. the last link opened by mysql_connect is assumed. If no connection is found or established.55. Examples Example 1. 'mysql_password'). $thread_id = mysql_thread_id($link). mysql_unbuffered_query Copyright 1997-2012 the PHP Documentation Group.

DELETE. Parameters query The SQL query to execute. If the link identifier is not specified. DESCRIBE or EXPLAIN statements. UPDATE. SHOW. resource link_identifier).MySQL Extension (mysql) resource mysql_unbuffered_query(string query. using the same link_identifier. See Also mysql_query 60 . an E_WARNING level error is generated. etc. you must specify the optional parameter link_identifier to identify which connection you want to use. Data inside the query should be properly escaped. If no such link is found. the last link opened by mysql_connect is assumed. 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. This saves a considerable amount of memory with SQL queries that produce large result sets. To use mysql_unbuffered_query while multiple database connections are open. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL. Return Values For SELECT. 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. DROP. mysql_unbuffered_query sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query does. until all rows are fetched. link_identifier The MySQL connection. mysql_unbuffered_query returns a resource on success. For other type of SQL statements. it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established. or FALSE on error.

The driver may also call a library. Sometimes people use the terms connector and driver interchangeably. or API. which allows it to interface with the MySQL server. By way of an example.1 and above.com/doc/.mysql.1. as it is more modern and leads to better organised code. the term connector refers to a piece of software that allows your application to connect to the MySQL database server. the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. Parts of this documentation included from MySQL manual with permissions of Oracle Corporation. What is a Driver? A driver is a piece of software designed to communicate with a specific type of database server. methods. such as the MySQL Client Library or the MySQL Native Driver.Chapter 2. functions and variables that your application will need to call in order to carry out its desired task. 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. possibly using other intermediate libraries where necessary. with the object-oriented API you instantiate classes and then call methods on the resulting objects. When writing PHP applications that need to connect to the MySQL server there are several API options available. These libraries implement the low-level protocol used to communicate with the MySQL database server.2. In the MySQL-related documentation the term “driver” is reserved for software that provides the database-specific part of a connector package. and also handle the communication between your application and the database server. What is a Connector? In the MySQL documentation. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions. All examples in the mysqli documentation use the world database. including PHP. The mysqli extension allows you to access the functionality provided by MySQL 4.sql. APIs can be procedural or object-oriented. Examples Copyright 1997-2012 the PHP Documentation Group. One of the drivers it has available is the PDO MYSQL driver. MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. The world database can be found at http://downloads. 2. this can be confusing.com/ An overview of software available for using MySQL from PHP can be found at Section 2.mysql. 61 . More information about the MySQL Database server can be found at http://www.com/docs/world.mysql. What is an API? An Application Programming Interface. Overview Copyright 1997-2012 the PHP Documentation Group. With a procedural API you call functions to carry out tasks. This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database. This software is known generically as a connector. Of the two the latter is usually the preferred interface. as it allows your application to connect to a database server. This document discusses what is available and how to select the best solution for your application.2.gz 2. Software is required to provide the API that your PHP application will use. MySQL provides connectors for a variety of languages. defines the classes. “Overview” Documentation for MySQL can be found at http://dev.

1. to allow its facilities to be used programmatically. and the mysql extension. see Chapter 1. What is PHP's mysqli Extension? The mysqli extension. The mysql extension source code is located in the PHP extension directory ext/mysql. PHP's MySQL-related extensions. The PDO MySQL driver extension. some extensions which use the PHP extension framework do not expose an API to the PHP programmer.3 and newer.1. Note If you are using MySQL versions 4. as an extension may not necessarily expose an API to the programmer. such as the mysqli extension.MySQL Improved Extension (Mysqli) What is an Extension? In the PHP documentation you will come across another term . The mysqli extension is included with PHP versions 5 and later. However.3 or newer.3. or as it is sometimes known. 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 mysqli extension has a number of benefits. The terms API and extension should not be taken to mean the same thing. but not all of the latest MySQL server features will be available.1. The PHP code consists of a core. MySQL Extension (mysql). For further information on the mysql extension.extension. 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. was developed to take advantage of new features found in MySQL systems versions 4. but provides an interface to the PDO layer above it.1. does not expose an API to the PHP programmer. the MySQL improved extension. The following discussion aims to give a brief introduction to the key aspects of each API. An extension typically exposes an API to the PHP programmer. are implemented using the PHP extension framework. with optional extensions to the core functionality.3 or later it is strongly recommended that you use the mysqli extension instead. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4. for example. This extension can be used with versions of MySQL 4. 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 .

net/book. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. For further information on the PDO MYSQL driver. is a database abstraction layer specifically for PHP applications. The programmer still calls the PDO API. as libmysql was originally designed with C applications in mind. The mysqli extension is built using the PHP extension framework. It does not expose an API to the PHP programmer. such as a clean. see Chapter 4. For further information on the mysqli extension. its source code is located in the directory ext/mysqli. see the http://www. It does not expose an API to the PHP programmer. What is PHP's MySQL Native Driver? In order to communicate with the MySQL database server the mysql extension. The PDO MYSQL driver is one of several available PDO drivers.3 or later it is strongly recommended that you use this extension. mysqli and the PDO MYSQL driver each use a lowlevel library that implements the required protocol. While PDO has its advantages.3 and later. and only need to make minor changes to your PHP code.1. In theory. otherwise known as libmysql. from say Firebird to MySQL.php. at least from the PHP programmer's perspective. For further information on PDO. What is the PDO MYSQL driver? The PDO MYSQL driver is not an API as such. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql. MySQL Functions (PDO_MYSQL) (MySQL (PDO)). its source code is located in the directory ext/pdo. The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/ pdo_mysql. but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server. In the past.MySQL Improved Extension (Mysqli) If you are using MySQL versions 4. However. or PDO. For example.1. was developed as an alternative to libmysql for PHP applications. PDO is implemented using the PHP extension framework. if you are using the PDO API. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. As well as the object-oriented interface the extension also provides a procedural interface. see Chapter 2. Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl. 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. the interface presented by libmysql was not optimized for communication with PHP applications. mysqlnd. The MySQL Native Driver is implemented using the PHP extension framework. You are strongly encouraged to take advantage of these improvements. the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd.pdo. The mysql extension. For this reason the MySQL Native Driver. the only available library was the MySQL Client Library. you could switch the database server you used. What is PDO? PHP Data Objects. MySQL Improved Extension (Mysqli). simple. PDO does not allow you to use MySQL's support for Multiple Statements. Other PDO drivers available include those for the Firebird and PostgreSQL database servers. portable API. The source code is located in ext/mysqlnd. Comparison of Features The following table compares the functionality of the three main methods of connecting to MySQL from PHP: 63 . Note The MySQL Native Driver can only be used with MySQL server versions 4.

Database concepts are explained to the degree needed for presenting MySQL specifics. echo $row['_msg']. ?> The above example will output: 64 . Some mysqli functions take a connection handle as their first argument. Familarity with the PHP programming language. $mysql). Quickstart Copyright 1997-2012 the PHP Documentation Group.preferred option Yes Yes No Prior to 3.3 Yes Yes Yes Yes Yes Most Most PHP's MySQL Extension PHP version introduced Included with PHP 5. $row = mysql_fetch_assoc($res). Dual procedural and object-oriented interface Copyright 1997-2012 the PHP Documentation Group. "SELECT 'Please. Users stepping up from the old mysql extension may prefer the procedural interface. 2.1. "user". In many cases function names differ only by prefix. ""). The quickstart gives an overview on the mysqli extension.0 yes Active development as of PHP 5.0 Yes Maintenance only No No No No No No No API supports Stored Procedures Yes Yes Supports all MySQL 4. This quickstart guide shall help choosing an PHP MYSQL API and help getting familiar with it. Code examples are given for all major aspects of the API.3. whereas matching functions in the old mysql interface take it as an optional last argument.0 yes Active development Yes .Yes tionality 2. Example 2. do not use ' AS _msg FROM DUAL"). $mysql = mysql_connect("localhost". Easy migration from the old mysql extension <?php $mysqli = mysqli_connect("example.MySQL Improved Extension (Mysqli) PHP's mysqli Extension PDO (Using PDO MySQL Driver and MySQL Native Driver) 5. mysql_select_db("test"). "password". It supports the procedural and object-oriented programming paradigma. echo $row['_msg']. The mysqli extension features a dual interface.3. $res = mysql_query("SELECT 'the mysql extension for new developments. $res = mysqli_query($mysqli.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 5.' AS _msg FROM DUAL". The procedural interface is similar to that of the mysql extension.com". "database"). the SQL language and basic knowledge of the MySQL server is assumed. $row = mysqli_fetch_assoc($res). "root".1+ func.1.

?> The above example will output: Possible but bad style. Bad coding style <?php $mysqli = new mysqli("example.3. There are no significant performance differences between the two interfaces.com". "password". ?> The above example will output: A world full of choices to please everybody. "database"). ") " .' AS _msg FROM DUAL"). "SELECT 'Possible but bad style. $res = $mysqli->query("SELECT 'choices to please everybody. $mysqli = new mysqli("example. $res = mysqli_query($mysqli. mysqli_connect_error(). Mixing styles It is possible to switch between styles at any time. $mysqli->connect_error. 65 . The documentation is organized using the object-oriented interface. "database"). The object oriented interface is used for the quickstart because the reference section is organized that way. $mysqli->errno . $mysqli->error. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . if (mysqli_connect_errno($mysqli)) echo "Failed to connect to MySQL: " . Users can base their choice on personal preference. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $row = $res->fetch_assoc(). The object-oriented interface In addition to the classical procedural interface. "user". $row = mysqli_fetch_assoc($res). if ($row = $res->fetch_assoc()) echo $row['_msg'].com".com". users can choose to use the object-oriented interface. "database"). making it easier to get started. "password". Example 2. $mysqli->connect_error.' AS _msg FROM DUAL"). $res = mysqli_query($mysqli. echo $row['_msg'].MySQL Improved Extension (Mysqli) Please. "SELECT 'A world full of ' AS _msg FROM DUAL"). "user". The reference section gives examples for both syntax variants.2. Example 2. do not use the mysql extension for new developments. echo $row['_msg']. "password". if (!$res) echo "Failed to run query: (" . Mixing both styles is not recommended for code clarity and coding style reasons. The object-oriented interface shows functions grouped by their purpose. Object-oriented and procedural interface <?php $mysqli = mysqli_connect("example. "user".

Setting defaults mysqli.0. If a parameter is not given the extension attempts to use defaults values set in the PHP configuration file.MySQL Improved Extension (Mysqli) See also mysqli::__construct mysqli::query mysqli_result::fetch_assoc $mysqli::connect_errno $mysqli::connect_error $mysqli::errno $mysqli::error The MySQLi Extension Function Summary 2. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . Special meaning of localhost <?php $mysqli = new mysqli("localhost". Unix domain sockets or Windows named pipes. echo $mysqli->host_info .27 mysqli.2.0. Example 2. 3306).3.0. $mysqli->connect_error. "password". it may default to library built-in values. "database").default_pw="" mysqli.sock The resulting parameter values are then passed to the client library used by the extension. 66 . ?> The above example will output: Localhost via UNIX socket 127. $mysqli->connect_errno .default_host=192.5. echo $mysqli->host_info . Example 2.0.1 via TCP/IP Connection parameter defaults Depending on the connection function used. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127. "password".default_port=3306 mysqli. The hostname localhost has a special meaning.1". Connections Copyright 1997-2012 the PHP Documentation Group. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . "\n". "user".0. "user". $mysqli->connect_errno . "\n".168.4. assorted parameters can be omitted. $mysqli->connect_error. Connections use TCP/IP. The MySQL server supports the use of different transport layers for connections. $mysqli = new mysqli("127.0. ") " .default_user=root mysqli. If the client library detects empty or unset parameters.default_socket=/tmp/mysql. ") " . It is bound to the use of Unix domain sockets.2. "database".1 instead.

a connection to the default socket on /tmp/mysql. A persistent connection is not. the mysqli extension implicitly calls mysqli_change_user to reset the state. the socket (here: pipe name) defaults to \\.max_persistent. Connection options Various connection options are available. No artefacts from previous usages are visible. port and default database can be found in the connection pool. For example. Every PHP process is using its own mysqli connection pool.MySQL Improved Extension (Mysqli) Built-in connection library defaults If the host value is unset or empty. if a connection to the same server using the same username. Therefore. Depending on the web server deployment model a PHP process may serve one or multiple requests. for example. On Windows systems the host name . But also. that the web server may spawn many PHP processes. The use of persistent connections can be enabled and disabled using the PHP directive mysqli. Reuse saves connection overhead. If socket is unset or empty and a Unix socket connection is requested. Both are valid optimization goals. the client library will default to a Unix socket connection on localhost. The persistent connection appears to the user as if it was just opened. unfinished transactions are not automatically rolled back. The mysqli_change_user function is an expensive operation. to set init commands which are executed upon connect or. In this case the socket parameter is interpreted as the pipes name. setting the requested options using mysqli_options and establishing the network connection with mysqli_real_connect.max_links. See also mysqli::__construct mysqli::init mysqli::options mysqli::real_connect mysqli::change_user $mysqli::host_info 67 . Please. the library will default to port 3306. is interpreted by the client library as an attempt to open a Windows named pipe based connection. password. which are a special kind of pooled connections. Instead it is put into a pool for later reuse. the safe behaviour has been made the default at the expense of maximum performance. For best performance. a pooled connection may be used by one or more scripts subsequently. This may be seen as an unwanted side-effect. For ease of use. port and default database is opened. On the contrary. Connection options must be set before a network connection is established. run your own benchmarks to measure the performance impact for your work load. Connection pooling The mysqli extension supports persistent database connections. password. the name persistent may be understood as a promise that the state is persisted. The default is reset. socket. Persistent connection If no unused persistent connection for a given combination of host. The mysqli extension supports both interpretations of a persistent connection: state persisted and state reset before reuse. open. The mysqlnd library and the MySQL Client Library (libmysql) implement the same logic for determining defaults.allow_persistent. The total number of connections opened by a script can be limited with mysqli. authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. For setting a connection option the connect operation has to be performed in three steps: creating a connection handle with mysqli_init. It is left to the user to choose between safe behaviour and best performance. If neither a Unix domain socket based not a Windows named pipe based connection is to be bestablished and the port parameter value is unset. A common complain about persistent connections is that their state is not reset before reuse. If not given or empty. Before a persistent connection is reused.sock is attempted.\pipe\MySQL. socket. Please note. username. mysqli opens a new connection. By default every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. for requesting use of a certain charset. The maximum number of persistent connections per PHP process can be restricted with mysqli. users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.

.\n". "database").. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1)")) echo "Table creation failed: (" . $res->data_seek(0). $mysqli->error. (2). ?> The above example will output: Reverse order. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . keep in mind that it is often easier to scale by client than it is to scale the server. Nagivation is fast because the result sets is hold in client memory. $mysqli->connect_errno . ") " . $mysqli->connect_error. The mysqli_multi_query function is used with Multiple Statements and is described elsewhere. $mysqli->connect_error. (3)")) echo "Table creation failed: (" . id = 3 id = 2 68 .com".. echo " id = " . if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $res = $mysqli->query("SELECT id FROM test ORDER BY id ASC"). Example 2. PHP applications can navigate freely through buffered results. Please. It combines executing statement and doing a buffered fetch of its result set. $row['id'] . Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. $mysqli->error. Executing statements Copyright 1997-2012 the PHP Documentation Group. Therefore.7. $row = $res->fetch_assoc(). "password".6. $mysqli->connect_errno .1. in one call. mysqli_query combines statement execution and result set buffering. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1). mysqli_real_query and mysqli_multi_query function. "\n". Generally speaking.com". $row['id'] . Bad coding style <?php $mysqli = new mysqli("example. for ($row_no = $res->num_rows . Statements can be executed by help of the mysqli_query. while ($row = $res->fetch_assoc()) echo " id = " . Calling mysqli_query is identical to calling mysqli_real_query followed by mysqli_store_result. "database"). The mysqli_query function is the most commonly used one. ") " .MySQL Improved Extension (Mysqli) MySQLi Configuration Options Persistent Database Connections 2.. $mysqli->errno . Navigation through buffered results <?php $mysqli = new mysqli("example.. $row_no >= 0. it is recommended to use buffered result sets. } echo "Result set order.. if any. "\n". ") " .3. ") " . "user". echo "Reverse order.\n". Example 2. "password". "user". clients are slow consuming result sets. $row_no--) { $res->data_seek($row_no).3. $mysqli->errno . ?> Buffered result sets After statement execution results can be retrieved at once to be buffered by the client or by read row by row.

$mysqli->errno . This way. $mysqli->connect_errno . $res = $mysqli->query("SELECT id. With the text protocol. "\n". Example 2. This conversion is done regardless of the SQL result set column data type. echo "Result set order. printf("label = %s (%s)\n".. $mysqli->error. $mysqli->connect_error.MySQL Improved Extension (Mysqli) id = 1 Result set order.8. Scrolling through unbuffered results is not possible before all rows have been read. the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers. 69 . 'a')")) echo "Table creation failed: (" . Navigation through buffered results <?php $mysqli->real_query("SELECT id FROM test ORDER BY id ASC"). $res = $mysqli->use_result(). ") " . Text protocol returns strings by default <?php $mysqli = new mysqli("example. label) VALUES (1. "password". At the level of the MySQL Client Server Protocol the command COM_QUERY and the text protocol are used for statement execution. unbuffered results can be used. No further client-side casting is done to convert columns back to their native types. ?> The above example will output: id = 1 (string) label = a (string) It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option. gettype($row['label'])). If set. ") " . $row = $res->fetch_assoc(). ?> Result set values data types The mysqli_query. $row['id']. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. Instead. all values are provided as PHP strings. Example 2.9. $row['label']. the MySQL server converts all data of a result sets into strings before sending. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . "database"). for example.com". if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. gettype($row['id'])). if using the mysqlnd libary. The mysql client libraries receive all column values as strings. printf("id = %s (%s)\n". SQL INT columns are returned as integers. id = 1 id = 2 id = 3 Unbuffered result sets If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed. $row['id'] ... if the PHP data type value range allows for it. mysqli_real_query and mysqli_multi_query functions are used to execute non-prepared statements. while ($row = $res->fetch_assoc()) echo " id = " .\n". label FROM test WHERE id = 1").. "user".

$row = $res->fetch_assoc(). printf("label = %s (%s)\n". $row['label']. Native data types with mysqlnd and connection option <?php $mysqli = mysqli_init(). "password". label FROM test WHERE id = 1"). "user". ") " . positional placeholder with ?. /* Non-prepared statement */ if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) echo "Table creation failed: (" . First stage: prepare <?php $mysqli = new mysqli("example. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . The MySQL server supports using anonymous. $mysqli->errno . "database"). $mysqli->errno . Prepared Statements Copyright 1997-2012 the PHP Documentation Group. Example 2.4. The server performs a syntax check and initializes server internal resources for later use. "database"). $mysqli->error. gettype($row['label'])). ") " . if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . Basic workflow The prepared statement execution consists of two stages: prepare and execute. printf("id = %s (%s)\n". 70 . $mysqli->connect_error. $row['id']. ") " .MySQL Improved Extension (Mysqli) Example 2. The MySQL database supports prepared statements.3. $mysqli->connect_errno . $mysqli->connect_error. $mysqli->error.11. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id.10. $res = $mysqli->query("SELECT id. At the prepare stage a statement template is send to the database server.com". "password". gettype($row['id'])). $mysqli->connect_errno . $mysqli->real_connect("example. $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE. "user". label) VALUES (1. 1). ") " . ?> The above example will output: id = 1 (integer) label = a (string) See also mysqli::__construct mysqli::init mysqli::options mysqli::real_connect mysqli::query mysqli::multi_query mysqli::use_result mysqli::store_result mysqli_result::free 2.com". A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. 'a')")) echo "Table creation failed: (" .

?> Repeated execution A prepared statement can be executed repeatedly. $stmt->error. $mysqli->errno . stage 2: bind and execute */ $id = 1. $stmt->errno . $stmt->error. Example 2. $mysqli->connect_error. $mysqli->connect_errno .com". "database"). "password". if (!$stmt->execute()) echo "Execute failed: (" . $stmt->errno . During execute the client binds parameter values and sends them to the server. $id)) echo "Binding parameters failed: (" . $stmt->errno . stage 2: bind and execute */ $id = 1. /* Prepared statement: repeated execution.13. /* Prepared statement. ") " . /* explicit close recommended */ $stmt->close(). if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . /* Non-prepared statement */ $res = $mysqli->query("SELECT id FROM test"). /* Prepared statement. $stmt->errno . Upon every execution the current value of the bound variable is evaluated and send to the server. stage 1: prepare */ if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) echo "Prepare failed: (" . stage 1: prepare */ if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) echo "Prepare failed: (" . /* Non-prepared statement */ if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) echo "Table creation failed: (" . INSERT prepared once. if (!$stmt->execute()) echo "Execute failed: (" . $mysqli->error. var_dump($res->fetch_all()). if (!$stmt->bind_param("i". $id++) if (!$stmt->execute()) echo "Execute failed: (" . The statement template is not transferred to the server again. ") " . The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources. ") " . ?> Prepare is followed by execute. if (!$stmt->bind_param("i". only data transferred from client to server */ for ($id = 2. $id)) echo "Binding parameters failed: (" . ") " . $stmt->error. $stmt->error. $id < 5. $mysqli->error. Second stage: bind and execute <?php /* Prepared statement.MySQL Improved Extension (Mysqli) /* Prepared statement. ?> The above example will output: array(4) { [0]=> array(1) { [0]=> string(1) "1" } [1]=> 71 . The statement is not parsed again. $mysqli->errno . Example 2. $mysqli->error. executed multiple times <?php $mysqli = new mysqli("example.12. ") " . ") " . "user". ") " . ") " . ") " . $mysqli->errno . $stmt->error. $stmt->errno .

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. ") " . Also. printf("label = %s (%s)\n". Results are not serialized into strings before sending. Example 2. $mysqli->error. ?> Result set values data types The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. (3). $mysqli->errno . Less round trips using multi-INSERT SQL <?php if (!$mysqli->query("INSERT INTO test(id) VALUES (1). results from an SQL INT column will be provided as PHP integer variables. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. This is why the SELECT is not run as a prepared statement above. For the example. $stmt->execute(). Example 2. If not done explicitly. consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. The client libraries do not receive strings only. (2). gettype($row['id'])). label FROM test WHERE id = 1").15. $row['label']. The MySQL server sends result set data "as is" in binary format.14. ") " . ?> The above example will output: 72 . $mysqli->connect_error. $row = $res->fetch_assoc(). Prepared statements are using the so called binary protocol.com". the statement will be closed when the statement handle is freed by PHP. $mysqli->connect_errno . if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $stmt = $mysqli->prepare("SELECT id. they will receive binary data and try to convert the values into appropriate PHP data types. belows multi-INSERT requires less round-trips between the server and client than the prepared statement shown above. $mysqli->error. 'a')")) echo "Table creation failed: (" . $mysqli->errno . A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. label) VALUES (1. Using a prepared statement is not always the most efficient way of executing a statement. $res = $stmt->get_result(). ") " . Native datatypes <?php $mysqli = new mysqli("example.MySQL Improved Extension (Mysqli) array(1) { [0]=> string(1) "2" } [2]=> array(1) { [0]=> string(1) "3" } [3]=> array(1) { [0]=> string(1) "4" } } Every prepared statement occupies server resources. $row['id']. "database"). "password". Instead. For example. "user". printf("id = %s (%s)\n". Statements should be closed explicitly immediately after use. gettype($row['label'])). (4)")) echo "Multi-INSERT failed: (" .

$mysqli->errno . results can also be retrieved through the mysqli_result interface. ?> The above example will output: id = 1 (integer). 'a')")) echo "Table creation failed: (" . Example 2. $mysqli->error. if (!$stmt->execute()) echo "Execute failed: (" . "user". One variable must be bound for every column of the statements result set. $out_label = NULL. label = a (string) Prepared statements return unbuffered result sets by default. "password". $stmt->errno . "user". there are no differences. $mysqli->connect_errno . By default. Using mysqli_result to fetch results <?php $mysqli = new mysqli("example. Thus it is recommended to consume results timely. It is also possible to buffer the results of a prepared statement using mysqli_stmt_store_result.16. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. non-prepared statements return all results as strings. ") " . if (!($stmt = $mysqli->prepare("SELECT id. $out_id. The result set takes server resources until all results have been fetched by the client. "password". $mysqli->error. $mysqli->connect_error. "database").com". $mysqli->errno . $mysqli->connect_errno . ") " . if (!$stmt->bind_result($out_id. $mysqli->errno . gettype($out_id). ") " . label = %s (%s)\n". label FROM test"))) echo "Prepare failed: (" . Fetching results using mysqli_result interface Instead of using bound results. If a client fails to fetch all results or the client closes the statement before having fetched all data. gettype($out_label)).com". if (!$mysqli->query("DROP TABLE IF EXISTS test") || 73 . $out_label. $mysqli->error. "database"). ") " . Output variable binding <?php $mysqli = new mysqli("example. $out_id = NULL.MySQL Improved Extension (Mysqli) id = 1 (integer) label = a (string) This behaviour differes from non-prepared statements. If the connection option is used. $stmt->error. This default can be changed using a connection option. $out_label)) echo "Binding output parameters failed: (" .17. ") " . the data has to be fetched implicitly by mysqli. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . mysqli_stmt_get_result returns a buffered result set. ") " . label) VALUES (1. while ($stmt->fetch()) printf("id = %s (%s). Output variables must be bound after statement execution. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. $mysqli->connect_error. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. Fetching results using bound variables Results from prepared statements can either be retrieved by binding output variables or by requesting a mysqli_result object. Example 2.

$mysqli->error. (2. Example 2. label FROM test"))) echo "Prepare failed: (" . ?> The above example will output: array(2) { ["id"]=> int(3) ["label"]=> string(1) "c" } array(2) { ["id"]=> int(2) ["label"]=> string(1) "b" } array(2) { ["id"]=> int(1) ["label"]=> string(1) "a" } 74 . $stmt->errno . $stmt->errno . label) VALUES (1. if (!$stmt->execute()) echo "Execute failed: (" . if (!($res = $stmt->get_result())) echo "Getting result set failed: (" .com". $stmt->errno . ") " . 'c')")) echo "Table creation failed: (" . $row_no--) { $res->data_seek($row_no). label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. "user". "password". $stmt->error.18. ") " . ") " . $mysqli->errno . Buffered result set for flexible read out <?php $mysqli = new mysqli("example. 'a'). 'b'). } $res->close().1). ?> The above example will output: array(1) { [0]=> array(2) { [0]=> int(1) [1]=> string(1) "a" } } Using the mysqli_result interface this has the additional benefit of flexible client-side result set navigation. $stmt->error. (3. $mysqli->errno . $mysqli->error. $mysqli->error. $mysqli->errno . ") " . $stmt->error. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . 'a')")) echo "Table creation failed: (" . if (!$stmt->execute()) echo "Execute failed: (" . $mysqli->connect_error. var_dump($res->fetch_all()). var_dump($res->fetch_assoc()). $stmt->errno . "database"). ") " . $mysqli->errno .MySQL Improved Extension (Mysqli) !$mysqli->query("CREATE TABLE test(id INT. label FROM test ORDER BY id ASC"))) echo "Prepare failed: (" . for ($row_no = ($res->num_rows . $mysqli->connect_errno . label) VALUES (1. ") " . $row_no >= 0. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. ") " . $stmt->error. ") " . if (!($stmt = $mysqli->prepare("SELECT id. if (!($stmt = $mysqli->prepare("SELECT id. ") " . label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. $mysqli->error. if (!($res = $stmt->get_result())) echo "Getting result set failed: (" .

manual input escaping no yes yes. Client-side prepared statement emulation The API does not include a client-side prepared statement emulation. use mysqli_stmt_get_result yes. Prepared Statement Client-server round trips. Users must hint the server about the type of the bound variable for appropriate conversion.non-prepared statement comparison The below table gives a quick comparison on server-side prepared and non-prepared statements. Stored Procedures 75 . SELECT. if input values are escaped correctly. if any n times together with parameter. see mysqli_stmt_bind_param. single execution Statement string transferred from client to server Client-server round trips. if any yes. use mysqli_real_query with mysqli_use_result text protocol converted to string or preserved when fetching yes See also mysqli::__construct mysqli::query mysqli::prepare mysqli_stmt::prepare mysqli_stmt::execute mysqli_stmt::bind_param mysqli_stmt::bind_result 2. default of mysqli_query Unbuffered result sets MySQL Client Server protocol data transfer flavour Result set values SQL data types Supports all SQL statements yes. use mysqli_stmt_get_result() or binding with mysqli_stmt_store_result yes.3. automatic input escaping yes yes. Quick prepared .5. n times bound parameter. use output binding API binary protocol preserved when fetching Recent MySQL versions support most but not all no. The same degree of security can be achieved with non-prepared statements.MySQL Improved Extension (Mysqli) Escaping and SQL injection Bound variables will be escaped automatically by the server. The automatic escaping of values within the server is sometimes considered as a security feature to prevent SQL injection. SELECT. repeated (n) execution Statement string transferred from client to server Input parameter binding API Output variable binding API Supports use of mysqli_result API Buffered result sets 2 1 1+n Non-prepared statement 1 1 n 1 template. The server inserts their escaped values at the appropriate places into the statement template before execution.

')) echo "Stored procedure creation failed: (" . $mysqli->error. if (!$mysqli->query("CALL p(1)")) echo "CALL failed: (" . $mysqli->errno . $mysqli->errno . if (!($res = $mysqli->query("SELECT @msg as _p_out"))) echo "Fetch failed: (" . Example 2. ") " . ") " . ") " . $mysqli->error. ") " . var_dump($res->fetch_assoc()). ") " . $mysqli->connect_errno . "password".19. END. $mysqli->error. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $mysqli->error. if (!($res = $mysqli->query("SELECT id FROM test"))) echo "SELECT failed: (" . ") " . The CALL SQL statement is used to execute a stored procedure.")) echo "Stored procedure creation failed: (" . if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) echo "Table creation failed: (" .com". if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . Example 2. $mysqli->error. $row = $res->fetch_assoc(). depending on the MySQL version. END. Parameter Stored procedures can have IN. $mysqli->error. ?> 76 . $mysqli->errno . Using session variables <?php $mysqli = new mysqli("example. IN parameter Input parameters are provided with the CALL statement. Please. "password".20. "user". make sure values are escaped correctly. ?> The above example will output: array(1) { ["id"]=> string(1) "1" } INOUT/OUT parameter The values of INOUT/OUT parameters are accessed using session variables.MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) echo "CALL failed: (" . Applications can call and execute the stored procedure. "database"). echo $row['_p_out']. $mysqli->errno . "user". $mysqli->connect_error. ") " . $mysqli->errno . The mysqli interface has no special notion for the different kinds of parameters. $mysqli->error. $mysqli->connect_error. $mysqli->errno . ") " .com". $mysqli->errno . INOUT and OUT parameters. if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg. if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val). "database"). The MySQL database supports stored procedures. Calling a stored procedure <?php $mysqli = new mysqli("example. A stored procedure is a subroutine stored in the database catalog.

END. ") " . if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1). ?> The above example will output: --array(3) { [0]=> array(1) { [0]=> string(1) "1" } [1]=> array(1) { [0]=> string(1) "2" } [2]=> array(1) { [0]=> string(1) "3" } } --array(3) { [0]=> array(1) { 77 . $mysqli->connect_error. var_dump($res->fetch_all()). $mysqli->error. The mysqli_query function combines statement execution and fetching the first result set into a buffered result set. $mysqli->errno . (2). if (!$mysqli->multi_query("CALL p()")) echo "CALL failed: (" . please note the possible performance impact of a custom solution based on catalog inspection.com". Example 2. if any. } } while ($mysqli->more_results() && $mysqli->next_result()).MySQL Improved Extension (Mysqli) The above example will output: Hi! Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. } else { if ($mysqli->errno) echo "Store failed: (" . (3)")) echo "Table creation failed: (" . $mysqli->errno . if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . "password". $mysqli->connect_errno . $mysqli->error. $mysqli->errno . Fetching results from stored procedures <?php $mysqli = new mysqli("example. Failing to fetch all result sets returned by a stored procedure causes an error. SELECT id + 1 FROM test. ") " . $mysqli->errno . ") " . there are additional stored procedure result sets hidden from the user which cause mysqli_query to fail returning the user expected result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query. Handling result sets Stored procedures can return result sets. do { if ($res = $mysqli->store_result()) { printf("---\n"). However.')) echo "Stored procedure creation failed: (" . $res->free(). $mysqli->error. However. $mysqli->error. if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test. Result sets returned from a stored procedure are fetched using mysqli_real_query or mysqli_multi_query. ") " . ") " .21. "database"). such as CALL. "user". Both functions allow fetching any number of result sets returned by a statement.

") " . $stmt->errno . ") " . $stmt->errno . (2). ") " . } while ($stmt->more_results() && $stmt->next_result()). "password". if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $mysqli->errno . do { if ($res = $stmt->get_result()) { printf("---\n"). if (!$stmt->execute()) echo "Execute failed: (" . $mysqli->connect_error. do { $id_out = NULL. that not every MYSQL server version may support preparing the CALL SQL statement. $mysqli->error. Example 2. SELECT id + 1 FROM test. $mysqli->error. Please note. if (!$stmt->bind_result($id_out)) echo "Bind failed: (" . if (!$stmt->execute()) echo "Execute failed: (" . Stored Procedures and Prepared Statements using bind API <?php if (!($stmt = $mysqli->prepare("CALL p()"))) echo "Prepare failed: (" . ?> Of course. ") " . mysqli_free_result($res). $stmt->errno . "user". } } while ($stmt->more_results() && $stmt->next_result()). $mysqli->errno . $mysqli->error. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1). if (!($stmt = $mysqli->prepare("CALL p()"))) echo "Prepare failed: (" . $stmt->errno . use of the bind API for fetching is supported as well. The prepared statement and non-prepared statement interfaces are similar. ") " . Example 2.22. var_dump(mysqli_fetch_all($res)). ") " . $stmt->error.MySQL Improved Extension (Mysqli) [0]=> string(1) "2" } [1]=> array(1) { [0]=> string(1) "3" } [2]=> array(1) { [0]=> string(1) "4" } } Use of prepared statements No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. Stored Procedures and Prepared Statements <?php $mysqli = new mysqli("example. while ($stmt->fetch()) echo "id = $id_out\n". $mysqli->error. if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test.23. ") " . } else { if ($stmt->errno) echo "Store failed: (" . END.')) echo "Stored procedure creation failed: (" .com". "database"). $mysqli->errno . (3)")) echo "Table creation failed: (" . $stmt->error. ") " . ?> 78 . $mysqli->connect_errno . $stmt->error. $stmt->error. $mysqli->errno . ") " .

"password". $mysqli->errno . Then. ") " . if (!$mysqli->multi_query($sql)) echo "Multi query failed: (" . Example 2. } } while ($mysqli->more_results() && $mysqli->next_result()). Multiple statements or multi queries must be executed with mysqli_multi_query.3.= "INSERT INTO test(id) VALUES (1). $sql = "SELECT COUNT(*) AS _num FROM test. $sql. $mysqli->connect_error. Multiple Statements <?php $mysqli = new mysqli("example.= "SELECT COUNT(*) AS _num FROM test. ". Sending multiple statements at once reduces client-server round trips but requires special handling.com".24. if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" .MySQL Improved Extension (Mysqli) See also mysqli::query mysqli::multi_query mysqli_result::next-result mysqli_result::more-results 2. $mysqli->errno . Multiple Statements Copyright 1997-2012 the PHP Documentation Group. if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) echo "Table creation failed: (" . ?> The above example will output: array(1) { [0]=> array(1) { ["_num"]=> string(1) "0" } } array(1) { [0]=> array(1) { ["_num"]=> string(1) "1" } } Security considerations 79 . MySQL optionally allows having multiple statements in one statement string. ") " . "user". $mysqli->error. $mysqli->connect_errno . do { if ($res = $mysqli->store_result()) { var_dump($res->fetch_all(MYSQLI_ASSOC)). $res->free(). ". ") " . The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement. all result sets returned by the executed statements must be fetched.6. The individual statements of the statement string are seperated by semicolon. $sql. "database"). $mysqli->error. ".

DROP DATABASE mysql or . /* Recommended: using API to control transactional settings */ $mysqli->autocommit(false). ?> Optional feature packages.25. can easily monitor API calls. SELECT SLEEP(999). SQL ijnection <?php $mysqli = new mysqli("example. It is recommended to use API calls for enabling and disabling the auto commit mode and for comitting and rolling back transactions. ") " . DROP TABLE mysql.com". "database"). check the manual that corresponds to your MySQL server Prepared statements Use of the multiple statement with prepared statements is not supported. such as the replication and load balancing plugin. InnoDB has full ACID transaction support. "user". If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used. $res = $mysqli->query("SELECT 1. Example 2. The MySQL server supports transactions depending on the storage engine used.y[TODO] the default storage engine is InnoDB. ") " .26. Example 2. "user".3. $mysqli->error. $mysqli->errno . if (!$res) echo "Error executing query: (" .MySQL Improved Extension (Mysqli) The API functions mysqli_query and mysqli_real_query do not set a connection flag necessary for activating multi queries in the server. "password". ") " . The replication plugin offers 80 . if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ?> The above example will output: Error executing query: (1064) You have an error in your SQL syntax. /* Won't be monitored and recognized by the replication and the load balancing plugin */ if (!$mysqli->query('SET AUTOCOMMIT = 0')) echo "Query failed: (" .com". Setting auto commit mode with SQL and through the API <?php $mysqli = new mysqli("example. injected and malicious SQL statement. the server will not execute the second. API support for transactions Copyright 1997-2012 the PHP Documentation Group. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks.user"). See also mysqli::query mysqli::multi_query mysqli_result::next-result mysqli_result::more-results 2. Transactions can either be controlled using SQL or API calls. $mysqli->error. $mysqli->errno . An attacker may try to add statements such as . $mysqli->connect_error. Since MySQL [TODO]x. "password". "database").7.

if ($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . See also mysqli::autocommit mysqli_result::commit mysqli_result::rollback 2. Meta data is access through the mysqli_result interface. $mysqli->query("INSERT INTO test(id) VALUES (2)"). "database").8. "password". $mysqli->connect_error. $mysqli->query("INSERT INTO test(id) VALUES (1)"). committing or rolling back a transaction.3.MySQL Improved Extension (Mysqli) transaction aware load balancing. "user". ?> The above example will output: array(2) { [0]=> object(stdClass)#3 (13) { ["name"]=> string(4) "_one" ["orgname"]=> string(0) "" ["table"]=> string(0) "" ["orgtable"]=> string(0) "" ["def"]=> string(0) "" ["db"]=> string(0) "" ["catalog"]=> string(3) "def" 81 . $res = $mysqli->query("SELECT 1 AS _one. Example 2. if transactions are controlled with API calls. $mysqli->commit(). Metadata Copyright 1997-2012 the PHP Documentation Group. Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode. All metadata send by MySQL is accessible through the mysqli interface. Some statements cause am implicit commit.com". Differences between MySQL server versions are not aligned. Commit and rollback <?php $mysqli = new mysqli("example.27.com". $mysqli->autocommit(false). "password". Accessing result set meta data <?php $mysqli = new mysqli("example. ") " . The metadata describes the columns found in the result set.28. that the MySQL server cannot roll back all statements. "user". "database"). 'Hello' AS _two FROM DUAL"). ?> Please note. var_dump($res->fetch_fields()). The extension performs no or negliable changes to the information it receives. A MySQL result set contains metadata. Example 2. $mysqli->rollback(). $mysqli->connect_errno .

Example 2.MySQL Improved Extension (Mysqli) ["max_length"]=> int(1) ["length"]=> int(1) ["charsetnr"]=> int(63) ["flags"]=> int(32897) ["type"]=> int(8) ["decimals"]=> int(0) } [1]=> object(stdClass)#4 (13) { ["name"]=> string(4) "_two" ["orgname"]=> string(0) "" ["table"]=> string(0) "" ["orgtable"]=> string(0) "" ["def"]=> string(0) "" ["db"]=> string(0) "" ["catalog"]=> string(3) "def" ["max_length"]=> int(5) ["length"]=> int(5) ["charsetnr"]=> int(8) ["flags"]=> int(1) ["type"]=> int(253) ["decimals"]=> int(31) } } Prepared statements Meta data of result sets created using prepared statements are accessed the same way. ?> See also mysqli::query mysqli_result::fetch_fields 2. 82 . $res = $stmt->result_metadata().4. A suitable mysqli_result handle is returned by mysqli_stmt_result_metadata. 'Hello' AS _two FROM DUAL"). Prepared statements metadata <?php $stmt = $mysqli->prepare("SELECT 1 AS _one. $stmt->execute().29. var_dump($res->fetch_fields()). Installing/Configuring Copyright 1997-2012 the PHP Documentation Group.

5.1. it is possible to enable the MySQL extension to use the MySQL Client Library (libmysql).2.x Default libmysql Configure Options: mysqlnd Not Available Configure Options: libmysql withmysqli=/path/to/m ysql_config mysqlnd is now supported withmysqli=/path/to/m ysql_config mysqlnd is now the default withmysqli=/path/to/m ysql_config Changelog 5. The common Unix distributions include binary versions of PHP that can be installed.MySQL Improved Extension (Mysqli) 2. The following example builds the MySQL extension to use the MySQL Client Library. Note The mysqli extension is designed to work with MySQL version 4. 5. The MySQL Native Driver was included in PHP version 5. Check the package manager than comes with your chosen distribution for availability.0.1.4.2. Installation Copyright 1997-2012 the PHP Documentation Group.4.3. Table 2. Building PHP from source allows you to specify the MySQL extensions you want to use. all permutations of extension and client library are possible. or 5.2.1. Installation on Linux Copyright 1997-2012 the PHP Documentation Group. 2. Refer to What is PHP's MySQL Native Driver? for a brief overview of the advantages of MySQL Native Driver.0.13 or newer.0. For previous versions.1. Requirements Copyright 1997-2012 the PHP Documentation Group.4. Although these binary versions are typically built with support for MySQL extensions enabled. as well as your choice of client library for each extension. and the mysqli and PDO MYSQL extensions to use the MySQL Native Driver: 83 . For example. while configuring the mysqli extension to use the MySQL Native Driver. The /path/to/mysql_config represents the location of the mysql_config program that comes with MySQL Server.x. you will need to build PHP from source code.4. Unless your Unix distribution comes with a binary package of PHP with the mysqli extension available. the extension libraries themselves may need to be installed using an additional package. please see the MySQL extension documentation.7 or newer.x libmysql withmysqli=mysqlnd --with-mysqli 5. The MySQL Native Driver is the recommended option. you must compile PHP with support for the mysqli extension. mysqli compile time support matrix PHP Version 5.x.3. However.0.0. 2.x mysqlnd Note that it is possible to freely mix MySQL extensions and client libraries.1. In order to have these functions available. The mysqli extension was introduced with PHP version 5. as it results in improved performance and gives access to features not available when using the MySQL Client Library.

Available since PHP 5.3.dll). so the php_mysqli.max_links mysqli.2. The mysqli extension is not enabled by default. Available since PHP 5.2. and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli. See also the Manual Windows Installation Instructions.2.dll.max_persistent mysqli. you need to make sure PHP can access the client library file. 2. Table 2.ini file (typically located in c:\php).2.3. for PHP versions 5.2. Installation on Windows Systems Copyright 1997-2012 the PHP Documentation Group. However. Copying libmysql. Available since PHP 5.0.0. 5. Available since PHP 5.2. this practice is strongly discouraged. some configuration is required to enable mysqli and specify the client library you want it to use.0./php_mysqli. in the section marked [PHP_MYSQLI]. On Windows. Available since PHP 5.0./configure --with-mysql=/usr/bin/mysql_config --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd [other options] \ 2. the mysqli extension is enabled and uses the MySQL Native Driver by default. so that it can be successfully loaded. MySQLi Configuration Options Name mysqli. As with enabling any PHP extension (such as php_mysqli.4. 2. Also.default_port mysqli.dll. this is because php_mysqli. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this.0. The MySQL Client Library is included as a file named libmysql.4. 5.allow_persistent mysqli.ini. Note If when starting the web server an error similar to the following occurs: "Unable to load dynamic library '.dll in the Windows PHP distribution.0.0.dll and/or libmysql. 84 . An example extension_dir value for PHP 5 is c:\php\ext.3. Once PHP has been installed. the PHP directive extension_dir should be set to the directory where the PHP extensions are located.dll to the Windows system directory (typically c:\Windows\system) also works. Runtime Configuration Copyright 1997-2012 the PHP Documentation Group.0. In order to do this you need to find the php.default_socket Default "1" "1" "-1" "-1" "3306" NULL Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL Changelog Available since PHP 5.1. as the system directory is by default in the system's PATH. The behaviour of these functions is affected by settings in php.1.2 Copyright 1997-2012 the PHP Documentation Group. if you want to use the MySQL Client Library with mysqli.0+ Copyright 1997-2012 the PHP Documentation Group. PHP 5.2.dll'". On Windows.0.MySQL Improved Extension (Mysqli) . PHP 5.dll cannot be found by the system. PHP is most commonly installed using the binary installer. This means you don't need to worry about configuring access to libmysql. This file needs to be available in the Windows system's PATH environment variable.4.3 and newer.4.2.allow_local_infile mysqli.4.2.dll DLL must be enabled inside of php.ini. 2.3.

default_pw string mysqli.5. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process.default_pw mysqli. Win32 will only use the MYSQL_PORT constant.cache_size 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.default_host string mysqli. Support was already present in PDO MYSQL and ext/mysql.default_user mysqli.0. The default socket name to use when connecting to a local database server if no other socket name is specified.allow_persistent integer mysqli. Automatically reconnect if the connection was lost.default_host mysqli. Available since PHP 5. mysqli does not provide a separate function for opening persistent connections. Doesn't apply in safe mode. The default password to use when connecting to the database server if no other password is specified.max_links integer mysqli. the port will be obtained from the MYSQL_TCP_PORT environment variable. For further details and definitions of the preceding PHP_INI_* constants.5. Doesn't apply in safe mode. The mysqli Extension and Persistent Connections Copyright 1997-2012 the PHP Documentation Group.default_socket string mysqli. Persistent connection support was introduced in PHP 5. mysqli.MySQL Improved Extension (Mysqli) Name mysqli. The default user name to use when connecting to the database server if no other name is specified.0.0. in that order.default_user string mysqli.0.4. Set to 0 for unlimited. as unused connections are cached and ready to be reused.3 for the mysqli extension. To open a persistent con85 .3.max_persistent integer mysqli. 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. mysqli. The default server host to use when connecting to the database server if no other host is specified.3. see the chapter on configuration changes. Available since PHP 4. Available since PHP 5. local files with LOAD DATA statements Enable the ability to create persistent connections using mysqli_connect. 2. 2.0.0.default_port integer Allow accessing. This reduces the overhead of creating fresh connections every time one is required.0.reconnect mysqli. Unlike the mysql extension. Resource Types Copyright 1997-2012 the PHP Documentation Group. rather than being created and destroyed multiple times. If no default is specified.reconnect integer mysqli. Available only with mysqlnd. Available since PHP 5. from PHP's perspective. Here's a short explanation of the configuration directives. This extension has no resource types defined.cache_size Default NULL NULL NULL "0" "2000" Changeable PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_SYSTEM PHP_INI_SYSTEM Changelog Available since PHP 5. Maximum of persistent connections that can be made. the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant. Doesn't apply in safe mode.allow_local_infil e integer mysqli.4.

The advantage is that the programmer no longer needs to worry about adding cleanup code. a table lock might be activated before a client terminates unexpectedly. The constants below are defined by this extension. It is possible to switch off the automatic cleanup code. as the code to perform the cleanup needs to run each time a connection is returned from the connection pool. as it is called automatically. Note The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library. Will automatically be re-executed when reconnecting.cnf MYSQLI_OPT_CONNECT_TIMEO Connect timeout in seconds UT MYSQLI_OPT_LOCAL_INFILE Enables command LOAD LOCAL INFILE MYSQLI_INIT_COMMAND MYSQLI_CLIENT_SSL MYSQLI_CLIENT_COMPRESS Command to execute when connecting to MySQL server. and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.cnf or the file specified with P MYSQLI_READ_DEFAULT_FILE MYSQLI_READ_DEFAULT_FILE Read options from the named option file instead of from my. MYSQLI_READ_DEFAULT_GROU Read options from the named group from my.6. The persistent connection of the mysqli extension however provides built-in cleanup handling code. The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user(). For example. The automatic cleanup feature has advantages and disadvantages though. increasing the burden on the programmer. A new client process reusing this persistent connection will get the connection “as is”. by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined. However. Predefined Constants Copyright 1997-2012 the PHP Documentation Group. Use SSL (encrypted protocol).MySQL Improved Extension (Mysqli) nection you must prepend p: to the hostname when connecting. The problem with persistent connections is that they can be left in unpredictable states by clients. the disadvantage is that the code could potentially be a little slower. This option should not be set by application programs. Any cleanup would need to be done by the new client process before it could make good use of the persistent connection. The cleanup carried out by mysqli includes: • • • • • • • Rollback active transactions Close and drop temporary tables Unlock tables Reset session variables Close prepared statements (always happens with PHP) Close handler Release locks acquired with GET_LOCK This ensures that persistent connections are in a clean state on return from the connection pool. 2. it is set internally in the MySQL client library Use compression protocol 86 . before the client process uses them.

CE MYSQLI_CLIENT_NO_SCHEMA Don't allow the db_name. Makes all functions names reserved words. MYSQLI_CLIENT_IGNORE_SPA Allow spaces after function names. MYSQLI_CLIENT_MULTI_QUER Allows multiple semicolon-delimited queries in a single mysqli_query call.3 and up) Field is defined as BIT (MySQL 5. Columns are returned into the array having an enumerated index.col_name syntax.0. Indicates that a field is defined as NOT NULL Field is part of a primary index Field is part of a unique index. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable. 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 both a numerical index and the fieldname as the associative index.tbl_name.MySQL Improved Extension (Mysqli) MYSQLI_CLIENT_INTERACTIV Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity E before closing the connection.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 87 .0. 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 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 Field is defined as SET Field is defined as NUMERIC 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.

Turns reporting off.1. Throw a mysqli_sql_exception for errors instead of warnings.5. Available since PHP 5. 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_REPORT_INDEX Report if no index or bad index was used in a query.0. Set all options on (report all).0. MYSQLI_DEBUG_TRACE_ENABL Is set to 1 if mysqli_debug functionality is enabled.MySQL Improved Extension (Mysqli) 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 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.3. NDEX_USED 88 .0 and MySQL 5. MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT MYSQLI_REPORT_ALL MYSQLI_REPORT_OFF Report errors from mysqli function calls. ED MYSQLI_SERVER_QUERY_NO_G MYSQLI_SERVER_QUERY_NO_I OOD_INDEX_USED MYSQLI_REFRESH_GRANT Refreshes the grant tables. Field is defined as ENUM. Available since PHP 5.

and restarts the slave. On a master replication server: removes the binary log files listed in the binary log index. Flushes the thread cache. For example. libmysql may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. Flushes the host cache. like executing the FLUSH HOSTS SQL statement. The MySQLi Extension Function Summary Copyright 1997-2012 the PHP Documentation Group.MySQL Improved Extension (Mysqli) MYSQLI_REFRESH_LOG MYSQLI_REFRESH_TABLES MYSQLI_REFRESH_HOSTS MYSQLI_REFRESH_STATUS MYSQLI_REFRESH_THREADS MYSQLI_REFRESH_SLAVE MYSQLI_REFRESH_MASTER Flushes the logs. like executing the FLUSH STATUS SQL statement.3. Some implementation notes: 1. Notes Copyright 1997-2012 the PHP Documentation Group. if using mysqlnd. Note there are different internal implementations within libmysql and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. mysqli Class OOP Interface Properties $mysqli::affected_rows mysqli_affected_rows N/A Gets the number of affected rows in a previous MySQL operation Returns the MySQL client version as a string Returns MySQL client version info as an integer Returns the error code from last connect call Returns a string description of the last connect error Returns the error code for the most recent function call Returns a string description of the last error Returns the number of columns for the most recent query Returns a string representing the type of connection used Returns the version of the Procedural Interface Alias (Do not use) Description $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_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 89 N/A N/A N/A N/A N/A N/A N/A N/A N/A . less than 50 bytes.7. On a slave replication server: resets the master server information.8. Reset the status variables. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5. if there is a POINT column in a result set. 2. Generally speaking. Like executing the RESET SLAVE SQL statement. Memory allocation is much lower. 2. like executing the FLUSH TABLES SQL statement. Like executing the RESET MASTER SQL statement. Flushes the table cache. 2. like executing the FLUSH LOGS SQL statement. and truncates the index file. mysqlnd will allocate significantly less memory.

Available only with mysqlnd. NOT DOCUMENTED NOT DOCUMENTED Initializes MySQLi and returns a resource for use with mysqli_real_connect. Returns the MySQL client version as a string Returns client per-process statistics.e. [Not called on an object.] Asks the server to kill a MySQL Methods mysqli::autocommit mysqli::change_user mysqli_autocommit mysqli_change_user N/A N/A mysqli_client_encodin g N/A N/A N/A mysqli::character_set mysqli_character_set_ _name. mysqli::client_encoding name mysqli::close mysqli::commit mysqli::__construct mysqli_close mysqli_commit mysqli_connect mysqli::debug mysqli::dump_debug_in fo mysqli::get_charset mysqli::get_connectio n_stats mysqli::get_client_in fo mysqli::get_client_st ats mysqli::get_cache_sta ts mysqli::get_server_in fo 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 N/A N/A N/A N/A N/A N/A N/A mysqli::kill mysqli_kill 90 N/A . Returns client Zval cache statistics.MySQL Improved Extension (Mysqli) mysqli Class OOP Interface $mysqli::server_info $mysqli::server_version $mysqli::info $mysqli::insert_id $mysqli::sqlstate $mysqli::warning_count Procedural Interface mysqli_get_server_inf o mysqli_get_server_ver sion mysqli_info mysqli_insert_id mysqli_sqlstate mysqli_warning_count Alias (Do not use) N/A N/A N/A N/A N/A N/A Description MySQL protocol used Returns the version of the MySQL server Returns the version of the MySQL server as an integer Retrieves information about the most recently executed query Returns the auto generated id used in the last query Returns the SQLSTATE error from previous MySQL operation Returns the number of warnings from the last query for the given link Turns on or off auto-commiting database modifications Changes the user of the specified database connection 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. Available only with mysqlnd. as it returns a $mysqli object. Available only with mysqlnd. class) method] Performs debugging operations Dump debugging information into the log Returns a character set object Returns client connection statistics.

mysqli::escape_string mysqli::real_query mysqli::refresh mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_st ring N/A N/A N/A mysqli_escape_string mysqli_real_query mysqli_refresh N/A N/A mysqli::rollback mysqli::select_db mysqli::set_charset mysqli::set_local_inf ile_default mysqli::set_local_inf ile_handler mysqli::ssl_set mysqli::stat mysqli::stmt_init 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 N/A N/A N/A N/A N/A N/A N/A mysqli::store_result mysqli::thread_id mysqli::thread_safe mysqli::use_result mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result N/A N/A N/A N/A 91 .MySQL Improved Extension (Mysqli) mysqli Class OOP Interface mysqli::more_results mysqli::multi_query mysqli::next_result mysqli::options mysqli::ping Procedural Interface mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_options mysqli_ping Alias (Do not use) N/A N/A N/A mysqli_set_opt N/A Description 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 string for use in an SQL statement. or resets the replication server information 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::prepare mysqli::query mysqli::real_connect mysqli::real_escape_s tring. taking into account the current charset of the connection Execute an SQL query Flushes tables or caches.

MySQL Improved Extension (Mysqli) 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.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 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 Gets a result set from a prepared statement. NOT DOCUMENTED NOT DOCUMENTED Available only with mysqlnd. NOT DOCUMENTED Available only with mysqlnd. Available only with mysqlnd. See also property $mysqli_stmt::num_rows Prepare an SQL statement for execution Procedural Interface Alias (Do not use) Description $mysqli_stmt::errno $mysqli_stmt::error $mysqli_stmt::field_count N/A N/A N/A $mysqli_stmt::insert_id $mysqli_stmt::num_rows $mysqli_stmt::param_count $mysqli_stmt::sqlstate 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 N/A N/A mysqli_param_count N/A 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 mysqli_stmt::free_res ult mysqli_stmt::get_resu lt mysqli_stmt::get_warn ings $mysqli_stmt::more_results() $mysqli_stmt::next_result() mysqli_stmt::num_rows mysqli_stmt::prepare mysqli_stmt_free_resu lt mysqli_stmt_get_resul t mysqli_stmt_get_warni ngs mysqli_stmt_more_results() mysqli_stmt_next_result() mysqli_stmt_num_rows mysqli_stmt_prepare N/A N/A N/A N/A N/A N/A N/A 92 . 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 .

MySQL Improved Extension (Mysqli) MySQL_STMT OOP Interface mysqli_stmt::reset mysqli_stmt::result_m etadata mysqli_stmt::send_lon g_data mysqli_stmt::store_re sult Procedural Interface mysqli_stmt_reset mysqli_stmt_result_me tadata mysqli_stmt_send_long _data mysqli_stmt_store_res ult Alias (Do not use) N/A mysqli_get_metadata mysqli_send_long_data N/A Description Resets a prepared statement Returns result set metadata from a prepared statement Send data in blocks Transfers a result set from a prepared statement 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 result Adjusts the result pointer to an arbitary row in the result Fetches all result rows and returns the result set as an associative array. or both. 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 $mysqli_result::num_rows Methods mysqli_result::data_s eek mysqli_result::fetch_ all mysqli_num_rows N/A mysqli_data_seek mysqli_fetch_all N/A N/A 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. a numeric array. mysqli_result::close. Available only with mysqlnd. a numeric array. 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 N/A N/A N/A N/A N/A N/A N/A N/A N/A 93 . Fetch a result row as an associative.

string mysqli->client_info . int mysqli->client_version . string mysqli->host_info . int mysqli->errno . mixed mysqli->insert_id . string mysqli->info . int mysqli->client_version . string mysqli->sqlstate . The mysqli class (mysqli) Copyright 1997-2012 the PHP Documentation Group.9. int mysqli->server_version . string mysqli->error . string mysqli->connect_errno . int mysqli->field_count . string mysqli->server_info .MySQL Improved Extension (Mysqli) 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. 2. string mysqli->protocol_version . Do not use them in new projects. mysqli { mysqli Properties int mysqli->affected_rows . Represents a connection between PHP and a MySQL database. string mysqli->connect_error . 94 .

95 . bool mysqli::next_result().MySQL Improved Extension (Mysqli) int mysqli->thread_id . bool mysqli::kill(int processid). bool mysqli::dump_debug_info(). int usec). bool mysqli::options(int option. bool mysqli::close(). int sec. public int mysqli::poll(array read. bool mysqli::change_user(string user. int mysqli->warning_count . mysqli_stmt mysqli::prepare(string query). bool mysqli::real_connect(string host. mysqli_warning mysqli::get_warnings(). array error. array reject. bool mysqli::debug(string message). bool mysqli::commit(). bool mysqli::more_results(). int resultmode= =MYSQLI_STORE_RESULT). bool mysqli::ping(). string password. bool mysqli::get_connection_stats(). bool mysqli::multi_query(string query). void mysqli::disable_reads_from_master(). mysqli mysqli::init(). mixed value). string mysqli::character_set_name(). Methods bool mysqli::autocommit(bool mode). mixed mysqli::query(string query. string mysqli::get_client_info(). string database). object mysqli::get_charset().

bool mysqli::select_db(string dbname). bool mysqli::ssl_set(string string string string string string mysqli::stat().9. bool mysqli::real_query(string query).MySQL Improved Extension (Mysqli) string username. string socket. mysqli_affected_rows Copyright 1997-2012 the PHP Documentation Group. bool mysqli::rollback(). string dbname. mysqli::$affected_rows. • mysqli::$affected_rows mysqli_affected_rows Gets the number of affected rows in a previous MySQL operation Description Object oriented style int mysqli->affected_rows . cert. mysqli_stmt mysqli::stmt_init(). int port. callback read_func). mysqli_result mysqli::use_result(). 96 . bool mysqli::send_query(string query). public mysqli_result mysqli::reap_async_query(). public bool mysqli::refresh(int options). string passwd. string mysqli::escape_string(string escapestr). capath. ca. cipher). bool mysqli::set_charset(string charset). int flags). mysqli_result mysqli::store_result(). bool mysqli::set_local_infile_handler(mysqli link. 2. } key. int mysqli::rpl_query_type(string query).1.

printf("Affected rows (DELETE): %d\n". -1 indicates that the query returned an error. "my_user". $mysqli->query("ALTER TABLE Language ADD Status int default 0"). mysqli_affected_rows($link)). } /* Insert rows */ $mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage"). /* delete rows */ $mysqli->query("DELETE FROM Language WHERE Percentage < 50"). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init An integer greater than zero indicates the number of rows affected or retrieved. $result->close(). $mysqli->affected_rows). mysqli_connect_error()). Examples Example 2. For SELECT statements mysqli_affected_rows works like mysqli_num_rows. "my_password".30. no rows matched the WHERE clause in the query or that no query has yet been executed. printf("Affected rows (UPDATE): %d\n". mysqli_connect_error()). "ALTER TABLE Language ADD Status int default 0").MySQL Improved Extension (Mysqli) Procedural style int mysqli_affected_rows(mysqli link). mysqli_query($link. "world"). Zero indicates that no records where updated for an UPDATE statement. $mysqli->affected_rows). if (!$link) { printf("Can't connect to localhost. Note If the number of affected rows is greater than maximal int value. exit(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Error: %s\n". exit(). /* Delete table Language */ $mysqli->query("DROP TABLE Language"). "world"). "my_user". /* update rows */ 97 . REPLACE or DELETE query. printf("Affected rows (INSERT): %d\n". $mysqli->affected_rows). Returns the number of rows affected by the last INSERT. /* update rows */ $mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50"). } /* Insert rows */ mysqli_query($link. /* close connection */ $mysqli->close(). $mysqli->affected_rows). "CREATE TABLE Language SELECT * from CountryLanguage"). printf("Affected rows (INSERT): %d\n". "my_password". UPDATE. printf("Affected rows (SELECT): %d\n". /* select all rows */ $result = $mysqli->query("SELECT CountryCode FROM Language"). ?> Procedural style <?php $link = mysqli_connect("localhost". $mysqli->affected_rows example Object oriented style <?php $mysqli = new mysqli("localhost". the number of affected rows will be returned as a string.

98 . mysqli_affected_rows($link)). printf("Affected rows (DELETE): %d\n". /* Delete table Language */ mysqli_query($link. bool mode). mysqli_affected_rows($link)). mysqli_free_result($result). printf("Affected rows (SELECT): %d\n". ?> The above examples will output: Affected Affected Affected Affected rows rows rows rows (INSERT): (UPDATE): (DELETE): (SELECT): 984 168 815 169 See Also mysqli_num_rows mysqli_info 2. • mysqli::autocommit mysqli_autocommit Turns on or off auto-commiting database modifications Description Object oriented style bool mysqli::autocommit(bool mode). /* select all rows */ $result = mysqli_query($link.9. "UPDATE Language SET Status=1 WHERE Percentage > 50"). mysqli_affected_rows($link)).MySQL Improved Extension (Mysqli) mysqli_query($link. mysqli_autocommit Copyright 1997-2012 the PHP Documentation Group. Parameters link mode Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Whether to turn on auto-commit or not. To determine the current state of autocommit use the SQL command SELECT @@autocommit. "DELETE FROM Language WHERE Percentage < 50").2. mysqli::autocommit. Procedural style bool mysqli_autocommit(mysqli link. Turns on or off auto-commit mode on queries for the database connection. printf("Affected rows (UPDATE): %d\n". /* delete rows */ mysqli_query($link. "DROP TABLE Language"). /* close connection */ mysqli_close($link). "SELECT CountryCode FROM Language").

3. printf("Autocommit is %s\n". "my_password". printf("Autocommit is %s\n". } /* close connection */ mysqli_close($link). "my_user". if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). } /* close connection */ $mysqli->close(). Notes Note This function doesn't work with non transactional table types (like MyISAM or ISAM). exit(). if ($result = mysqli_query($link. Examples Example 2. ?> Procedural style <?php $link = mysqli_connect("localhost". $row[0]). "my_user". ?> The above examples will output: Autocommit is 1 See Also mysqli_commit mysqli_rollback 2. mysqli_free_result($result). } /* turn autocommit on */ $mysqli->autocommit(TRUE).9. "my_password". mysqli::change_user. TRUE). "world"). exit().MySQL Improved Extension (Mysqli) Return Values Returns TRUE on success or FALSE on failure. Error: %s\n". "world"). $result->free(). mysqli_connect_error()). $row[0]). "SELECT @@autocommit")) { $row = mysqli_fetch_row($result). mysqli_change_user 99 . if ($result = $mysqli->query("SELECT @@autocommit")) { $row = $result->fetch_row(). } /* turn autocommit on */ mysqli_autocommit($link. mysqli::autocommit example Object oriented style <?php $mysqli = new mysqli("localhost".31. if (!$link) { printf("Can't connect to localhost.

MySQL Improved Extension (Mysqli)

Copyright 1997-2012 the PHP Documentation Group. • mysqli::change_user mysqli_change_user Changes the user of the specified database connection Description Object oriented style
bool mysqli::change_user(string user, string password, string database);

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

link user password database

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

Example 2.32. mysqli::change_user example
Object oriented style
<?php /* connect database test */

100

MySQL Improved Extension (Mysqli)

$mysqli = new mysqli("localhost", "my_user", "my_password", "test"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Set Variable a */ $mysqli->query("SET @a:=1"); /* reset all and select a new database */ $mysqli->change_user("my_user", "my_password", "world"); if ($result = $mysqli->query("SELECT DATABASE()")) { $row = $result->fetch_row(); printf("Default database: %s\n", $row[0]); $result->close(); } if ($result = $mysqli->query("SELECT @a")) { $row = $result->fetch_row(); if ($row[0] === NULL) { printf("Value of variable a is NULL\n"); } $result->close(); } /* close connection */ $mysqli->close(); ?>

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); } /* close connection */ mysqli_close($link); ?>

The above examples will output:
Default database: world Value of variable a is NULL

See Also mysqli_connect mysqli_select_db

2.9.4. mysqli::character_set_name, mysqli_character_set_name
Copyright 1997-2012 the PHP Documentation Group.

101

MySQL Improved Extension (Mysqli)

mysqli::character_set_name mysqli_character_set_name Returns the default character set for the database connection

Description Object oriented style
string mysqli::character_set_name();

Procedural style
string mysqli_character_set_name(mysqli link);

Returns the current character set for the database connection. Parameters

link Return Values

Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

The default character set for the current connection Examples

Example 2.33. mysqli::character_set_name example
Object oriented style
<?php /* Open a connection */ $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); ?>

102

MySQL Improved Extension (Mysqli)

The above examples will output:
Current character set is latin1_swedish_ci

See Also mysqli_client_encoding mysqli_real_escape_string

2.9.5. mysqli::$client_info, mysqli_get_client_info
Copyright 1997-2012 the PHP Documentation Group. • mysqli::$client_info mysqli_get_client_info Returns the MySQL client version as a string Description Object oriented style
string mysqli->client_info ;

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 Examples

Example 2.34. mysqli_get_client_info
<?php /* We don't need a connection to determine the version of mysql client library */ printf("Client library version: %s\n", mysqli_get_client_info()); ?>

See Also mysqli_get_client_version mysqli_get_server_info mysqli_get_server_version

2.9.6. mysqli::$client_version, mysqli_get_client_version
103

MySQL Improved Extension (Mysqli)

Copyright 1997-2012 the PHP Documentation Group. • mysqli::$client_version mysqli_get_client_version Get MySQL client info Description Object oriented style
int mysqli->client_version ;

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 exists. Examples

Example 2.35. mysqli_get_client_version
<?php /* We don't need a connection to determine the version of mysql client library */ printf("Client library version: %d\n", mysqli_get_client_version()); ?>

See Also mysqli_get_client_info mysqli_get_server_info mysqli_get_server_version

2.9.7. mysqli::close, mysqli_close
Copyright 1997-2012 the PHP Documentation Group. • mysqli::close mysqli_close Closes a previously opened database connection Description

104

Commits the current transaction for the database connection. mysqli_commit Copyright 1997-2012 the PHP Documentation Group.MySQL Improved Extension (Mysqli) Object oriented style bool mysqli::close(). See Also mysqli_connect mysqli_init mysqli_real_connect 2. • mysqli::commit mysqli_commit Commits the current transaction Description Object oriented style bool mysqli::commit(). mysqli::commit. Examples See mysqli_connect. Closes a previously opened database connection.8.9. Procedural style bool mysqli_commit(mysqli link). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure. Procedural style bool mysqli_close(mysqli link). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 105 .

mysqli_connect_errno Copyright 1997-2012 the PHP Documentation Group. 11. mysqli_connect_error()). /* commit transaction */ mysqli_commit($link). "CREATE TABLE Language LIKE CountryLanguage"). • mysqli::$connect_errno mysqli_connect_errno Returns the error code from last connect call 106 . FALSE). mysqli_query($link. mysqli::commit example Object oriented style <?php $mysqli = new mysqli("localhost". 'F'. "world"). 'Bavarian'. 11. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli::$connect_errno. } /* set autocommit to off */ mysqli_autocommit($link. "my_password".9. Examples Example 2. exit(). ?> See Also mysqli_autocommit mysqli_rollback 2.36. 9.2)"). /* check connection */ if (!$link) { printf("Connect failed: %s\n". /* drop table */ $mysqli->query("DROP TABLE Language"). "my_password". /* commit transaction */ $mysqli->commit(). 9. /* set autocommit to off */ $mysqli->autocommit(FALSE).4)"). "INSERT INTO Language VALUES ('DEU'. /* close connection */ mysqli_close($link). /* Insert some values */ $mysqli->query("INSERT INTO Language VALUES ('DEU'. /* Insert some values */ mysqli_query($link. "my_user". mysqli_connect_error()). 'Swabian'. mysqli_query($link. 'F'. 'F'.4)"). $mysqli->query("INSERT INTO Language VALUES ('DEU'. "test"). "my_user". 'Bavarian'. ?> Procedural style <?php $link = mysqli_connect("localhost". "INSERT INTO Language VALUES ('DEU'. } $mysqli->query("CREATE TABLE Language LIKE CountryLanguage"). exit(). /* close connection */ $mysqli->close().2)").9. 'Swabian'.MySQL Improved Extension (Mysqli) Returns TRUE on success or FALSE on failure. 'F'.

'fake_user'. zero means no error occurred. if it failed. 'my_password'. if ($mysqli->connect_errno) { die('Connect Error: ' . In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error. } ?> Procedural style <?php $link = @mysqli_connect('localhost'. Note Client error message numbers are listed in the MySQL errmsg. server error message numbers are listed in mysqld_error.37.txt. Examples Example 2. 'fake_user'.h. Procedural style int mysqli_connect_errno(). 'my_db'). Returns the last error code number from the last call to mysqli_connect. $mysqli->connect_errno example Object oriented style <?php $mysqli = @new mysqli('localhost'. 'my_password'. mysqli_connect_errno()). 'my_db'). if (!$link) { die('Connect Error: ' .h header file.MySQL Improved Extension (Mysqli) Description Object oriented style string mysqli->connect_errno . $mysqli->connect_errno). } ?> The above examples will output: Connect Error: 1045 See Also mysqli_connect mysqli_connect_error mysqli_errno mysqli_error mysqli_sqlstate 107 . Return Values An error code value for the last call to mysqli_connect.

} ?> The above examples will output: Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES) Notes Warning 108 . Return Values A string that describes the error. Examples Example 2.3. if (!$link) { die('Connect Error: ' . Procedural style string mysqli_connect_error(). mysqli_connect_error Copyright 1997-2012 the PHP Documentation Group. $mysqli->connect_error). • mysqli::$connect_error mysqli_connect_error Returns a string description of the last connect error Description Object oriented style string mysqli->connect_error . 'my_password'. 'my_password'. 'fake_user'.9. NULL is returned if no error occurred.0. $mysqli->connect_error example Object oriented style <?php $mysqli = @new mysqli('localhost'.2. mysqli::$connect_error. } ?> Procedural style <?php $link = @mysqli_connect('localhost'.38.9 and 5. 'fake_user'. if ($mysqli->connect_error) { die('Connect Error: ' . 'my_db'). 'my_db').10.MySQL Improved Extension (Mysqli) 2. // Works as of PHP 5. mysqli_connect_error()). Returns the last error message string from the last call to mysqli_connect.

default_socket")). Passing the NULL value or the string "localhost" to this parameter. Specifies the port number to attempt to connect to the MySQL server. the MySQL server will attempt to authenticate the user against those user records which have no password only. int port= =ini_get("mysqli. This allows one username to be used with different permissions (depending on if a password as provided or not). Opens a connection to the MySQL Server running on. string socket= =ini_get("mysqli.default_socket")). string dbname= ="". string socket= =ini_get("mysqli. Specifies the socket or named pipe that should be used.default_host").9 and 5.default_port").3. Procedural style mysqli mysqli_connect(string host= =ini_get("mysqli. See Also mysqli_connect mysqli_connect_errno mysqli_errno mysqli_error mysqli_sqlstate 2. username passwd The MySQL user name.default_pw").default_user"). string dbname= ="". string passwd= =ini_get("mysqli. • mysqli::__construct mysqli_connect Open a new connection to the MySQL server Description Object oriented style mysqli::__construct(string host= =ini_get("mysqli. string username= =ini_get("mysqli. mysqli::__construct.default_port").MySQL Improved Extension (Mysqli) The mysqli->connect_error property only works properly as of PHP versions 5. Use the mysqli_connect_error function if compatibility with earlier PHP versions is required. mysqli_connect Copyright 1997-2012 the PHP Documentation Group.2.11. int port= =ini_get("mysqli. string passwd= =ini_get("mysqli.9.0. pipes will be used instead of the TCP/IP protocol. mysqli_change_user is automatically called on connections opened from the connection pool.default_host").default_user"). the local host is assumed.default_pw"). 109 dbname port socket . If provided will specify the default database to be used when performing queries. Prepending host by p: opens a persistent connection. When possible. Parameters host Can be either a host name or an IP address. string username= =ini_get("mysqli. If not provided or NULL .

'my_password'. 'my_password'..3. 'my_user'. $mysqli->host_info . $mysqli->connect_errno . } } } $db = new foo_mysqli('localhost'. Example 2. */ if (mysqli_connect_error()) { die('Connect Error (' . Changelog Version 5.9 and 5. mysqli::__construct example Object oriented style <?php $mysqli = new mysqli('localhost'. 'my_user'. * BUT $connect_error was broken until PHP 5. How the connection is made to the MySQL database is determined by the host parameter.. 'my_db').0 Examples Description Added the ability of persistent connections. $db->close().0. } echo 'Success. ') ' . 'my_password'.3. echo 'Success. $db->host_info . mysqli_connect_errno() . 'my_db'). } /* * Use this instead of $connect_error if you need to ensure * compatibility with PHP versions prior to 5.39. "\n". ') ' . "\n". ' . $mysqli->close(). ?> Procedural style <?php $link = mysqli_connect('localhost'. $pass. ') ' .. 110 . $user. mysqli_connect_errno() . $db).2. */ if ($mysqli->connect_error) { die('Connect Error (' . 'my_user'. 'my_db'). $db) { parent::__construct($host. ' . ?> Object oriented style when extending mysqli class <?php class foo_mysqli extends mysqli { public function __construct($host. $pass. if (mysqli_connect_error()) { die('Connect Error (' . /* * This is the "official" OO way to do it.. $user.3.2.MySQL Improved Extension (Mysqli) Note Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. Return Values Returns an object which represents the connection to a MySQL Server.0. $mysqli->connect_error).9 and 5. mysqli_connect_error()). mysqli_connect_error()).

cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect. On Windows. mysqli_debug Copyright 1997-2012 the PHP Documentation Group. MySQL host info: localhost via TCP/IP Notes Note MySQLnd always assumes the server default charset. mysqli_close($link). } echo 'Success. Note OO syntax only: If a connection fails an object is still returned. Note If it is necessary to set options. "\n"..12. • mysqli::debug mysqli_debug Performs debugging operations 111 . mysqli_connect_error()). ') ' . ?> The above examples will output: Success. mysqli::debug. if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. Note Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. This charset is sent during connection hand-shake/authentication. See Also mysqli_real_connect mysqli_options mysqli_connect_errno mysqli_connect_error mysqli_close 2. Note Calling the constructor with no parameters is the same as calling mysqli_init.. Libmysql uses the default charset set in the my. which mysqlnd will use.9. such as the connection timeout. 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. mysqli_real_connect must be used instead. ' .. mysqli_get_host_info($link) .MySQL Improved Extension (Mysqli) if (!$link) { die('Connect Error (' .. but after mysqli_init. mysqli_connect_errno() .

Performs debugging operations using the Fred Fish debugging library. • mysqli::disable_reads_from_master mysqli_disable_reads_from_master Disable reads from master Description Object oriented style 112 .trace' on the local (client) machine: */ mysqli_debug("d:t:o. Generating a Trace File <?php /* Create a trace file in '/tmp/client.MySQL Improved Extension (Mysqli) Description Object oriented style bool mysqli::debug(string message). Examples Example 2. Notes A string representing the debugging operation to perform Note To use the mysqli_debug function you must compile the MySQL client library to support debugging./tmp/client.9. Parameters message Return Values Returns TRUE .40.13. mysqli_disable_reads_from_master Copyright 1997-2012 the PHP Documentation Group.trace"). Procedural style bool mysqli_debug(string message). ?> See Also mysqli_dump_debug_info mysqli_report 2. mysqli::disable_reads_from_master.

only its argument list is available.15. mysqli::dump_debug_info. Procedural style bool mysqli_disable_reads_from_master(mysqli link). mysqli::$errno.0. Warning This function is currently not documented.14. mysqli_dump_debug_info Copyright 1997-2012 the PHP Documentation Group. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure. 2.9. Warning This function has been DEPRECATED and REMOVED as of PHP 5. 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.3. • mysqli::$errno mysqli_errno 113 .9. See Also mysqli_debug 2. Procedural style bool mysqli_dump_debug_info(mysqli link).MySQL Improved Extension (Mysqli) void mysqli::disable_reads_from_master(). • mysqli::dump_debug_info mysqli_dump_debug_info Dump debugging information into the log Description Object oriented style bool mysqli::dump_debug_info(). mysqli_errno Copyright 1997-2012 the PHP Documentation Group.

txt. exit(). } /* close connection */ $mysqli->close(). "world").h header file. Client error message numbers are listed in the MySQL errmsg. "my_password". if it failed. "my_user". Returns the last error code for the most recent MySQLi function call that can succeed or fail. mysqli_errno($link)). "my_user".h. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } if (!mysqli_query($link.41. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". ?> 114 . ?> Procedural style <?php $link = mysqli_connect("localhost". $mysqli->errno). server error message numbers are listed in mysqld_error. } /* close connection */ mysqli_close($link). mysqli_connect_error()). Procedural style int mysqli_errno(mysqli link). "my_password". Examples Example 2. "world"). exit(). $mysqli->errno example Object oriented style <?php $mysqli = new mysqli("localhost".MySQL Improved Extension (Mysqli) Returns the error code for the most recent function call Description Object oriented style int mysqli->errno . Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init An error code value for the last call. "SET a=1")) { printf("Errorcode: %d\n". In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error. } if (!$mysqli->query("SET a=1")) { printf("Errorcode: %d\n". mysqli_connect_error()). zero means no error occurred.

9. 115 . mysqli::$error. An empty string if no error occurred. "my_password".42. Procedural style string mysqli_error(mysqli link). "my_user". } if (!$mysqli->query("SET a=1")) { printf("Errormessage: %s\n". mysqli_error Copyright 1997-2012 the PHP Documentation Group. "world"). • mysqli::$error mysqli_error Returns a string description of the last error Description Object oriented style string mysqli->error . Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A string that describes the error. exit(). mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $mysqli->error). $mysqli->error example Object oriented style <?php $mysqli = new mysqli("localhost".16. Returns the last error message for the most recent MySQLi function call that can succeed or fail.MySQL Improved Extension (Mysqli) The above examples will output: Errorcode: 1193 See Also mysqli_connect_errno mysqli_connect_error mysqli_error mysqli_sqlstate 2. Examples Example 2.

Procedural style int mysqli_field_count(mysqli link). ?> Procedural style <?php $link = mysqli_connect("localhost". mysqli_field_count Copyright 1997-2012 the PHP Documentation Group. exit(). "my_password". "my_user". } /* close connection */ mysqli_close($link). } if (!mysqli_query($link. "SET a=1")) { printf("Errormessage: %s\n". mysqli_connect_error()).17. Parameters 116 . 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. ?> The above examples will output: Errormessage: Unknown system variable 'a' See Also mysqli_connect_errno mysqli_connect_error mysqli_errno mysqli_sqlstate 2. • mysqli::$field_count mysqli_field_count Returns the number of columns for the most recent query Description Object oriented style int mysqli->field_count . mysqli::$field_count. "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".MySQL Improved Extension (Mysqli) } /* close connection */ $mysqli->close(). mysqli_error($link)).9. Returns the number of columns for the most recent query on the connection represented by the link parameter.

• mysqli::get_charset mysqli_get_charset Returns a character set object Description 117 . if (mysqli_field_count($link)) { /* this was a select/show or describe query */ $result = mysqli_store_result($link). mysqli_real_query($link. name varchar(20))"). /* free resultset */ $result->close().MySQL Improved Extension (Mysqli) link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init An integer representing the number of fields in a result set.9. $mysqli->query( "CREATE TABLE friends (id int. $mysqli->query( "DROP TABLE IF EXISTS friends"). "my_user". Examples Example 2. (2. mysqli_query($link. "INSERT INTO friends VALUES (1. name varchar(20))").18. 'Ulf')").43. mysqli::get_charset. "DROP TABLE IF EXISTS friends"). $mysqli->field_count example Object oriented style <?php $mysqli = new mysqli("localhost". "SELECT * FROM friends"). } /* close connection */ mysqli_close($link). 'Ulf')"). (2. "my_password". "CREATE TABLE friends (id int. /* process resultset */ $row = mysqli_fetch_row($result). if ($mysqli->field_count) { /* this was a select/show or describe query */ $result = $mysqli->store_result(). "my_user". ?> Procedural style <?php $link = mysqli_connect("localhost". /* process resultset */ $row = $result->fetch_row(). mysqli_query($link. "test"). mysqli_query($link. ?> 2. mysqli_get_charset Copyright 1997-2012 the PHP Documentation Group. /* free resultset */ mysqli_free_result($result). $mysqli->query( "INSERT INTO friends VALUES (1. } /* close connection */ $mysqli->close(). "test").'Hartmut').'Hartmut'). "my_password". $mysqli->real_query("SELECT * FROM friends").

"localhost". $db->real_connect("localhost"."". Returns a character set object providing several properties of the current active character set."root". Procedural style object mysqli_get_charset(mysqli link).44. ?> Procedural style <?php $db = mysqli_init(). var_dump($db->get_charset()).MySQL Improved Extension (Mysqli) Object oriented style object mysqli::get_charset()."test")."test"). mysqli_real_connect($db."root"."". mysqli::get_charset example Object oriented style <?php $db = mysqli_init(). ?> The above examples will output: object(stdClass)#2 (7) { ["charset"]=> string(6) "latin1" 118 . var_dump($db->get_charset()). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 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 (?) Example 2.

mysqli::get_client_info. mysqli_get_client_info Copyright 1997-2012 the PHP Documentation Group.45.19. Procedural style string mysqli_get_client_info(mysqli link). mysqli_get_client_info <?php /* We don't need a connection to determine the version of mysql client library */ printf("Client library version: %s\n".MySQL Improved Extension (Mysqli) ["collation"]=> string(17) "latin1_swedish_ci" ["dir"]=> string(0) "" ["min_length"]=> int(1) ["max_length"]=> int(1) ["number"]=> int(8) ["state"]=> int(801) } See Also mysqli_character_set_name mysqli_set_charset 2.9. ?> See Also 119 . Returns a string that represents the MySQL client library version. • mysqli::get_client_info mysqli_get_client_info Returns the MySQL client version as a string Description Object oriented style string mysqli::get_client_info(). mysqli_get_client_info()). Return Values A string that represents the MySQL client library version Examples Example 2.

A mysqli_get_client_stats example <?php $link = mysqli_connect(). • mysqli_get_client_stats Returns client per-process statistics Description array mysqli_get_client_stats().MySQL Improved Extension (Mysqli) mysqli_get_client_version mysqli_get_server_info mysqli_get_server_version 2. print_r(mysqli_get_client_stats()). ?> The above example will output something similar to: 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 120 . FALSE otherwise.9. Parameters Return Values Returns an array with client stats if success. mysqli_get_client_stats Copyright 1997-2012 the PHP Documentation Group. Available only with mysqlnd.46. Examples Example 2.20. Returns client per-process statistics.

MySQL Improved Extension (Mysqli) [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 [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 121 .

0 is returned as 40100. Procedural style int mysqli_get_client_version(mysqli link).MySQL Improved Extension (Mysqli) ) See Also Stats description 2. mysqli_get_client_version()).47. mysqli::$client_version.1. For example.22. 4. mysqli_get_connection_stats 122 . Returns client version number as an integer. mysqli_get_client_version Copyright 1997-2012 the PHP Documentation Group. Return Values A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version.21. • mysqli::$client_version mysqli_get_client_version Get MySQL client info Description Object oriented style int mysqli->client_version . mysqli_get_client_version <?php /* We don't need a connection to determine the version of mysql client library */ printf("Client library version: %d\n".9.9. ?> See Also mysqli_get_client_info mysqli_get_server_info mysqli_get_server_version 2. This is useful to quickly determine the version of the client library to know if some capability exits. Examples Example 2. mysqli::get_connection_stats.

MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. Examples Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Example 2. FALSE otherwise. Procedural style array mysqli_get_connection_stats(mysqli link). A mysqli_get_connection_stats example <?php $link = mysqli_connect(). Available only with mysqlnd. ?> The above example will output something similar to: 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 123 . Returns statistics about the client connection.48. print_r(mysqli_get_connection_stats($link)). • mysqli::get_connection_stats mysqli_get_connection_stats Returns statistics about the client connection Description Object oriented style bool mysqli::get_connection_stats(). Parameters link Return Values Returns an array with connection stats if success.

MySQL Improved Extension (Mysqli) [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 124 .

/* close connection */ 125 . mysqli_get_host_info Copyright 1997-2012 the PHP Documentation Group. "world"). exit().MySQL Improved Extension (Mysqli) [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 ) See Also Stats description 2. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A character string representing the server hostname and the connection type. } /* print host information */ printf("Host info: %s\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $mysqli->host_info example Object oriented style <?php $mysqli = new mysqli("localhost". $mysqli->host_info). • mysqli::$host_info mysqli_get_host_info Returns a string representing the type of connection used Description Object oriented style string mysqli->host_info .49. mysqli::$host_info.9. "my_user". Examples Example 2. mysqli_connect_error()). "my_password". Procedural style string mysqli_get_host_info(mysqli link).23. Returns a string describing the connection represented by the link parameter (including the server host name).

} /* print host information */ printf("Host info: %s\n". ?> The above examples will output: Host info: Localhost via UNIX socket See Also mysqli_get_proto_info 2. Procedural style int mysqli_get_proto_info(mysqli link). mysqli_get_proto_info Copyright 1997-2012 the PHP Documentation Group. "my_password". "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter. mysqli_connect_error()).24. exit().MySQL Improved Extension (Mysqli) $mysqli->close(). ?> Procedural style <?php $link = mysqli_connect("localhost". mysqli::$protocol_version. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 126 . /* close connection */ mysqli_close($link).9. • mysqli::$protocol_version mysqli_get_proto_info Returns the version of the MySQL protocol used Description Object oriented style string mysqli->protocol_version . mysqli_get_host_info($link)).

MySQL Improved Extension (Mysqli) Returns an integer representing the protocol version. mysqli_connect_error()). mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli::$server_info. 127 . "my_password").50. "my_password"). } /* print protocol version */ printf("Protocol version: %d\n". ?> Procedural style <?php $link = mysqli_connect("localhost". exit(). exit(). /* close connection */ mysqli_close($link).9. ?> The above examples will output: Protocol version: 10 See Also mysqli_get_host_info 2. mysqli_get_server_info Copyright 1997-2012 the PHP Documentation Group. "my_user". $mysqli->protocol_version example Object oriented style <?php $mysqli = new mysqli("localhost". "my_user". /* close connection */ $mysqli->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $mysqli->protocol_version). } /* print protocol version */ printf("Protocol version: %d\n". • mysqli::$server_info mysqli_get_server_info Returns the version of the MySQL server Description Object oriented style string mysqli->server_info .25. Examples Example 2. mysqli_get_proto_info($link)).

} /* print server version */ printf("Server version: %s\n". mysqli_connect_error()). "my_user".1.2-alpha-debug See Also mysqli_get_client_info mysqli_get_client_version mysqli_get_server_version 128 . exit(). /* close connection */ $mysqli->close(). Returns a string representing the version of the MySQL server that the MySQLi extension is connected to. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A character string representing the server version. /* close connection */ mysqli_close($link). mysqli_connect_error()). } /* print server version */ printf("Server version: %s\n".51. exit(). mysqli_get_server_info($link)). "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $mysqli->server_info). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Examples Example 2. ?> Procedural style <?php $link = mysqli_connect("localhost". $mysqli->server_info example Object oriented style <?php $mysqli = new mysqli("localhost".MySQL Improved Extension (Mysqli) Procedural style string mysqli_get_server_info(mysqli link). "my_password"). "my_password"). ?> The above examples will output: Server version: 4.

/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init An integer representing the server version. "my_user". version 4. mysqli_connect_error()). ?> Procedural style <?php $link = mysqli_connect("localhost". Examples Example 2. $mysqli->server_version example Object oriented style <?php $mysqli = new mysqli("localhost". "my_password"). $mysqli->server_version). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style int mysqli_get_server_version(mysqli link).0 is 40100). "my_user". The mysqli_get_server_version function returns the version of the server connected to (represented by the link parameter) as an integer.9. • mysqli::$server_version mysqli_get_server_version Returns the version of the MySQL server as an integer Description Object oriented style int mysqli->server_version .52. mysqli::$server_version. The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.1.e. mysqli_get_server_version Copyright 1997-2012 the PHP Documentation Group.26.MySQL Improved Extension (Mysqli) 2. } /* print server version */ printf("Server version: %d\n". /* close connection */ $mysqli->close(). "my_password"). mysqli_connect_error()). exit(). 129 .

• mysqli::get_warnings mysqli_get_warnings Get result of SHOW WARNINGS Description Object oriented style mysqli_warning mysqli::get_warnings(). mysqli_get_server_version($link)).MySQL Improved Extension (Mysqli) exit(). mysqli::get_warnings. only its argument list is available. Procedural style mysqli_warning mysqli_get_warnings(mysqli link). mysqli_get_warnings Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented. mysqli::$info.9. } /* print server version */ printf("Server version: %d\n". 2. /* close connection */ mysqli_close($link).28. mysqli_info Copyright 1997-2012 the PHP Documentation Group.27. ?> The above examples will output: Server version: 40102 See Also mysqli_get_client_info mysqli_get_client_version mysqli_get_server_info 2. • mysqli::$info mysqli_info Retrieves information about the most recently executed query Description Object oriented style 130 .9.

"world"). "world"). Possible mysqli_info return values Query type INSERT INTO... INSERT INTO.. /* close connection */ $mysqli->close().). ?> Procedural style <?php $link = mysqli_connect("localhost".. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_info will return an empty string. $mysqli->info). In these situations. Examples Example 2. UPDATE . "my_user". "my_password"... /* INSERT INTO . /* check connection */ 131 ..53..MySQL Improved Extension (Mysqli) string mysqli->info . Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A character string representing additional information about the most recently executed query. Example result string Records: 100 Duplicates: 0 Warnings: 0 Records: 3 Duplicates: 0 Warnings: 0 Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 Records: 3 Duplicates: 0 Warnings: 0 Rows matched: 40 Changed: 40 Warnings: 0 Note Queries which do not fall into one of the preceding formats are not supported. "my_password".. Procedural style string mysqli_info(mysqli link).... exit(). mysqli_connect_error()). "my_user". The nature of this string is provided below: Table 2..(. SELECT */ $mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150")..VALUES (. } $mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City")... The mysqli_info function returns a string providing information about the last query executed.. $mysqli->info example Object oriented style <?php $mysqli = new mysqli("localhost"..(.). ALTER TABLE . printf("%s\n".3.SELECT.) LOAD DATA INFILE ..

. /* close connection */ mysqli_close($link). mysqli::init. ?> The above examples will output: Records: 150 Duplicates: 0 Warnings: 0 See Also mysqli_affected_rows mysqli_warning_count mysqli_num_rows 2. See Also 132 . mysqli_init Copyright 1997-2012 the PHP Documentation Group. mysqli_info($link)).MySQL Improved Extension (Mysqli) if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Note Any subsequent calls to any mysqli function (except mysqli_options) will fail until mysqli_real_connect was called. Allocates or initializes a MYSQL object suitable for mysqli_options and mysqli_real_connect. Examples See mysqli_real_connect. Return Values Returns an object. mysqli_connect_error()). Procedural style mysqli mysqli_init(). • mysqli::init mysqli_init Initializes MySQLi and returns a resource for use with mysqli_real_connect() Description Object oriented style mysqli mysqli::init(). SELECT */ mysqli_query($link.29. "CREATE TEMPORARY TABLE t1 LIKE City"). } mysqli_query($link. printf("%s\n". exit(). /* INSERT INTO . "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150").9.

9. exit(). • mysqli::$insert_id mysqli_insert_id Returns the auto generated id used in the last query Description Object oriented style mixed mysqli->insert_id . mysqli_connect_error()). mysqli_insert_id Copyright 1997-2012 the PHP Documentation Group. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The value of the AUTO_INCREMENT field that was updated by the previous query.30. this function will return zero. Procedural style mixed mysqli_insert_id(mysqli link). Note If the number is greater than maximal int value. The mysqli_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. mysqli_insert_id will return a string. 133 . "my_password". "world"). mysqli::$insert_id.54. 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. Examples Example 2.MySQL Improved Extension (Mysqli) mysqli_options mysqli_close mysqli_real_connect mysqli_connect 2. 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. $mysqli->insert_id example Object oriented style <?php $mysqli = new mysqli("localhost". Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user".

/* close connection */ $mysqli->close(). mysqli_connect_error()). /* drop table */ mysqli_query($link. printf ("New Record has id %d.31. 'DEU'. 617000)". exit(). 'Stuttgart'. 'Stuttgart'. printf ("New Record has id %d. /* drop table */ $mysqli->query("DROP TABLE myCity"). "world").9. Procedural style bool mysqli_kill(mysqli link. To stop a running query you should use the SQL command KILL QUERY processid. "my_password". Parameters 134 . 617000)". $query = "INSERT INTO myCity VALUES (NULL. • mysqli::kill mysqli_kill Asks the server to kill a MySQL thread Description Object oriented style bool mysqli::kill(int processid). $query). 2. mysqli::kill. ?> Procedural style <?php $link = mysqli_connect("localhost". $mysqli->query($query).\n". ?> The above examples will output: New Record has id 1. $query = "INSERT INTO myCity VALUES (NULL.MySQL Improved Extension (Mysqli) } $mysqli->query("CREATE TABLE myCity LIKE City"). "my_user". This value must be retrieved by calling the mysqli_thread_id function. 'Stuttgart'. "CREATE TABLE myCity LIKE City"). This function is used to ask the server to kill a MySQL thread specified by the processid parameter. /* close connection */ mysqli_close($link). int processid). $mysqli->insert_id). mysqli_kill Copyright 1997-2012 the PHP Documentation Group. "DROP TABLE myCity"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". 'Stuttgart'. mysqli_query($link. } mysqli_query($link. mysqli_insert_id($link)).\n". 'DEU'.

} /* close connection */ $mysqli->close(). } /* close connection */ mysqli_close($link). "my_user". "my_password".MySQL Improved Extension (Mysqli) link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure. } /* determine our thread id */ $thread_id = $mysqli->thread_id. mysqli::kill example Object oriented style <?php $mysqli = new mysqli("localhost". /* Kill connection */ mysqli_kill($link. exit(). /* This should produce an error */ if (!mysqli_query($link. exit. $thread_id). "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). ?> The above examples will output: Error: MySQL server has gone away See Also mysqli_thread_id 135 . "my_user". } /* determine our thread id */ $thread_id = mysqli_thread_id($link). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". exit(). "world"). mysqli_connect_error()). "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n". Examples Example 2. /* This should produce an error */ if (!$mysqli->query("CREATE TABLE myCity LIKE City")) { printf("Error: %s\n". exit. "my_password". ?> Procedural style <?php $link = mysqli_connect("localhost". $mysqli->error). mysqli_error($link)).55. /* Kill connection */ $mysqli->kill($thread_id).

mysqli_more_results Copyright 1997-2012 the PHP Documentation Group. See Also mysqli_multi_query mysqli_next_result mysqli_store_result mysqli_use_result 2. mysqli::more_results.32. Indicates if one or more result sets are available from a previous call to mysqli_multi_query. mysqli_multi_query Copyright 1997-2012 the PHP Documentation Group. Examples See mysqli_multi_query.MySQL Improved Extension (Mysqli) 2. • mysqli::more_results mysqli_more_results Check if there are any more query results from a multi query Description Object oriented style bool mysqli::more_results().9.9. Procedural style bool mysqli_more_results(mysqli link). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure.33. • mysqli::multi_query mysqli_multi_query Performs a query on the database Description Object oriented style bool mysqli::multi_query(string query). mysqli::multi_query. 136 .

} $result->free(). $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20. string query).MySQL Improved Extension (Mysqli) Procedural style bool mysqli_multi_query(mysqli link. Data inside the query should be properly escaped. Return Values Returns FALSE if the first statement failed. "my_user". 137 . Parameters link query Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query.". as a string. "world"). To retrieve the resultset from the first query you can use mysqli_use_result or mysqli_store_result. ?> Procedural style <?php $link = mysqli_connect("localhost". 5".". "my_password". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } $query = "SELECT CURRENT_USER(). Executes one or multiple queries which are concatenated by a semicolon. mysqli::multi_query example Object oriented style <?php $mysqli = new mysqli("localhost". All subsequent query results can be processed using mysqli_more_results and mysqli_next_result. } /* close connection */ $mysqli->close(). "world"). mysqli_connect_error()). Examples Example 2. exit(). $row[0]). } } while ($mysqli->next_result()). "my_password". "my_user". } $query = "SELECT CURRENT_USER(). To retrieve subsequent errors from other statements you have to call mysqli_next_result first. } /* print divider */ if ($mysqli->more_results()) { printf("-----------------\n"). mysqli_connect_error()). /* execute multi query */ if ($mysqli->multi_query($query)) { do { /* store first result set */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { printf("%s\n".56. exit().

9. } /* close connection */ mysqli_close($link).MySQL Improved Extension (Mysqli) $query . Prepares next result set from a previous call to mysqli_multi_query which can be retrieved by mysqli_store_result or mysqli_use_result. ?> The above examples will output something similar to: my_user@localhost ----------------Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer See Also mysqli_use_result mysqli_store_result mysqli_next_result mysqli_more_results 2. } } while (mysqli_next_result($link)). • mysqli::next_result mysqli_next_result Prepare next result from multi_query Description Object oriented style bool mysqli::next_result(). /* execute multi query */ if (mysqli_multi_query($link. mysqli::next_result. mysqli_next_result Copyright 1997-2012 the PHP Documentation Group. Parameters 138 .34. $query)) { do { /* store first result set */ if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n". } mysqli_free_result($result). Procedural style bool mysqli_next_result(mysqli link). } /* print divider */ if (mysqli_more_results($link)) { printf("-----------------\n"). 5".= "SELECT Name FROM City ORDER BY ID LIMIT 20. $row[0]).

3. This function may be called multiple times to set several options. Parameters link option Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The option that you want to set. Valid options Name MYSQLI_OPT_CONNECT_TIMEOUT Description connection timeout in seconds (supported on Windows with TCP/ IP since PHP 5. • mysqli::options mysqli_options Set options Description Object oriented style bool mysqli::options(int option. mysqli_options should be called after mysqli_init and before mysqli_real_connect.MySQL Improved Extension (Mysqli) link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure. mysqli_options Copyright 1997-2012 the PHP Documentation Group. Procedural style bool mysqli_options(mysqli link. Used to set extra connect options and affect behavior for a connection. Examples See mysqli_multi_query.35. mysqli::options.4. mixed value).9. int option. mixed value). It can be one of the following values: Table 2.1) 139 . See Also mysqli_multi_query mysqli_more_results mysqli_store_result mysqli_use_result 2.

cnf or the file specified with MYSQL_READ_DEFAULT_FILE . which mysqlnd will use. Checks whether the connection to the server is working. If it has gone down. This function can be used by clients that remain idle for a long while. Libmysql uses the default charset set in the my. • mysqli::ping mysqli_ping Pings a server connection. The value for the option.36. Examples See mysqli_real_connect. This charset is sent during connection hand-shake/authentication. and global option mysqli. or tries to reconnect if the connection has gone down Description Object oriented style bool mysqli::ping(). to check whether the server has closed the connection and reconnect if necessary.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect. Procedural style bool mysqli_ping(mysqli link). mysqli::ping.reconnect is enabled an automatic reconnection is attempted. Notes Note MySQLnd always assumes the server default charset. mysqli_ping Copyright 1997-2012 the PHP Documentation Group. See Also mysqli_init mysqli_real_connect 2. 140 . but after mysqli_init.MySQL Improved Extension (Mysqli) Name MYSQLI_OPT_LOCAL_INFILE MYSQLI_INIT_COMMAND MYSQLI_READ_DEFAULT_FILE MYSQLI_READ_DEFAULT_GROUP Description enable/disable use of LOAD LOCAL INFILE command to execute after when connecting to MySQL server Read options from named option file instead of my.cnf Read options from the named group from my.9. value Return Values Returns TRUE on success or FALSE on failure.

"my_password". } /* close connection */ mysqli_close($link). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".MySQL Improved Extension (Mysqli) Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure. ?> The above examples will output: Our connection is ok! 2. • mysqli::poll 141 .57. } /* close connection */ $mysqli->close(). } /* check if server is alive */ if (mysqli_ping($link)) { printf ("Our connection is ok!\n"). mysqli_poll Copyright 1997-2012 the PHP Documentation Group. "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Examples Example 2. "my_password". mysqli_connect_error()). mysqli_connect_error()). "my_user". exit(). $mysqli->error).9. exit(). mysqli::poll. } else { printf ("Error: %s\n". mysqli::ping example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_error($link)). ?> Procedural style <?php $link = mysqli_connect("localhost". "world"). } /* check if server is alive */ if ($mysqli->ping()) { printf ("Our connection is ok!\n"). "world"). } else { printf ("Error: %s\n".37.

} if (!mysqli_poll($links. } foreach ($links as $link) { if ($result = $link->reap_async_query()) { print_r($result->fetch_row()). do { $links = $errors = $reject = array(). Available only with mysqlnd. int sec. MYSQLI_ASYNC). A mysqli_poll example <?php $link1 = mysqli_connect(). array error.MySQL Improved Extension (Mysqli) mysqli_poll Poll connections Description Object oriented style public int mysqli::poll(array read. $all_links = array($link1). array reject. Procedural style int mysqli_poll(array read. must be non-negative. $errors. $processed = 0. FALSE otherwise. Warning This function is currently not documented. Returns number of ready connections in success. int sec. int usec). 1)) { continue. } } } while ($processed < count($all_links)).58. array reject. Examples Example 2. mysqli_free_result($result). $reject. $link1->query("SELECT 'test'". Parameters read error reject sec usec Return Values Number of seconds to wait. must be non-negative. int usec). only its argument list is available. $processed++. array error. Number of microseconds to wait. 142 . foreach ($all_links as $link) { $links[] = $errors[] = $reject[] = $link. Poll connections.

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. and returns a statement handle to be used for further operations on the statement. This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions. Procedural style mysqli_stmt mysqli_prepare(mysqli link. Note You should not add a terminating semicolon or \g to the statement. string query).MySQL Improved Extension (Mysqli) ?> The above example will output: Array ( [0] => test ) See Also mysqli_query mysqli_reap_async_query 2. Parameters link query Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query. as a string. mysqli::prepare. Prepares the SQL query. The query must consist of a single SQL statement. mysqli_prepare Copyright 1997-2012 the PHP Documentation Group.9.38. • mysqli::prepare mysqli_prepare Prepare an SQL statement for execution Description Object oriented style mysqli_stmt mysqli::prepare(string query). Note 143 .

144 . $city. in the select list that names the columns to be returned by a SELECT statement. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". It's not allowed to compare marker with NULL by ? IS NULL too. /* fetch value */ $stmt->fetch(). mysqli_connect_error()). they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row).59. /* execute query */ $stmt->execute(). Examples Example 2. Return Values mysqli_prepare returns a statement object or FALSE if an error occurred. /* create a prepared statement */ if ($stmt = mysqli_prepare($link. parameters are legal only in Data Manipulation Language (DML) statements. printf("%s is in district %s\n". "my_password". However. and not in Data Definition Language (DDL) statements. /* bind result variables */ mysqli_stmt_bind_result($stmt. "world"). "world"). The latter restriction is necessary because it would be impossible to determine the parameter type. /* fetch value */ mysqli_stmt_fetch($stmt). "s". "SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt. printf("%s is in district %s\n". $district). exit(). "my_password". } /* close connection */ $mysqli->close(). $city). exit(). /* execute query */ mysqli_stmt_execute($stmt). /* create a prepared statement */ if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ $stmt->bind_param("s". or in a comparison with a column in a WHERE clause to specify a comparison value. $district). ?> Procedural style <?php $link = mysqli_connect("localhost". } $city = "Amersfoort". } $city = "Amersfoort". $city. In general. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". For example.MySQL Improved Extension (Mysqli) The markers are legal only in certain places in SQL statements. mysqli::prepare example Object oriented style <?php $mysqli = new mysqli("localhost". "my_user". /* close statement */ mysqli_stmt_close($stmt). $city). } /* close connection */ mysqli_close($link). /* close statement */ $stmt->close(). "my_user". /* bind result variables */ $stmt->bind_result($district). mysqli_connect_error()). they are not allowed for identifiers (such as table or column names). $district). or to specify both operands of a binary operator such as the = equal sign.

mysqli::query.MySQL Improved Extension (Mysqli) ?> The above examples will output: Amersfoort is in district Utrecht See Also mysqli_stmt_execute mysqli_stmt_fetch mysqli_stmt_bind_param mysqli_stmt_bind_result mysqli_stmt_close 2. 145 . This error message means “server has gone away”. mysqli_query Copyright 1997-2012 the PHP Documentation Group.9. string query. • mysqli::query mysqli_query Performs a query on the database Description Object oriented style mixed mysqli::query(string query. Performs a query against the database. using this function is identical to calling mysqli_real_query followed either by mysqli_use_result or mysqli_store_result. This error message means “server has gone away”.39. the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). Functionally. Procedural style mixed mysqli_query(mysqli link. The error message means “got a packet bigger than max_allowed_packet bytes”. libmysql on all platforms returns an error code 2006. mysqlnd on Windows returns an error code 2006. The behavior is as follows: • • • mysqlnd on Linux returns an error code of 1153. int resultmode= =MYSQLI_STORE_RESULT). int resultmode= =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.

Data inside the query should be properly escaped. } $result->close().\n". $mysqli->connect_error). "my_user". 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). /* free result set */ $result->close().3. ?> Procedural style 146 . it is possible to perform query asynchronously. All calls will return an 'out of sync' error */ if (!$mysqli->query("SET @a:='this will not work'")) { printf("Error: %s\n". } /* Select queries return a resultset */ if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) { printf("Select returned %d rows. resultmode Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. /* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n".MySQL Improved Extension (Mysqli) Parameters link query Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query string.0 Examples Description Added the ability of async queries. mysqli_poll is then used to get results from such queries. mysqli::query example Object oriented style <?php $mysqli = new mysqli("localhost". For successful SELECT.\n"). MYSQLI_USE_RESULT)) { /* Note. } /* Create table doesn't return a resultset */ if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) { printf("Table myCity successfully created. Return Values Returns FALSE on failure. "my_password". $mysqli->error). SHOW. that we can't execute any functions which interact with the server until result set was closed. By default. } /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ if ($result = $mysqli->query("SELECT * FROM City". exit().60. For other successful queries mysqli_query will return TRUE . DESCRIBE or EXPLAIN queries mysqli_query will return a mysqli_result object. } $mysqli->close(). MYSQLI_STORE_RESULT is used. Example 2. $result->num_rows). Changelog Version 5. "world").

string socket.MySQL Improved Extension (Mysqli) <?php $link = mysqli_connect("localhost". that we can't execute any functions which interact with the server until result set was closed. int flags). "world").\n". "my_password". } mysqli_free_result($result). } mysqli_close($link). MYSQLI_USE_RESULT)) { /* Note. "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) { printf("Table myCity successfully created. } /* Select queries return a resultset */ if ($result = mysqli_query($link. } /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ if ($result = mysqli_query($link. All calls will return an 'out of sync' error */ if (!mysqli_query($link. mysqli::real_connect. string dbname. ?> The above examples will output: Table myCity successfully created.40. Error: Commands out of sync. "my_user". • mysqli::real_connect mysqli_real_connect Opens a connection to a mysql server Description Object oriented style bool mysqli::real_connect(string host. Select returned 10 rows. string username. /* free result set */ mysqli_free_result($result). } /* Create table doesn't return a resultset */ if (mysqli_query($link. mysqli_connect_error()).\n"). Procedural style 147 .9. exit(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". string passwd. mysqli_error($link)). mysqli_num_rows($result)). "SET @a:='this will not work'")) { printf("Error: %s\n". mysqli_real_connect Copyright 1997-2012 the PHP Documentation Group. int port. You can't run this command now See Also mysqli_real_query mysqli_multi_query mysqli_free_result 2. "SELECT * FROM City". "SELECT Name FROM City LIMIT 10")) { printf("Select returned %d rows.

int flags). The MySQL user name.MySQL Improved Extension (Mysqli) bool mysqli_real_connect(mysqli link. int port. string username. Passing the NULL value or the string "localhost" to this parameter. Specifies the port number to attempt to connect to the MySQL server. string passwd. the local host is assumed. Parameters link host Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Can be either a host name or an IP address. There is a flags parameter. Makes all function names reserved words. How the connection is made to the MySQL database is determined by the host parameter. not the number of affected rows Allow spaces after function names. With the mysqli_options function you can set various options for connection. 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). string socket. If provided or NULL . flags With the parameter flags you can set different connection options: Table 2.5. This function differs from mysqli_connect: • • • mysqli_real_connect needs a valid object which has to be created by function mysqli_init. Specifies the socket or named pipe that should be used. Supported flags Name MYSQLI_CLIENT_COMPRESS MYSQLI_CLIENT_FOUND_ROWS MYSQLI_CLIENT_IGNORE_SPACE MYSQLI_CLIENT_INTERACTIVE Description Use compression protocol return number of matched rows. pipes will be used instead of the TCP/IP protocol. If provided will specify the default database to be used when performing queries. When possible. string dbname. string host. Establish a connection to a MySQL database engine. Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection Use SSL (encryption) MYSQLI_CLIENT_SSL Note 148 . username passwd dbname port socket Note Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server.

$user. mysqli_connect_error()). ') ' . ' . } if (!mysqli_real_connect($link. $user. if (!parent::options(MYSQLI_INIT_COMMAND. mysqli_connect_errno() . 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed').. $mysqli->close(). 'my_password'. $db->host_info . "\n". 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed'). if (!$link) { die('mysqli_init failed'). 'my_password'. } if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT. $db)) { die('Connect Error (' . 'my_password'. } if (!$mysqli->options(MYSQLI_INIT_COMMAND. Examples Example 2. If you want to execute multiple queries use the mysqli_multi_query function. Return Values Returns TRUE on success or FALSE on failure. $db->close(). 'my_db')) { die('Connect Error (' . 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed').MySQL Improved Extension (Mysqli) For security reasons the MULTI_STATEMENT flag is not supported in PHP. } if (!$mysqli->real_connect('localhost'. 'my_user'. 'my_db')) { die('Connect Error (' . "\n". $pass. 'my_user'. ?> Procedural style <?php $link = mysqli_init().61. 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'). } if (!parent::real_connect($host. } echo 'Success. } if (!mysqli_options($link.. mysqli_connect_errno() . ') ' . if (!$mysqli) { die('mysqli_init failed'). ?> Object oriented style when extending mysqli class <?php class foo_mysqli extends mysqli { public function __construct($host. $pass. ' . mysqli::real_connect example Object oriented style <?php $mysqli = mysqli_init(). 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'). $mysqli->host_info . ') ' 149 . mysqli_connect_error()). 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'). 'my_user'. $db) { parent::init(). 'my_db'). echo 'Success. MYSQLI_INIT_COMMAND. mysqli_connect_errno() . MYSQLI_OPT_CONNECT_TIMEOUT.. } if (!mysqli_options($link. } } } $db = new foo_mysqli('localhost'.. } if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT. 'localhost'.

. mysqli::real_escape_string. mysqli_close($link). This function is used to create a legal SQL string that you can use in an SQL statement. } echo 'Success.. string escapestr).MySQL Improved Extension (Mysqli) ..41. Libmysql uses the default charset set in the my. taking into account the current charset of the connection Description Object oriented style string mysqli::escape_string(string escapestr)..9. ?> The above examples will output: Success.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect. Procedural style string mysqli_real_escape_string(mysqli link. mysqli_get_host_info($link) . ' . "\n". The given string is encoded to an escaped SQL string. See Also mysqli_connect mysqli_init mysqli_options mysqli_ssl_set mysqli_close 2. • mysqli::real_escape_string mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement. taking into account the current character set of the connection. This charset is sent during connection hand-shake/authentication. mysqli_connect_error()). MySQL host info: localhost via TCP/IP Notes Note MySQLnd always assumes the server default charset. but after mysqli_init. which mysqlnd will use. string mysqli::real_escape_string(string escapestr). mysqli_real_escape_string Copyright 1997-2012 the PHP Documentation Group. Parameters 150 .

\. $mysqli->affected_rows). } mysqli_close($link). "INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n". 151 .\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* this query with escaped $city will work */ if (mysqli_query($link. cause we didn't escape $city */ if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n". mysqli_connect_error()). } $city = mysqli_real_escape_string($link. $city = "'s Hertogenbosch". Return Values Returns an escaped string.MySQL Improved Extension (Mysqli) link escapestr Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The string to be escaped. "CREATE TEMPORARY TABLE myCity LIKE City"). exit(). /* this query will fail. } mysqli_query($link. $mysqli->sqlstate). /* this query with escaped $city will work */ if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted. \n. and Control-Z. mysqli_affected_rows($link)). mysqli_connect_error()). "INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted. "my_password". "my_user". "world"). mysqli_sqlstate($link)). } $mysqli->close(). } $city = $mysqli->real_escape_string($city). \r. ". ?> The above examples will output: Error: 42000 1 Row inserted.62. cause we didn't escape $city */ if (!mysqli_query($link. '. "my_password". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".\n". "world"). Examples Example 2. } $mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"). ?> Procedural style <?php $link = mysqli_connect("localhost". exit(). mysqli::real_escape_string example Object oriented style <?php $mysqli = new mysqli("localhost". $city = "'s Hertogenbosch". $city). Characters encoded are NUL (ASCII 0). "my_user". /* this query will fail.

Data inside the query should be properly escaped.42. mysqli_reap_async_query 152 . See Also mysqli_character_set_name 2. mysqli::reap_async_query. as a string. mysqli::real_query. • mysqli::real_query mysqli_real_query Execute an SQL query Description Object oriented style bool mysqli::real_query(string query). Parameters link query Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query.43. note that the arguments of mysqli_real_escape_string differ from what mysql_real_escape_string expects. In order to determine if a given query should return a result set or not. string query).9.MySQL Improved Extension (Mysqli) Notes Note For those accustomed to using mysql_real_escape_string. Return Values Returns TRUE on success or FALSE on failure. mysqli_real_query Copyright 1997-2012 the PHP Documentation Group. See Also mysqli_query mysqli_store_result mysqli_use_result 2. 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. The link identifier comes first in mysqli_real_escape_string. see mysqli_field_count.9. whereas the string to be escaped comes first in mysql_real_escape_string. Procedural style bool mysqli_real_query(mysqli link.

mysqli_refresh Copyright 1997-2012 the PHP Documentation Group.44.9. Available only with mysqlnd. Procedural style mysqli_result mysqli_reap_async_query(mysql link). FALSE otherwise. 153 . Get result from async query. • mysqli::refresh mysqli_refresh Refreshes Description Object oriented style public bool mysqli::refresh(int options). Warning This function is currently not documented. See Also mysqli_poll 2. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns mysqli_result in success.MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. mysqli::refresh. Procedural style int mysqli_refresh(resource link. • mysqli::reap_async_query mysqli_reap_async_query Get result from async query Description Object oriented style public mysqli_result mysqli::reap_async_query(). only its argument list is available. int options).

Examples Example 2.MySQL Improved Extension (Mysqli) Flushes tables or caches.9.45. using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation. Return Values TRUE if the refresh was a success. • mysqli::rollback mysqli_rollback Rolls back current transaction Description Object oriented style bool mysqli::rollback(). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns TRUE on success or FALSE on failure.63. mysqli_rollback Copyright 1997-2012 the PHP Documentation Group. See also the official MySQL Refresh documentation. or resets the replication server information. mysqli::rollback example Object oriented style 154 . otherwise FALSE See Also mysqli_poll 2. Rollbacks the current transaction for the database. mysqli::rollback. Parameters link options Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The options to refresh. Procedural style bool mysqli_rollback(mysqli link).

printf("%d rows in table myCity (after rollback). printf("%d rows in table myCity. /* commit insert */ mysqli_commit($link). ?> Procedural style <?php $link = mysqli_connect("localhost". exit(). "my_user". } /* disable autocommit */ $mysqli->autocommit(FALSE). exit(). /* Free result */ mysqli_free_result($result). mysqli_query($link. 155 . mysqli_query($link. mysqli_query($link. if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(). /* Free result */ $result->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".\n". /* commit insert */ $mysqli->commit(). $row[0]). if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(). "my_password". } /* disable autocommit */ mysqli_autocommit($link. ?> The above examples will output: 0 rows in table myCity. } /* Rollback */ $mysqli->rollback(). /* Free result */ $result->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). "CREATE TABLE myCity LIKE City"). mysqli_close($link). "my_user". $row[0]). "ALTER TABLE myCity Type=InnoDB"). "DROP TABLE myCity"). $mysqli->close(). "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result). } /* Drop table myCity */ mysqli_query($link. "DELETE FROM myCity"). "world"). } /* Rollback */ mysqli_rollback($link). $mysqli->query("CREATE TABLE myCity LIKE City"). FALSE).MySQL Improved Extension (Mysqli) <?php $mysqli = new mysqli("localhost". /* delete all rows */ $mysqli->query("DELETE FROM myCity"). if ($result = mysqli_query($link.\n". } /* Drop table myCity */ $mysqli->query("DROP TABLE myCity").\n". /* delete all rows */ mysqli_query($link. 50 rows in table myCity (after rollback). if ($result = mysqli_query($link. mysqli_connect_error()). "my_password". $mysqli->query("ALTER TABLE myCity Type=InnoDB"). $row[0]). "world").\n". printf("%d rows in table myCity. "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result). $row[0]). "INSERT INTO myCity SELECT * FROM City LIMIT 50"). $mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50"). printf("%d rows in table myCity (after rollback). /* Free result */ mysqli_free_result($result).

Warning This function has been DEPRECATED and REMOVED as of PHP 5. Warning This function is currently not documented. MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type.9. UPDATE and similar are master queries.9. mysqli_select_db Copyright 1997-2012 the PHP Documentation Group. and FLUSH. SELECT is slave. only its argument list is available. REPAIR and similar are admin. string dbname). string query). • mysqli::rpl_query_type mysqli_rpl_query_type Returns RPL query type Description Object oriented style int mysqli::rpl_query_type(string query). mysqli::select_db. 2.3. 156 .47.46. Procedural style bool mysqli_select_db(mysqli link. Returns MYSQLI_RPL_MASTER . Procedural style int mysqli_rpl_query_type(mysqli link. • mysqli::select_db mysqli_select_db Selects the default database for database queries Description Object oriented style bool mysqli::select_db(string dbname).MySQL Improved Extension (Mysqli) See Also mysqli_commit mysqli_autocommit 2. mysqli_rpl_query_type Copyright 1997-2012 the PHP Documentation Group. mysqli::rpl_query_type.0. INSERT. Selects the default database to be used when performing queries against the database connection.

mysqli_free_result($result). "my_password". "test"). "world"). "SELECT DATABASE()")) { $row = mysqli_fetch_row($result). mysqli::select_db example Object oriented style <?php $mysqli = new mysqli("localhost". You can select the default database with 4th parameter in mysqli_connect. "my_user".64. "SELECT DATABASE()")) { $row = mysqli_fetch_row($result).\n". printf("Default database is %s. exit(). "my_password". } $mysqli->close(). Parameters link dbname Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The database name. /* return name of current default database */ if ($result = $mysqli->query("SELECT DATABASE()")) { $row = $result->fetch_row(). "test"). Returns TRUE on success or FALSE on failure. $row[0]). } /* return name of current default database */ if ($result = mysqli_query($link. printf("Default database is %s.\n". mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". ?> 157 .\n". $result->close().\n". $row[0]). } /* return name of current default database */ if ($result = $mysqli->query("SELECT DATABASE()")) { $row = $result->fetch_row(). } /* change db to world db */ mysqli_select_db($link. "my_user". printf("Default database is %s. $result->close(). $row[0]). /* return name of current default database */ if ($result = mysqli_query($link. $row[0]). ?> Procedural style <?php $link = mysqli_connect("localhost". } mysqli_close($link).MySQL Improved Extension (Mysqli) Note This function should only be used to change the default database for the connection. mysqli_connect_error()). Examples Example 2. printf("Default database is %s. mysqli_free_result($result). } /* change db to world db */ $mysqli->select_db("world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". exit().

3. mysqli::set_charset. See Also mysqli_connect mysqli_real_connect 2. • mysqli::send_query mysqli_send_query Send the query and return Description Object oriented style bool mysqli::send_query(string query).49. string query). Procedural style bool mysqli_send_query(mysqli link. Warning This function is currently not documented.9.MySQL Improved Extension (Mysqli) The above examples will output: Default database is test. mysqli_send_query Copyright 1997-2012 the PHP Documentation Group. • mysqli::set_charset mysqli_set_charset Sets the default client character set Description Object oriented style bool mysqli::set_charset(string charset).0. mysqli_set_charset Copyright 1997-2012 the PHP Documentation Group. mysqli::send_query. only its argument list is available. 2. Default database is world. 158 .48. Warning This function has been DEPRECATED and REMOVED as of PHP 5.9.

mysqli_connect_error()).MySQL Improved Extension (Mysqli) Procedural style bool mysqli_set_charset(mysqli link.1.6 or above). "utf8")) { printf("Error loading character set utf8: %s\n". string charset). Notes Note To use this function on a Windows platform you need MySQL client library version 4. mysqli::set_charset example Object oriented style <?php $mysqli = new mysqli("localhost". Parameters link charset Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The charset to be set as default. } else { printf("Current character set: %s\n". "test"). 'my_password'. mysqli_connect_error()). ?> Procedural style <?php $link = mysqli_connect('localhost'. "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } /* change character set to utf8 */ if (!$mysqli->set_charset("utf8")) { printf("Error loading character set utf8: %s\n".. $mysqli->character_set_name()).0 you need 5. } /* change character set to utf8 */ if (!mysqli_set_charset($link. $mysqli->error). Examples Example 2. exit(). 159 . } else { printf("Current character set: %s\n". mysqli_character_set_name($link)). 'my_user'.65. Returns TRUE on success or FALSE on failure. exit().0. mysqli_error($link)). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Sets the default character set to be used when sending data from and to the database server. Using mysqli::query to execute SET NAMES .11 or above (for MySQL 5. "my_password". Note This is the preferred way to change the charset. 'test'). } $mysqli->close(). is not recommended.

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler. • mysqli::set_local_infile_default mysqli_set_local_infile_default Unsets user defined handler for load local infile command Description void mysqli_set_local_infile_default(mysqli link). Parameters link Return Values No value is returned. mysqli::set_local_infile_handler. ?> The above examples will output: Current character set: utf8 See Also mysqli_character_set_name mysqli_real_escape_string List of character sets that MySQL supports 2. mysqli::set_local_infile_default. 160 . mysqli_set_local_infile_handler Copyright 1997-2012 the PHP Documentation Group. Examples Procedural style only: A link identifier returned by mysqli_connect or mysqli_init See mysqli_set_local_infile_handler examples See Also mysqli_set_local_infile_handler 2.9.50.51. mysqli_set_local_infile_default Copyright 1997-2012 the PHP Documentation Group.9.MySQL Improved Extension (Mysqli) } mysqli_close($link).

MySQL Improved Extension (Mysqli)

mysqli::set_local_infile_handler mysqli_set_local_infile_handler Set callback function for LOAD DATA LOCAL INFILE command

Description Object oriented style
bool mysqli::set_local_infile_handler(mysqli link, callback read_func);

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

Example 2.66. mysqli::set_local_infile_handler example
Object oriented style
<?php $db = mysqli_init(); $db->real_connect("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";

161

MySQL Improved Extension (Mysqli)

$db->set_local_infile_handler("callme"); $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1"); $db->set_local_infile_default(); $res = $db->query("SELECT * FROM t1"); echo "\nResult:\n"; while ($row = $res->fetch_assoc()) { echo join(",", $row)."\n"; } ?>

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"; } ?>

The above examples will output:
Input: 23,foo 42,bar Output: 23,FOO 42,BAR

See Also mysqli_set_local_infile_default

2.9.52. mysqli::$sqlstate, mysqli_sqlstate
Copyright 1997-2012 the PHP Documentation Group. • mysqli::$sqlstate mysqli_sqlstate Returns the SQLSTATE error from previous MySQL operation Description Object oriented style
string mysqli->sqlstate ;

162

MySQL Improved Extension (Mysqli)

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

link Return Values

Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. Examples

Example 2.67. $mysqli->sqlstate example
Object oriented style
<?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(); } /* Table City already exists, so we should get an error */ if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) { printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate); } $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(); } /* 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); ?>

The above examples will output:
Error - SQLSTATE 42S01.

163

MySQL Improved Extension (Mysqli)

See Also mysqli_errno mysqli_error

2.9.53. mysqli::ssl_set, mysqli_ssl_set
Copyright 1997-2012 the PHP Documentation Group. • mysqli::ssl_set mysqli_ssl_set Used for establishing secure connections using SSL Description Object oriented style
bool mysqli::ssl_set(string string string string string key, cert, ca, capath, cipher);

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 before PHP 5.3.3, 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

link key cert ca capath cipher

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 164

MySQL Improved Extension (Mysqli)

mysqli_options mysqli_real_connect

2.9.54. mysqli::stat, mysqli_stat
Copyright 1997-2012 the PHP Documentation Group. • mysqli::stat mysqli_stat Gets the current system status Description Object oriented style
string mysqli::stat();

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

link Return Values

Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

A string describing the server status. FALSE if an error occurred. Examples

Example 2.68. mysqli::stat example
Object oriented style
<?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(); } printf ("System status: %s\n", $mysqli->stat()); $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();

165

Parameters link Return Values Returns an object.55. ?> The above examples will output: System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0 Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19. mysqli::stmt_init. Allocates and initializes a statement object suitable for mysqli_stmt_prepare. • mysqli::stmt_init mysqli_stmt_init Initializes a statement and returns an object for use with mysqli_stmt_prepare Description Object oriented style mysqli_stmt mysqli::stmt_init().56. mysqli_close($link). Procedural style mysqli_stmt mysqli_stmt_init(mysqli link).632 Memory in use: 8496K Max memory used: 8560K See Also mysqli_get_server_info 2. mysqli_stat($link)). See Also mysqli_stmt_prepare Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 2.MySQL Improved Extension (Mysqli) } printf("System status: %s\n". mysqli_store_result 166 . mysqli_stmt_init Copyright 1997-2012 the PHP Documentation Group. mysqli::store_result.9. Note Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare was called.9.

for example an INSERT statement).57. 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. mysqli_thread_id Copyright 1997-2012 the PHP Documentation Group. Examples See mysqli_multi_query. Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns a buffered result object or FALSE if an error occurred. • mysqli::store_result mysqli_store_result Transfers a result set from the last query Description Object oriented style mysqli_result mysqli::store_result(). If mysqli_field_count returns a non-zero value. the statement should have produced a non-empty result set. if mysqli_errno returns a non zero value. when transferring large result sets using the mysqli_store_result this becomes particularly important. or if mysqli_field_count returns a non zero value. 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.MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. 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). mysqli::$thread_id.9. See Also mysqli_real_query mysqli_use_result 2. 167 . 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. Note mysqli_store_result returns FALSE in case the query didn't return a result set (if the query was.

Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Returns the Thread ID for the current connection. "world"). To kill a running query you can use the SQL command KILL QUERY processid. mysqli_connect_error()). /* Kill connection */ $mysqli->kill($thread_id). The mysqli_thread_id function returns the thread ID for the current connection which can then be killed using the mysqli_kill function. "my_user". If the connection is lost and you reconnect with mysqli_ping. } /* determine our thread id */ $thread_id = $mysqli->thread_id. if the connection is broken and then re-established a new thread ID will be assigned. $mysqli->error). ?> Procedural style 168 . exit. "my_password".69.MySQL Improved Extension (Mysqli) • mysqli::$thread_id mysqli_thread_id Returns the thread ID for the current connection Description Object oriented style int mysqli->thread_id . Examples Example 2. exit(). the thread ID will be other. Therefore you should get the thread ID only when you need it. /* This should produce an error */ if (!$mysqli->query("CREATE TABLE myCity LIKE City")) { printf("Error: %s\n". Procedural style int mysqli_thread_id(mysqli link). Hence. } /* close connection */ $mysqli->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Note The thread ID is assigned on a connection-by-connection basis. $mysqli->thread_id example Object oriented style <?php $mysqli = new mysqli("localhost".

$thread_id). "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n". /* This should produce an error */ if (!mysqli_query($link. 2. Return Values TRUE if the client library is thread-safe. • mysqli::thread_safe mysqli_thread_safe Returns whether thread safety is given or not Description Procedural style bool mysqli_thread_safe(). ?> The above examples will output: Error: MySQL server has gone away See Also mysqli_kill 2. mysqli_use_result Copyright 1997-2012 the PHP Documentation Group. "world"). "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Tells whether the client library is compiled as thread-safe. "my_password". mysqli_thread_safe Copyright 1997-2012 the PHP Documentation Group. mysqli_connect_error()).9. mysqli::use_result. mysqli_error($link)).59. exit().9. otherwise FALSE . mysqli::thread_safe. exit.MySQL Improved Extension (Mysqli) <?php $link = mysqli_connect("localhost".58. /* Kill connection */ mysqli_kill($link. } /* determine our thread id */ $thread_id = mysqli_thread_id($link). } /* close connection */ mysqli_close($link). • mysqli::use_result mysqli_use_result Initiate a result set retrieval 169 .

Either this or the mysqli_store_result function must be called before the results of a query can be retrieved.". } /* close connection */ $mysqli->close(). "world"). /* check connection */ if (mysqli_connect_errno()) { 170 . Procedural style mysqli_result mysqli_use_result(mysqli link). "my_user". } $result->close(). Examples Example 2. 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. "my_password". "my_user". One should not use mysqli_use_result if a lot of processing on the client side is performed. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query function on the database connection. ?> Procedural style <?php $link = mysqli_connect("localhost".70. exit().MySQL Improved Extension (Mysqli) Description Object oriented style mysqli_result mysqli::use_result(). "my_password". mysqli::use_result example Object oriented style <?php $mysqli = new mysqli("localhost". } $query = "SELECT CURRENT_USER(). To use this functionality.= "SELECT Name FROM City ORDER BY ID LIMIT 20. "world"). 5". and one or the other must be called to prevent the next query on that database connection from failing. mysqli_connect_error()). the result set must be stored using mysqli_store_result. $row[0]). 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. $query . } /* print divider */ if ($mysqli->more_results()) { printf("-----------------\n"). } } while ($mysqli->next_result()). /* execute multi query */ if ($mysqli->multi_query($query)) { do { /* store first result set */ if ($result = $mysqli->use_result()) { while ($row = $result->fetch_row()) { printf("%s\n".

} /* print divider */ if (mysqli_more_results($link)) { printf("-----------------\n"). mysqli::$warning_count.9. $query)) { do { /* store first result set */ if ($result = mysqli_use_result($link)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n". $query . • mysqli::$warning_count mysqli_warning_count Returns the number of warnings from the last query for the given link Description Object oriented style int mysqli->warning_count .= "SELECT Name FROM City ORDER BY ID LIMIT 20.". } /* close connection */ mysqli_close($link). 5".60. mysqli_warning_count Copyright 1997-2012 the PHP Documentation Group. Returns the number of warnings from the last query in the connection. exit(). $row[0]).MySQL Improved Extension (Mysqli) printf("Connect failed: %s\n". Note 171 . ?> The above examples will output: my_user@localhost ----------------Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer See Also mysqli_real_query mysqli_store_result 2. } $query = "SELECT CURRENT_USER(). } } while (mysqli_next_result($link)). } mysqli_free_result($result). mysqli_connect_error()). /* execute multi query */ if (mysqli_multi_query($link. Procedural style int mysqli_warning_count(mysqli link).

$result->close(). Examples Example 2. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".71. } } /* close connection */ $mysqli->close(). "my_user". exit(). printf("%s (%d): %s\n".MySQL Improved Extension (Mysqli) For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count]. Name) VALUES('GBR'. 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')". mysqli_connect_error()). exit(). "my_password". mysqli_connect_error()). "world"). $query). $row[0]. $row[2]). } mysqli_query($link. mysqli_query($link. "CREATE TABLE myCity LIKE City"). printf("%s (%d): %s\n". /* a remarkable city in Wales */ $query = "INSERT INTO myCity (CountryCode. } $mysqli->query("CREATE TABLE myCity LIKE City"). Name) VALUES('GBR'. ?> The above examples will output: Warning (1264): Data truncated for column 'Name' at row 1 172 . 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')". $mysqli->warning_count example Object oriented style <?php $mysqli = new mysqli("localhost". $row[1]. ?> Procedural style <?php $link = mysqli_connect("localhost". $row[1]. if (mysqli_warning_count($link)) { if ($result = mysqli_query($link. "SHOW WARNINGS")) { $row = mysqli_fetch_row($result). Parameters link Return Values Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Number of warnings or zero if there are no warnings. "world"). } } /* close connection */ mysqli_close($link). $mysqli->query($query). $row[0]. /* a remarkable long city name in Wales */ $query = "INSERT INTO myCity (CountryCode. mysqli_free_result($result). $row[2]). "my_password". "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($mysqli->warning_count) { if ($result = $mysqli->query("SHOW WARNINGS")) { $row = $result->fetch_row().

bool mysqli_stmt::fetch().).10. 173 . mysqli_stmt { mysqli_stmt Properties int mysqli_stmt->affected_rows . void mysqli_stmt::free_result(). int mysqli_stmt->num_rows .. bool mysqli_stmt::bind_param(string types. void mysqli_stmt::data_seek(int offset).. string mysqli_stmt->sqlstate . bool mysqli_stmt::execute()..). int mysqli_stmt->insert_id .. The mysqli_stmt class (mysqli_stmt) Copyright 1997-2012 the PHP Documentation Group. bool mysqli_stmt::close(). bool mysqli_stmt::bind_result(mixed var1. int mysqli_stmt->param_count . bool mysqli_stmt::attr_set(int attr. Represents a prepared statement. int mysqli_stmt->errno . mixed . string mysqli_stmt->error . mixed var1. mixed . int mysqli_stmt->field_count . Methods int mysqli_stmt::attr_get(int attr). int mode). mysqli_result mysqli_stmt::get_result().MySQL Improved Extension (Mysqli) See Also mysqli_errno mysqli_error mysqli_sqlstate 2.

the number of affected rows will be returned as a string value. Returns the number of rows affected by INSERT. mysqli_stmt_affected_rows Copyright 1997-2012 the PHP Documentation Group. bool mysqli_stmt::send_long_data(int param_nr. or inserted by the last executed statement Description Object oriented style int mysqli_stmt->affected_rows .10. use mysqli_stmt_num_rows instead. -1 indicates that the query has returned an error. Zero indicates that no records where updated for an UPDATE/DELETE statement. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. • mysqli_stmt::$affected_rows mysqli_stmt_affected_rows Returns the total number of rows changed. mysqli_stmt::$affected_rows. UPDATE.1. mixed mysqli_stmt::prepare(string query). deleted. NULL indicates an invalid argument was supplied to the function. mysqli_result mysqli_stmt::result_metadata(). This function only works with queries which update a table. Procedural style int mysqli_stmt_affected_rows(mysqli_stmt stmt). bool mysqli_stmt::store_result(). string data). } 2. bool mysqli_stmt::reset(). or DELETE query. An integer greater than zero indicates the number of rows affected or retrieved. no rows matched the WHERE clause in the query or that no query has yet been executed. Note If the number of affected rows is greater than maximal PHP int value.MySQL Improved Extension (Mysqli) object mysqli_stmt::get_warnings(mysqli_stmt stmt). Examples 174 . In order to get the number of rows from a SELECT query.

mysqli_stmt_bind_param($stmt. "my_password". $code). } /* close connection */ mysqli_close($link). mysqli_connect_error()). $stmt->bind_param("s". ?> The above examples will output: rows inserted: 17 See Also mysqli_stmt_num_rows mysqli_prepare 2. mysqli_connect_error()). } /* create temp table */ mysqli_query($link.2. exit(). /* execute statement */ $stmt->execute(). /* prepare statement */ if ($stmt = mysqli_prepare($link. $stmt->affected_rows). $query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?". /* close statement */ $stmt->close().MySQL Improved Extension (Mysqli) Example 2. } /* create temp table */ $mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country"). mysqli_stmt_attr_get 175 . /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". printf("rows inserted: %d\n". "CREATE TEMPORARY TABLE myCountry LIKE Country"). mysqli_stmt::attr_get. } /* close connection */ $mysqli->close(). $query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?". Procedural style <?php $link = mysqli_connect("localhost". $query)) { /* Bind variable for placeholder */ $code = 'A%'. /* prepare statement */ if ($stmt = $mysqli->prepare($query)) { /* Bind variable for placeholder */ $code = 'A%'.10. "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* close statement */ mysqli_stmt_close($stmt). "my_user".72. ?> Example 2. printf("rows inserted: %d\n". mysqli_stmt_affected_rows($stmt)). exit(). "s". "world"). "my_password". /* execute statement */ mysqli_stmt_execute($stmt). Object oriented style <?php $mysqli = new mysqli("localhost". $code).73.

int mode). int mode).3. mysqli_stmt::attr_set.MySQL Improved Extension (Mysqli) Copyright 1997-2012 the PHP Documentation Group. int attr. Procedural style int mysqli_stmt_attr_get(mysqli_stmt stmt. otherwise returns the value of the attribute. Parameters 176 . Procedural style bool mysqli_stmt_attr_set(mysqli_stmt stmt. int attr). Parameters stmt attr Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. mysqli_stmt_attr_set Copyright 1997-2012 the PHP Documentation Group. • mysqli_stmt::attr_get mysqli_stmt_attr_get Used to get the current value of a statement attribute Description Object oriented style int mysqli_stmt::attr_get(int attr). Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes. Returns FALSE if the attribute is not found. The attribute that you want to get. Gets the current value of a statement attribute.10. 2. • mysqli_stmt::attr_set mysqli_stmt_attr_set Used to modify the behavior of a prepared statement Description Object oriented style bool mysqli_stmt::attr_set(int attr.

6.MySQL Improved Extension (Mysqli) stmt attr Procedural style only: A statement identifier returned by mysqli_stmt_init. mysqli_stmt_store_result is unnecessary. it closes the cursor before opening a new one.. The default is 1. The attribute that you want to set. Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare. allowed packet size (max_allowed_packet). Note If data size of a variable exceeds max. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY. you have to specify b in types and use mysqli_stmt_send_long_data to send the data in packets. mode The value to assign to the attribute.). Attribute values Character MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH MYSQLI_STMT_ATTR_CURSOR_TYPE Description If set to 1..10.). Procedural style bool mysqli_stmt_bind_param(mysqli_stmt stmt. causes mysqli_stmt_store_result to update the metadata MYSQL_FIELD->max_length value. mysqli_stmt_reset also closes any open cursor before preparing the statement for reexecution. If you open a cursor for a prepared statement. mixed . Type of cursor to open for statement when mysqli_stmt_execute is invoked. string types. It can have one of the following values: Table 2. If there is already an open cursor from a previous mysqli_stmt_execute call.. mysqli_stmt::bind_param. mixed var1.. mysqli_stmt_bind_param Copyright 1997-2012 the PHP Documentation Group. mixed var1. mysqli_stmt_free_result closes any open cursor.4. mode can be in the range from 1 to the maximum value of unsigned long. Number of rows to fetch from server at a time when using a cursor. 2. mixed . • mysqli_stmt::bind_param mysqli_stmt_bind_param Binds variables to a prepared statement as parameters Description Object oriented style bool mysqli_stmt::bind_param(string types. a cursor is opened for the statement when you invoke mysqli_stmt_execute. MYSQLI_STMT_ATTR_PREFETCH_ROWS If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY. 177 .

7. whereas call_user_func_array can accept as a parameter a list of variables that can represent references or values. $stmt->bind_param('sssd'. var1 Return Values Returns TRUE on success or FALSE on failure.2.74. $percent). $code. /* close statement and connection */ $stmt->close(). ?> Example 2. 'my_password'. $official = "F". ?. Object oriented style <?php $mysqli = new mysqli('localhost'. $language. 'world'). ?)"). /* execute prepared statement */ $stmt->execute(). $official. ?.MySQL Improved Extension (Mysqli) Note Care must be taken when using mysqli_stmt_bind_param in conjunction with call_user_func_array. /* close connection */ $mysqli->close().\n". /* Clean up table CountryLanguage */ $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'"). Parameters stmt types Procedural style only: A statement identifier returned by mysqli_stmt_init. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style <?php 178 . exit(). $code = 'DEU'. printf("%d Row deleted. printf("%d Row inserted. Examples Example 2. $mysqli->affected_rows). 'my_user'. mysqli_connect_error()). $language = 'Bavarian'. Note that mysqli_stmt_bind_param requires parameters to be passed by reference. $stmt->affected_rows). $percent = 11.75. Type specification chars Character i d s b Description corresponding variable has type integer corresponding variable has type double corresponding variable has type string corresponding variable is a blob and will be sent in packets The number of variables and length of string types must match the parameters in the statement.\n". } $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?. A string that contains one or more characters which specify the types for the corresponding bind variables: Table 2.

$language = 'Bavarian'. 1 Row deleted. 'world'). $official = "F".). ?> The above examples will output: 1 Row inserted. $code.). /* execute prepared statement */ mysqli_stmt_execute($stmt). ?. "DELETE FROM CountryLanguage WHERE Language='Bavarian'"). ?.10. Binds columns in the result set to variables. /* Clean up table CountryLanguage */ mysqli_query($link.. mixed var1. printf("%d Row inserted. $code = 'DEU'. 'sssd'. mysqli_stmt_affected_rows($stmt)). } $stmt = mysqli_prepare($link. 'my_password'. mysqli_stmt::bind_result. See Also mysqli_stmt_bind_result mysqli_stmt_execute mysqli_stmt_fetch mysqli_prepare mysqli_stmt_send_long_data mysqli_stmt_errno mysqli_stmt_error 2. 'my_user'.2. $language.\n". mysqli_stmt_bind_param($stmt. $percent). $official. exit(). mixed .5. • mysqli_stmt::bind_result mysqli_stmt_bind_result Binds variables to a prepared statement for result storage Description Object oriented style bool mysqli_stmt::bind_result(mixed var1.MySQL Improved Extension (Mysqli) $link = mysqli_connect('localhost'. mysqli_affected_rows($link)). Procedural style bool mysqli_stmt_bind_result(mysqli_stmt stmt... mysqli_connect_error()). $percent = 11. /* close connection */ mysqli_close($link).. /* check connection */ if (!$link) { printf("Connect failed: %s\n". mysqli_stmt_bind_result Copyright 1997-2012 the PHP Documentation Group.\n". "INSERT INTO CountryLanguage VALUES (?. 179 . mixed . /* close statement and connection */ mysqli_stmt_close($stmt). ?)"). printf("%d Row deleted.

/* fetch values */ while ($stmt->fetch()) { printf("%s %s\n". $col2). } /* prepare statement */ if ($stmt = mysqli_prepare($link. Object oriented style <?php $mysqli = new mysqli("localhost". $col1. . "world"). exit(). "my_user". /* fetch values */ while (mysqli_stmt_fetch($stmt)) { printf("%s %s\n". Note Note that all columns must be bound after mysqli_stmt_execute and prior to calling mysqli_stmt_fetch. even after a result set has been partially retrieved. $col1. $col1. Depending on column types bound variables can silently change to the corresponding PHP type. mysqli_connect_error()). Name FROM Country ORDER BY Name LIMIT 5")) { mysqli_stmt_execute($stmt). /* check connection */ if (!$link) { printf("Connect failed: %s\n". the MySQL client/server protocol places the data for the bound columns into the specified variables var1.... } /* close connection */ $mysqli->close(). exit(). "world"). "SELECT Code. /* bind variables to prepared statement */ $stmt->bind_result($col1. if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). Returns TRUE on success or FALSE on failure. The new binding takes effect the next time mysqli_stmt_fetch is called. $col2). "my_password". A column can be bound or rebound at any time. } /* close statement */ 180 . "my_user".77. $col2). } /* prepare statement */ if ($stmt = $mysqli->prepare("SELECT Code.MySQL Improved Extension (Mysqli) When mysqli_stmt_fetch is called to fetch data. /* bind variables to prepared statement */ mysqli_stmt_bind_result($stmt.76. ?> Example 2. "my_password". Procedural style <?php $link = mysqli_connect("localhost". Name FROM Country ORDER BY Name LIMIT 5")) { $stmt->execute(). The variable to be bound. Examples Example 2. Parameters stmt var1 Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. } /* close statement */ $stmt->close(). $col2).

Procedural style bool mysqli_stmt_close(mysqli_stmt stmt). mysqli_stmt_close also deallocates the statement handle. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. • mysqli_stmt::close mysqli_stmt_close Closes a prepared statement Description Object oriented style bool mysqli_stmt::close(). Returns TRUE on success or FALSE on failure. 181 .6.10. If the current statement has pending or unread results. ?> The above examples will output: AFG ALB DZA ASM AND Afghanistan Albania Algeria American Samoa Andorra 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 2. mysqli_stmt_close Copyright 1997-2012 the PHP Documentation Group. } /* close connection */ mysqli_close($link). mysqli_stmt::close. this function cancels them so that the next query can be executed.MySQL Improved Extension (Mysqli) mysqli_stmt_close($stmt). Closes a prepared statement.

"my_password".10. • mysqli_stmt::data_seek mysqli_stmt_data_seek Seeks to an arbitrary row in statement result set Description Object oriented style void mysqli_stmt::data_seek(int offset). if ($stmt = $mysqli->prepare($query)) { /* execute query */ $stmt->execute().78. mysqli_stmt_data_seek Copyright 1997-2012 the PHP Documentation Group. } $query = "SELECT Name.7. mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".MySQL Improved Extension (Mysqli) See Also mysqli_prepare 2. Procedural style void mysqli_stmt_data_seek(mysqli_stmt stmt. /* store result */ $stmt->store_result(). mysqli_stmt_store_result must be called prior to mysqli_stmt_data_seek. Must be between zero and the total number of rows minus one (0. mysqli_stmt_num_rows . exit().1). mysqli_stmt::data_seek. "my_user". $code). /* seek to row no.. "world"). Parameters stmt offset Procedural style only: A statement identifier returned by mysqli_stmt_init. int offset). 400 */ $stmt->data_seek(399). Return Values No value is returned. /* fetch values */ 182 . /* bind result variables */ $stmt->bind_result($name. Seeks to an arbitrary result pointer in the statement result set. CountryCode FROM City ORDER BY Name". Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". Examples Example 2.

mysqli_stmt::$errno. "my_password". /* store result */ mysqli_stmt_store_result($stmt). } /* close connection */ $mysqli->close(). $code). CountryCode FROM City ORDER BY Name". exit(). $code). if ($stmt = mysqli_prepare($link.10. Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". /* seek to row no.8. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* close statement */ $stmt->close(). /* fetch values */ mysqli_stmt_fetch($stmt). $name. printf ("City: %s Countrycode: %s\n". "world"). mysqli_stmt_errno Copyright 1997-2012 the PHP Documentation Group. 399). ?> Example 2. $code). $name. 400 */ mysqli_stmt_data_seek($stmt. /* close statement */ mysqli_stmt_close($stmt). printf ("City: %s Countrycode: %s\n". } $query = "SELECT Name. mysqli_connect_error()).79. $query)) { /* execute query */ mysqli_stmt_execute($stmt). } /* close connection */ mysqli_close($link).MySQL Improved Extension (Mysqli) $stmt->fetch(). • mysqli_stmt::$errno mysqli_stmt_errno Returns the error code for the most recent statement call Description Object oriented style 183 . /* bind result variables */ mysqli_stmt_bind_result($stmt. "my_user". ?> The above examples will output: City: Benin City Countrycode: NGA See Also mysqli_prepare 2. $name.

Code FROM myCountry ORDER BY Name". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "INSERT INTO myCountry SELECT * FROM Country"). Zero means no error occurred. $stmt->errno). mysqli_connect_error()).\n". Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". "my_password". Client error message numbers are listed in the MySQL errmsg. exit(). exit(). An error code value.MySQL Improved Extension (Mysqli) int mysqli_stmt->errno . $query = "SELECT Name. "my_user". ?> Example 2. /* execute query */ 184 . Examples Example 2. } $mysqli->query("CREATE TABLE myCountry LIKE Country"). Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error. } mysqli_query($link. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. if ($stmt = mysqli_prepare($link. mysqli_connect_error()). printf("Error: %d. $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"). server error message numbers are listed in mysqld_error.h. /* execute query */ $stmt->execute().h header file. $query)) { /* drop table */ mysqli_query($link. Code FROM myCountry ORDER BY Name".81. if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry"). "my_password". "CREATE TABLE myCountry LIKE Country"). "my_user". /* close statement */ $stmt->close(). Returns the error code for the most recently invoked statement function that can succeed or fail. } /* close connection */ $mysqli->close(). $query = "SELECT Name. Procedural style int mysqli_stmt_errno(mysqli_stmt stmt). "world"). "DROP TABLE myCountry"). "world"). mysqli_query($link.txt.80. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".

Object oriented style <?php /* Open a connection */ 185 . printf("Error: %d. mysqli_stmt_error Copyright 1997-2012 the PHP Documentation Group. A string that describes the error. mysqli_stmt::$error. mysqli_stmt_errno($stmt)). Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. Procedural style string mysqli_stmt_error(mysqli_stmt stmt).\n". • mysqli_stmt::$error mysqli_stmt_error Returns a string description for last statement error Description Object oriented style string mysqli_stmt->error . } /* close connection */ mysqli_close($link). See Also mysqli_stmt_error mysqli_stmt_sqlstate 2.10. Returns a containing the error message for the most recently invoked statement function that can succeed or fail. An empty string if no error occurred.MySQL Improved Extension (Mysqli) mysqli_stmt_execute($stmt). Examples Example 2. ?> The above examples will output: Error: 1146.82. /* close statement */ mysqli_stmt_close($stmt).9.

"my_password". mysqli_query($link. Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". $stmt->error). $query)) { /* drop table */ mysqli_query($link.83. printf("Error: %s. mysqli_connect_error()). /* close statement */ mysqli_stmt_close($stmt). exit().MySQL Improved Extension (Mysqli) $mysqli = new mysqli("localhost". mysqli_connect_error()).10. "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($stmt = mysqli_prepare($link. mysqli_stmt::execute. "world"). exit(). Code FROM myCountry ORDER BY Name". mysqli_stmt_execute Copyright 1997-2012 the PHP Documentation Group.\n". "my_password". "INSERT INTO myCountry SELECT * FROM Country"). /* close statement */ $stmt->close().\n". if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry"). /* execute query */ mysqli_stmt_execute($stmt). $query = "SELECT Name. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".10. ?> Example 2. • mysqli_stmt::execute mysqli_stmt_execute 186 . "DROP TABLE myCountry"). $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"). mysqli_stmt_error($stmt)). "my_user". ?> The above examples will output: Error: Table 'world. printf("Error: %s. Code FROM myCountry ORDER BY Name". } /* close connection */ $mysqli->close(). } mysqli_query($link. /* execute query */ $stmt->execute(). } /* close connection */ mysqli_close($link). See Also mysqli_stmt_errno mysqli_stmt_sqlstate 2. $query = "SELECT Name. } $mysqli->query("CREATE TABLE myCountry LIKE Country"). "CREATE TABLE myCountry LIKE Country").myCountry' doesn't exist. "my_user".

if ($result = $mysqli->query($query)) { while ($row = $result->fetch_row()) { printf("%s (%s. if the query yields a result set the mysqli_stmt_fetch function is used. Procedural style bool mysqli_stmt_execute(mysqli_stmt stmt). the total number of affected rows can be determined by using the mysqli_stmt_affected_rows function. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. $val3 = 'Aquitaine'. Note When using mysqli_stmt_execute. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". or INSERT. $val2. mysqli_connect_error()). 187 . /* Prepare an insert statement */ $query = "INSERT INTO myCity (Name. $stmt->bind_param("sss". } $mysqli->query("CREATE TABLE myCity LIKE City"). Object oriented style <?php $mysqli = new mysqli("localhost". "my_user". CountryCode. "world"). Examples Example 2.MySQL Improved Extension (Mysqli) Executes a prepared Query Description Object oriented style bool mysqli_stmt::execute(). $val1. "my_password". District FROM myCity". When executed any parameter markers which exist will automatically be replaced with the appropriate data.?. the mysqli_stmt_fetch function must be used to fetch the data prior to performing any additional queries. CountryCode. $row[2]). Executes a query that has been previously prepared using the mysqli_prepare function. /* retrieve all rows from myCity */ $query = "SELECT Name. $val3). /* close statement */ $stmt->close(). } /* free result set */ $result->close().?)". $val2 = 'DEU'. Likewise.%s)\n". DELETE. Returns TRUE on success or FALSE on failure. $val1 = 'Bordeaux'. exit(). /* Execute the statement */ $stmt->execute(). $row[0]. $val3 = 'Baden-Wuerttemberg'. District) VALUES (?. $row[1]. $stmt = $mysqli->prepare($query). /* Execute the statement */ $stmt->execute(). $val2 = 'FRA'. $val1 = 'Stuttgart'. If the statement is UPDATE.84.

Aquitaine) See Also mysqli_prepare mysqli_stmt_bind_param 2.10. /* Prepare an insert statement */ $query = "INSERT INTO myCity (Name. $val3 = 'Aquitaine'. exit(). } mysqli_query($link. $val1. $query)) { while ($row = mysqli_fetch_row($result)) { printf("%s (%s. District) VALUES (?. $val2 = 'DEU'. $row[0]. $val1 = 'Stuttgart'. Procedural style <?php $link = mysqli_connect("localhost". CountryCode. $stmt = mysqli_prepare($link. $val3 = 'Baden-Wuerttemberg'. District FROM myCity". $query). /* close connection */ mysqli_close($link). /* close connection */ $mysqli->close(). mysqli_stmt_bind_param($stmt.Baden-Wuerttemberg) Bordeaux (FRA. "CREATE TABLE myCity LIKE City"). if ($result = mysqli_query($link. CountryCode. mysqli_connect_error()). $val2.MySQL Improved Extension (Mysqli) } /* remove table */ $mysqli->query("DROP TABLE myCity"). $row[2]).85. "world"). $row[1]. mysqli_stmt::fetch. "my_user". $val2 = 'FRA'. ?> The above examples will output: Stuttgart (DEU. • mysqli_stmt::fetch 188 . ?> Example 2. } /* remove table */ mysqli_query($link. $val1 = 'Bordeaux'.?.?)".%s)\n". /* retrieve all rows from myCity */ $query = "SELECT Name. "my_password". /* close statement */ mysqli_stmt_close($stmt). /* Execute the statement */ mysqli_stmt_execute($stmt). "sss". $val3). /* Execute the statement */ mysqli_stmt_execute($stmt). } /* free result set */ mysqli_free_result($result). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "DROP TABLE myCity"). mysqli_stmt_fetch Copyright 1997-2012 the PHP Documentation Group.11.

/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($stmt = $mysqli->prepare($query)) { /* execute statement */ $stmt->execute(). $name. Note Data are transferred unbuffered without calling mysqli_stmt_store_result which can decrease performance (but reduces memory cost).86. $code). Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result. } /* close statement */ 189 . "world"). Object oriented style <?php $mysqli = new mysqli("localhost". } $query = "SELECT Name. Note Note that all columns must be bound by the application before calling mysqli_stmt_fetch. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. exit(). /* bind result variables */ $stmt->bind_result($name. mysqli_connect_error()). Procedural style bool mysqli_stmt_fetch(mysqli_stmt stmt). Return Values Value TRUE FALSE NULL Description Success. "my_password".MySQL Improved Extension (Mysqli) mysqli_stmt_fetch Fetch results from a prepared statement into the bound variables Description Object oriented style bool mysqli_stmt::fetch(). CountryCode FROM City ORDER by ID DESC LIMIT 150. $code). Table 2. "my_user".8. /* fetch values */ while ($stmt->fetch()) { printf ("%s (%s)\n". Data has been fetched Error occurred No more rows/data exists or data truncation occurred Examples Example 2.5".

"my_password".10. } $query = "SELECT Name. mysqli_connect_error()).87. mysqli_stmt_field_count Copyright 1997-2012 the PHP Documentation Group. } /* close connection */ $mysqli->close(). ?> The above examples will output: Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) See Also mysqli_prepare mysqli_stmt_errno mysqli_stmt_error mysqli_stmt_bind_result 2. $code).12. if ($stmt = mysqli_prepare($link.5". "my_user". /* bind result variables */ mysqli_stmt_bind_result($stmt. } /* close connection */ mysqli_close($link). CountryCode FROM City ORDER by ID DESC LIMIT 150.MySQL Improved Extension (Mysqli) $stmt->close(). /* fetch values */ while (mysqli_stmt_fetch($stmt)) { printf ("%s (%s)\n". } /* close statement */ mysqli_stmt_close($stmt). • mysqli_stmt::$field_count mysqli_stmt_field_count Returns the number of field in the given statement Description Object oriented style 190 . $query)) { /* execute statement */ mysqli_stmt_execute($stmt). $name. $code). $name. mysqli_stmt::$field_count. "world"). ?> Example 2. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style <?php $link = mysqli_connect("localhost". exit().

10. See Also mysqli_stmt_store_result Procedural style only: A statement identifier returned by mysqli_stmt_init. Procedural style int mysqli_stmt_field_count(mysqli_stmt stmt). • mysqli_stmt::free_result mysqli_stmt_free_result Frees stored result memory for the given statement handle Description Object oriented style void mysqli_stmt::free_result(). mysqli_stmt_free_result Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented. • mysqli_stmt::get_result mysqli_stmt_get_result Gets a result set from a prepared statement Description 191 . Parameters stmt Return Values No value is returned. 2. only its argument list is available.13. mysqli_stmt::get_result. which was allocated by mysqli_stmt_store_result. Frees the result memory associated with the statement. mysqli_stmt_get_result Copyright 1997-2012 the PHP Documentation Group.10. Procedural style void mysqli_stmt_free_result(mysqli_stmt stmt). 2.14. mysqli_stmt::free_result.MySQL Improved Extension (Mysqli) int mysqli_stmt->field_count .

} $query = "SELECT Name. "world").'Africa'. ?> Example 2. while ($row = $result->fetch_array(MYSQLI_NUM)) { foreach ($row as $r) { print "$r ".88. "world"). Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. } } } $stmt->close(). Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1". if(!$stmt->prepare($query)) { print "Failed to prepare statement\n".0. $mysqli->close().0.1". Call to return a result set from a prepared statement query. Procedural style mysqli_result mysqli_stmt_get_result(mysqli_stmt stmt). MySQL Native Driver Only Available only with mysqlnd. Procedural style <?php $link = mysqli_connect("127. "user". $continent_array = array('Europe'.0. "password". Population. "password". if (!$link) 192 .'North America'). } print "\n".0. $stmt = $mysqli->stmt_init().1".'Asia'. if($mysqli->connect_error) { die("$mysqli->connect_errno: $myslqi->connect_error"). Object oriented style <?php $mysqli = new mysqli("127. } else { $stmt->bind_param("s".89.MySQL Improved Extension (Mysqli) Object oriented style mysqli_result mysqli_stmt::get_result(). $continent). "user". Returns a resultset or FALSE on failure. $result = $stmt->get_result(). Examples Example 2. foreach($continent_array as $continent) { $stmt->execute().

10. print "$errno: $error\n". $result = mysqli_stmt_get_result($stmt). $continent_array = array('Europe'. foreach($continent_array as $continent) { mysqli_stmt_execute($stmt).MySQL Improved Extension (Mysqli) { $error = mysqli_connect_error(). exit(). if(!mysqli_stmt_prepare($stmt. mysqli_stmt::get_warnings. ?> The above examples will output: Albania 3401200 Europe Algeria 31471000 Africa Afghanistan 22720000 Asia Anguilla 8000 North America See Also mysqli_prepare mysqli_stmt_result_metadata mysqli_stmt_fetch mysqli_fetch_array mysqli_stmt_store_result 2.'Africa'. $stmt = mysqli_stmt_init($link).'North America'). $query)) { print "Failed to prepare statement\n". $errno = mysqli_connect_errno(). • mysqli_stmt::get_warnings mysqli_stmt_get_warnings Get result of SHOW WARNINGS Description Object oriented style object mysqli_stmt::get_warnings(mysqli_stmt stmt). "s". MYSQLI_NUM)) { foreach ($row as $r) { print "$r ". } } } mysqli_stmt_close($stmt). Population. while ($row = mysqli_fetch_array($result. } $query = "SELECT Name. } else { mysqli_stmt_bind_param($stmt. } print "\n". mysqli_close($link).15. Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1". Procedural style 193 . $continent). mysqli_stmt_get_warnings Copyright 1997-2012 the PHP Documentation Group.'Asia'.

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. mysqli_stmt::$num_rows. mysqli_stmt::$insert_id. 2.16. mysqli_stmt_num_rows Copyright 1997-2012 the PHP Documentation Group. • mysqli_stmt::$num_rows mysqli_stmt_num_rows Return the number of rows in statements result set Description Object oriented style int mysqli_stmt->num_rows . Warning This function is currently not documented. • mysqli_stmt::$insert_id mysqli_stmt_insert_id Get the ID generated from the previous INSERT operation Description Object oriented style int mysqli_stmt->insert_id . mysqli_stmt_num_rows may be called immediately. mysqli_stmt_insert_id Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented.10. only its argument list is available. If you use mysqli_stmt_store_result.MySQL Improved Extension (Mysqli) object mysqli_stmt_get_warnings(mysqli_stmt stmt). Procedural style mixed mysqli_stmt_insert_id(mysqli_stmt stmt). Parameters 194 .10. 2.17. Returns the number of rows in the result set. Procedural style int mysqli_stmt_num_rows(mysqli_stmt stmt). only its argument list is available.

printf("Number of rows: %d. "my_password". "my_user".90. ?> Example 2. /* close statement */ mysqli_stmt_close($stmt). exit().\n". Examples Example 2. Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". } $query = "SELECT Name. mysqli_stmt_num_rows($stmt)). CountryCode FROM City ORDER BY Name LIMIT 20". Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". An integer representing the number of rows in result set. /* store result */ mysqli_stmt_store_result($stmt). See Also 195 . "my_password". exit(). mysqli_connect_error()).91.MySQL Improved Extension (Mysqli) stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. /* close statement */ $stmt->close(). ?> The above examples will output: Number of rows: 20. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } /* close connection */ $mysqli->close(). } $query = "SELECT Name.\n". mysqli_connect_error()). $query)) { /* execute query */ mysqli_stmt_execute($stmt). /* store result */ $stmt->store_result(). if ($stmt = mysqli_prepare($link. printf("Number of rows: %d. CountryCode FROM City ORDER BY Name LIMIT 20". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } /* close connection */ mysqli_close($link). "world"). if ($stmt = $mysqli->prepare($query)) { /* execute query */ $stmt->execute(). "world"). $stmt->num_rows). "my_user".

Returns the number of parameter markers present in the prepared statement. Procedural style int mysqli_stmt_param_count(mysqli_stmt stmt). exit(). • mysqli_stmt::$param_count mysqli_stmt_param_count Returns the number of parameter for the given statement Description Object oriented style int mysqli_stmt->param_count . printf("Statement has %d markers. $marker). Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. ?> Example 2.MySQL Improved Extension (Mysqli) mysqli_stmt_affected_rows mysqli_prepare mysqli_stmt_store_result 2. "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Returns an integer representing the number of parameters. mysqli_stmt_param_count Copyright 1997-2012 the PHP Documentation Group.10.93. mysqli_connect_error()).92. mysqli_stmt::$param_count. "my_password".18. Object oriented style <?php $mysqli = new mysqli("localhost". Examples Example 2. "world").\n". } /* close connection */ $mysqli->close(). } if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) { $marker = $stmt->param_count. Procedural style 196 . /* close statement */ $stmt->close().

mysqli_stmt_prepare Copyright 1997-2012 the PHP Documentation Group. "my_password". exit().10. The behavior is as follows: • mysqlnd on Linux returns an error code of 1153.19. ?> The above examples will output: Statement has 2 markers. "my_user". 197 . string query). the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_stmt::prepare.MySQL Improved Extension (Mysqli) <?php $link = mysqli_connect("localhost". } if ($stmt = mysqli_prepare($link. printf("Statement has %d markers. The error message means “got a packet bigger than max_allowed_packet bytes”. mysqli_connect_error()). } /* close connection */ mysqli_close($link). $marker). "SELECT Name FROM Country WHERE Name=? OR Code=?")) { $marker = mysqli_stmt_param_count($stmt). Prepares the SQL query pointed to by the null-terminated string query. • mysqli_stmt::prepare mysqli_stmt_prepare Prepare an SQL statement for execution Description Object oriented style mixed mysqli_stmt::prepare(string query). Procedural style bool mysqli_stmt_prepare(mysqli_stmt stmt. Note In the case where you pass a statement to mysqli_stmt_prepare that is longer than max_allowed_packet of the server.\n". 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. See Also mysqli_prepare 2. /* close statement */ mysqli_stmt_close($stmt).

In general. You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions. Return Values Returns TRUE on success or FALSE on failure. The query. It must consist of a single SQL statement. "world"). as a string. Note The markers are legal only in certain places in SQL statements. printf("%s is in district %s\n". } /* close connection */ $mysqli->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". This error message means “server has gone away”. $district). Examples Example 2. exit(). if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ $stmt->bind_param("s". ?> 198 . mysqli_connect_error()). /* close statement */ $stmt->close(). and not in Data Definition Language (DDL) statements. or to specify both operands of a binary operator such as the = equal sign. } $city = "Amersfoort". "my_password". Note You should not add a terminating semicolon or \g to the statement. they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row). /* fetch value */ $stmt->fetch(). $city). in the select list that names the columns to be returned by a SELECT statement). Parameters stmt query Procedural style only: A statement identifier returned by mysqli_stmt_init. However. $city. they are not allowed for identifiers (such as table or column names). parameters are legal only in Data Manipulation Language (DML) statements. /* create a prepared statement */ $stmt = $mysqli->stmt_init(). The latter restriction is necessary because it would be impossible to determine the parameter type. Object oriented style <?php $mysqli = new mysqli("localhost". or in a comparison with a column in a WHERE clause to specify a comparison value.94.MySQL Improved Extension (Mysqli) • • mysqlnd on Windows returns an error code 2006. For example. This error message means “server has gone away”. libmysql on all platforms returns an error code 2006. /* bind result variables */ $stmt->bind_result($district). /* execute query */ $stmt->execute(). "my_user".

/* close statement */ mysqli_stmt_close($stmt). $district). /* create a prepared statement */ $stmt = mysqli_stmt_init($link). /* bind result variables */ mysqli_stmt_bind_result($stmt. "my_user". ?> The above examples will output: Amersfoort is in district Utrecht See Also mysqli_stmt_init mysqli_stmt_execute mysqli_stmt_fetch mysqli_stmt_bind_param mysqli_stmt_bind_result mysqli_stmt_close 2.MySQL Improved Extension (Mysqli) Example 2.95.20. $city. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style bool mysqli_stmt_reset(mysqli_stmt stmt). exit(). 'SELECT District FROM City WHERE Name=?')) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt. $city). mysqli_connect_error()). • mysqli_stmt::reset mysqli_stmt_reset Resets a prepared statement Description Object oriented style bool mysqli_stmt::reset(). Procedural style <?php $link = mysqli_connect("localhost". "s". mysqli_stmt::reset. 199 . } $city = "Amersfoort". } /* close connection */ mysqli_close($link). "my_password". /* fetch value */ mysqli_stmt_fetch($stmt). mysqli_stmt_reset Copyright 1997-2012 the PHP Documentation Group. if (mysqli_stmt_prepare($stmt.10. "world"). /* execute query */ mysqli_stmt_execute($stmt). $district). printf("%s is in district %s\n".

Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. unbuffered result sets and current errors.MySQL Improved Extension (Mysqli) Resets a prepared statement on client and server to state after prepare. such as: • • • • • • mysqli_num_fields mysqli_fetch_field mysqli_fetch_field_direct mysqli_fetch_fields mysqli_field_count mysqli_field_seek 200 . Note This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata. Stored result sets will be cleared when executing the prepared statement (or closing it). See Also mysqli_prepare 2. If a statement passed to mysqli_prepare is one that produces a result set. mysqli_stmt::result_metadata. Procedural style mysqli_result mysqli_stmt_result_metadata(mysqli_stmt stmt). • mysqli_stmt::result_metadata mysqli_stmt_result_metadata Returns result set metadata from a prepared statement Description Object oriented style mysqli_result mysqli_stmt::result_metadata(). Returns TRUE on success or FALSE on failure. mysqli_stmt_result_metadata Copyright 1997-2012 the PHP Documentation Group. It resets the statement on the server.21.10. 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. data sent using mysqli_stmt_send_long_data. It does not clear bindings or stored result sets. To prepare a statement with another query use function mysqli_stmt_prepare.

$field->name). 'Ulf')"). "SELECT id. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. "test"). Returns a result object or FALSE if an error occurred. Examples Example 2. $stmt = $mysqli->prepare("SELECT id. printf("Fieldname: %s\n".'Hartmut'). $mysqli->query("CREATE TABLE friends (id int. name FROM friends"). $mysqli->query("INSERT INTO friends VALUES (1. The rows are obtained by using the statement handle with mysqli_stmt_fetch. "INSERT INTO friends VALUES (1. ?> Example 2. "my_user".96. /* close resultset */ $result->close(). /* close connection */ $mysqli->close(). /* close resultset */ mysqli_free_result($result). mysqli_stmt_execute($stmt). ?> 201 . Procedural style <?php $link = mysqli_connect("localhost".'Hartmut'). (2. mysqli_query($link. name varchar(20))"). /* retrieve field information from metadata result set */ $field = $result->fetch_field(). /* retrieve field information from metadata result set */ $field = mysqli_fetch_field($result). $stmt = mysqli_prepare($link. /* get resultset for metadata */ $result = $stmt->result_metadata(). /* close connection */ mysqli_close($link).97. "test"). (2. $mysqli->query("DROP TABLE IF EXISTS friends"). "DROP TABLE IF EXISTS friends"). "my_password". "CREATE TABLE friends (id int. $field->name). 'Ulf')"). mysqli_query($link. printf("Fieldname: %s\n". /* get resultset for metadata */ $result = mysqli_stmt_result_metadata($stmt). name varchar(20))"). mysqli_query($link.MySQL Improved Extension (Mysqli) • • mysqli_field_tell mysqli_free_result The result set structure should be freed when you are done with it. Object oriented style <?php $mysqli = new mysqli("localhost". $stmt->execute(). "my_user". name FROM friends"). which you can do by passing it to mysqli_free_result Note The result set returned by mysqli_stmt_result_metadata contains only metadata. "my_password". It does not contain any row results.

string data). while (!feof($fp)) { $stmt->send_long_data(0. $null = NULL. mysqli_stmt_send_long_data Copyright 1997-2012 the PHP Documentation Group.22. "r"). Allows to send parameter data to the server in pieces (or chunks). $stmt->bind_param("b". Returns TRUE on success or FALSE on failure. string data). ?> 202 . mysqli_stmt::send_long_data. A string containing data to be sent. Object oriented style <?php $stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)"). Parameters are numbered beginning with 0. Examples Example 2. 8192)). $fp = fopen("messages. int param_nr. if the size of a blob exceeds the size of max_allowed_packet.10. $null). e. fread($fp. • mysqli_stmt::send_long_data mysqli_stmt_send_long_data Send data in blocks Description Object oriented style bool mysqli_stmt::send_long_data(int param_nr. $stmt->execute(). Procedural style bool mysqli_stmt_send_long_data(mysqli_stmt stmt. This function can be called multiple times to send the parts of a character or binary data value for a column. Parameters stmt param_nr data Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init.txt". which must be one of the TEXT or BLOB datatypes.MySQL Improved Extension (Mysqli) See Also mysqli_prepare mysqli_free_result 2.g. Indicates which parameter to associate the data with. } fclose($fp).98.

Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". see http://dev. "world"). "my_password".MySQL Improved Extension (Mysqli) See Also mysqli_prepare mysqli_stmt_bind_param 2. Returns a string containing the SQLSTATE error code for the last error.10. The error code consists of five characters. Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. $query = "SELECT Name. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".com/doc/mysql/en/error-handling.23. The error code consists of five characters. mysqli_connect_error()). } $mysqli->query("CREATE TABLE myCountry LIKE Country"). The value HY000 (general error) is used for unmapped errors. Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. For a list of possible values. '00000' means no error. 203 . exit(). mysqli_stmt::$sqlstate. "my_user". Procedural style string mysqli_stmt_sqlstate(mysqli_stmt stmt).html. • mysqli_stmt::$sqlstate mysqli_stmt_sqlstate Returns SQLSTATE error from previous statement operation Description Object oriented style string mysqli_stmt->sqlstate .mysql. mysqli_stmt_sqlstate Copyright 1997-2012 the PHP Documentation Group. Code FROM myCountry ORDER BY Name". Notes Note Note that not all MySQL errors are yet mapped to SQLSTATE's.99. The values are specified by ANSI SQL and ODBC. $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"). Examples Example 2. '00000' means no error.

24. $stmt->sqlstate). printf("Error: %s. } mysqli_query($link.10. "my_user". /* execute query */ $stmt->execute(). mysqli_query($link. } /* close connection */ $mysqli->close(). • mysqli_stmt::store_result mysqli_stmt_store_result Transfers a result set from a prepared statement Description Object oriented style 204 . "my_password". mysqli_stmt_store_result Copyright 1997-2012 the PHP Documentation Group. } /* close connection */ mysqli_close($link). "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".\n". /* close statement */ $stmt->close(). mysqli_stmt_sqlstate($stmt)). if ($stmt = mysqli_prepare($link. /* execute query */ mysqli_stmt_execute($stmt). ?> The above examples will output: Error: 42S02. Code FROM myCountry ORDER BY Name". See Also mysqli_stmt_errno mysqli_stmt_error 2.\n". mysqli_stmt::store_result. ?> Example 2. mysqli_connect_error()). printf("Error: %s. $query)) { /* drop table */ mysqli_query($link. exit().MySQL Improved Extension (Mysqli) if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry"). Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost".100. $query = "SELECT Name. "INSERT INTO myCountry SELECT * FROM Country"). /* close statement */ mysqli_stmt_close($stmt). "DROP TABLE myCountry"). "CREATE TABLE myCountry LIKE Country").

$stmt->num_rows). it will not harm or cause any notable performance in all cases. Note It is unnecessary to call mysqli_stmt_store_result for other queries. but if you do. You must call mysqli_stmt_store_result for every query that successfully produces a result set (SELECT. mysqli_connect_error()). } $query = "SELECT Name. DESCRIBE. $query)) { 205 . "my_user". CountryCode FROM City ORDER BY Name LIMIT 20". printf("Number of rows: %d. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata returns NULL. Examples Example 2. if ($stmt = $mysqli->prepare($query)) { /* execute query */ $stmt->execute().102.MySQL Improved Extension (Mysqli) bool mysqli_stmt::store_result(). /* store result */ $stmt->store_result(). Procedural style bool mysqli_stmt_store_result(mysqli_stmt stmt). so that the subsequent mysqli_stmt_fetch call returns buffered data. } /* close connection */ $mysqli->close(). } $query = "SELECT Name. Returns TRUE on success or FALSE on failure. /* close statement */ $stmt->close(). "my_user".\n". "my_password". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". exit(). Parameters stmt Return Values Procedural style only: A statement identifier returned by mysqli_stmt_init. "world"). /* free result */ $stmt->free_result(). EXPLAIN). Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost".101. "world"). ?> Example 2. and only if you want to buffer the complete result set by the client. CountryCode FROM City ORDER BY Name LIMIT 20". "my_password". exit(). if ($stmt = mysqli_prepare($link. SHOW. Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost".

mysqli_result { mysqli_result . Represents the result set obtained from a query against the database. See Also mysqli_prepare mysqli_stmt_result_metadata mysqli_stmt_fetch 2. array mysqli_result->lengths . ?> The above examples will output: Number of rows: 20. printf("Number of rows: %d. mysqli_stmt_num_rows($stmt)). The mysqli_result class (mysqli_result) Copyright 1997-2012 the PHP Documentation Group. Methods bool mysqli_result::data_seek(int offset). int mysqli_result->num_rows . Changelog Table 2. Traversable Properties int mysqli_result->current_field . /* close statement */ mysqli_stmt_close($stmt).9. int mysqli_result->field_count . } /* close connection */ mysqli_close($link). 206 .4.11. /* free result */ mysqli_stmt_free_result($stmt). as mysqli_result now implements Traversable. mixed mysqli_result::fetch_all(int resulttype= =MYSQLI_NUM). /* store result */ mysqli_stmt_store_result($stmt).\n". mixed mysqli_result::fetch_array(int resulttype= =MYSQLI_BOTH).MySQL Improved Extension (Mysqli) /* execute query */ mysqli_stmt_execute($stmt).0 Description Iterator support was added. Changelog Version 5.

} 2. mysqli_field_tell Copyright 1997-2012 the PHP Documentation Group. Return Values Returns current offset of field cursor.1. mysqli_store_result or mysqli_use_result. This value can be used as an argument to mysqli_field_seek. • mysqli_result::$current_field mysqli_field_tell Get current field offset of a result pointer Description Object oriented style int mysqli_result->current_field .103. object mysqli_result::fetch_field().11. Examples Example 2.MySQL Improved Extension (Mysqli) array mysqli_result::fetch_assoc(). Object oriented style 207 . bool mysqli_result::field_seek(int fieldnr). mysqli_result::$current_field. mixed mysqli_result::fetch_row(). Procedural style int mysqli_field_tell(mysqli_result result). void mysqli_result::free(). array params). object mysqli_result::fetch_field_direct(int fieldnr). array mysqli_result::fetch_fields(). Returns the position of the field cursor used for the last mysqli_fetch_field call. object mysqli_result::fetch_object(string class_name. Parameters result Procedural style only: A result set identifier returned by mysqli_query.

printf("Type: %d\n\n". } /* close connection */ mysqli_close($link). printf("Name: %s\n". $finfo->table). printf("Flags: %d\n". $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { /* get fieldpointer offset */ $currentfield = mysqli_field_tell($result). } $result->close(). } $query = "SELECT Name. Len: Flags: Type: Name Country 11 1 254 SurfaceArea Country 10 32769 4 See Also 208 . "my_password". $currentfield). $finfo->name). "my_password".104. mysqli_connect_error()). printf("Type: %d\n\n". SurfaceArea from Country ORDER BY Code LIMIT 5". if ($result = $mysqli->query($query)) { /* Get field information for all columns */ while ($finfo = $result->fetch_field()) { /* get fieldpointer offset */ $currentfield = $result->current_field. $finfo->name). exit(). mysqli_connect_error()). "world"). printf("Name: %s\n". "my_user". $finfo->flags). Len: %d\n". $finfo->flags). if ($result = mysqli_query($link. Len: Flags: Type: Column 2: Name: Table: max. } $query = "SELECT Name. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $finfo->max_length). "my_user". printf("max. printf("Column %d:\n".MySQL Improved Extension (Mysqli) <?php $mysqli = new mysqli("localhost". $finfo->type). printf("Table: %s\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } mysqli_free_result($result). } /* close connection */ $mysqli->close(). $finfo->type). ?> The above examples will output: Column 1: Name: Table: max. $currentfield). $finfo->max_length). exit(). printf("Flags: %d\n". ?> Example 2. SurfaceArea from Country ORDER BY Code LIMIT 5". Len: %d\n". Procedural style <?php $link = mysqli_connect("localhost". printf("max. printf("Column %d:\n". "world"). $finfo->table). printf("Table: %s\n".

Examples Example 2. mysqli_result::data_seek. } $query = "SELECT Name. if ($result = $mysqli->query( $query)) { /* seek to row no. The mysqli_data_seek function seeks to an arbitrary result pointer specified by the offset in the result set.2. "world"). 400 */ $result->data_seek(399). CountryCode FROM City ORDER BY Name".. Parameters result offset Procedural style only: A result set identifier returned by mysqli_query. mysqli_data_seek Copyright 1997-2012 the PHP Documentation Group.1). Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". Must be between zero and the total number of rows minus one (0.mysqli_num_rows . Procedural style bool mysqli_data_seek(mysqli_result result. The field offset. mysqli_connect_error()). "my_password". int offset).11. "my_user".MySQL Improved Extension (Mysqli) mysqli_fetch_field mysqli_field_seek 2. 209 . Return Values Returns TRUE on success or FALSE on failure.105. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_store_result or mysqli_use_result. exit(). Notes Note This function can only be used with buffered results attained from the use of the mysqli_store_result or mysqli_query functions. • mysqli_result::data_seek mysqli_data_seek Adjusts the result pointer to an arbitary row in the result Description Object oriented style bool mysqli_result::data_seek(int offset).

printf ("City: %s Countrycode: %s\n". or both Description 210 . if ($result = mysqli_query($link. CountryCode FROM City ORDER BY Name".11. } /* close connection */ $mysqli->close().3. "my_user". mysqli_result::fetch_all. exit(). ?> The above examples will output: City: Benin City Countrycode: NGA See Also mysqli_store_result mysqli_fetch_row mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_object mysqli_query mysqli_num_rows 2. "my_password". ?> Example 2. /* fetch row */ $row = mysqli_fetch_row($result). Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". mysqli_connect_error()).106. /* free result set*/ mysqli_free_result($result). $row[1]).MySQL Improved Extension (Mysqli) /* fetch row */ $row = $result->fetch_row(). 399). mysqli_fetch_all Copyright 1997-2012 the PHP Documentation Group. } /* close connection */ mysqli_close($link). /* check connection */ if (!$link) { printf("Connect failed: %s\n". a numeric array. 400 */ mysqli_data_seek($result. $query)) { /* seek to row no. $row[0]. } $query = "SELECT Name. • mysqli_result::fetch_all mysqli_fetch_all Fetches all result rows as an associative array. "world"). $row[1]). /* free result set*/ $result->close(). printf ("City: %s Countrycode: %s\n". $row[0].

mysqli_fetch_array Copyright 1997-2012 the PHP Documentation Group. which only returns one row at a time from the result set. The possible values for this parameter are the constants MYSQLI_ASSOC . it may consume more memory than some similar functions such as mysqli_fetch_array. or both.MySQL Improved Extension (Mysqli) Object oriented style mixed mysqli_result::fetch_all(int resulttype= =MYSQLI_NUM). 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. mysqli_fetch_all fetches all result rows and returns the result set as an associative array. you will need a looping construct that will further impact performance. As mysqli_fetch_all returns all the rows as an array in a single step. int resulttype= =MYSQLI_NUM).11. a numeric array. a numeric array. MYSQLI_NUM . mysqli_result::fetch_array. or both Description Object oriented style mixed mysqli_result::fetch_array(int resulttype= =MYSQLI_BOTH). Further. MySQL Native Driver Only Available only with mysqlnd. 211 . Procedural style mixed mysqli_fetch_all(mysqli_result result. mysqli_store_result or mysqli_use_result. • mysqli_result::fetch_array mysqli_fetch_array Fetch a result row as an associative. or MYSQLI_BOTH . Return Values Returns an array of associative or numeric arrays holding result rows. int resulttype= =MYSQLI_BOTH). Parameters result resulttype Procedural style only: A result set identifier returned by mysqli_query. Procedural style mixed mysqli_fetch_array(mysqli_result result. if you need to iterate over the result set. See Also mysqli_fetch_array mysqli_query 2. This optional parameter is a constant indicating what type of array should be produced from the current row data.4.

the mysqli_fetch_array function can also store the data in associative indices. while MYSQLI_NUM will behave identically to the mysqli_fetch_row function. ?> 212 . This optional parameter is a constant indicating what type of array should be produced from the current row data. $row[0]. printf ("%s (%s)\n". Object oriented style <?php $mysqli = new mysqli("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). The possible values for this parameter are the constants MYSQLI_ASSOC . Note This function sets NULL fields to the PHP NULL value. $result = $mysqli->query($query). /* associative array */ $row = $result->fetch_array(MYSQLI_ASSOC). Parameters result resulttype Procedural style only: A result set identifier returned by mysqli_query.MySQL Improved Extension (Mysqli) 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. In order to access multiple columns with the same name. mysqli_store_result or mysqli_use_result. using the field names of the result set as keys. In addition to storing the data in the numeric indices of the result array. "my_user". $row[1]). CountryCode FROM City ORDER by ID LIMIT 3". or MYSQLI_BOTH . $row["CountryCode"]). /* associative and numeric array */ $row = $result->fetch_array(MYSQLI_BOTH). $row["CountryCode"]). By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc. The final option MYSQLI_BOTH will create a single array with the attributes of both. $row[0]. mysqli_fetch_array is an extended version of the mysqli_fetch_row function. If two or more columns of the result have the same field names. /* free result set */ $result->close().107. /* numeric array */ $row = $result->fetch_array(MYSQLI_NUM). exit(). /* close connection */ $mysqli->close(). printf ("%s (%s)\n". Note Field names returned by this function are case-sensitive. the numerically indexed version of the row must be used. MYSQLI_NUM . "world"). "my_password". Return Values Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset. } $query = "SELECT Name. printf ("%s (%s)\n". Examples Example 2. the last column will take precedence and overwrite the earlier data. $row["Name"].

$row[0]. 213 . mysqli_result::fetch_assoc. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf ("%s (%s)\n". exit().11. mysqli_connect_error()).MySQL Improved Extension (Mysqli) Example 2.108. printf ("%s (%s)\n". $result = mysqli_query($link. $query). mysqli_fetch_assoc Copyright 1997-2012 the PHP Documentation Group. Procedural style array mysqli_fetch_assoc(mysqli_result result). MYSQLI_ASSOC). $row[1]). Procedural style <?php $link = mysqli_connect("localhost".5. $row["CountryCode"]). $row[0]. "my_user". MYSQLI_BOTH). /* numeric array */ $row = mysqli_fetch_array($result. ?> The above examples will output: Kabul (AFG) Qandahar (AFG) Herat (AFG) See Also mysqli_fetch_assoc mysqli_fetch_row mysqli_fetch_object mysqli_query mysqli_data_seek 2. $row["CountryCode"]). printf ("%s (%s)\n". "my_password". } $query = "SELECT Name. /* associative array */ $row = mysqli_fetch_array($result. /* close connection */ mysqli_close($link). $row["Name"]. "world"). /* free result set */ mysqli_free_result($result). /* associative and numeric array */ $row = mysqli_fetch_array($result. CountryCode FROM City ORDER by ID LIMIT 3". MYSQLI_NUM). • mysqli_result::fetch_assoc mysqli_fetch_assoc Fetch a result row as an associative array Description Object oriented style array mysqli_result::fetch_assoc().

Examples Example 2.109. the last column will take precedence. if ($result = mysqli_query($link.5". mysqli_connect_error()). exit().5". If two or more columns of the result have the same field names. you either need to access the result with numeric indices by using mysqli_fetch_row or add alias names. $row["Name"]. exit(). } /* free result set */ $result->free(). Return Values Returns an associative array of strings representing the fetched row in the result set. "world"). "world"). } $query = "SELECT Name. ?> Example 2. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_store_result or mysqli_use_result. Parameters result Procedural style only: A result set identifier returned by mysqli_query. CountryCode FROM City ORDER by ID DESC LIMIT 50. $query)) { /* fetch associative array */ while ($row = mysqli_fetch_assoc($result)) { printf ("%s (%s)\n". Object oriented style <?php $mysqli = new mysqli("localhost".110. mysqli_connect_error()). $row["Name"]. Note This function sets NULL fields to the PHP NULL value. } $query = "SELECT Name. if ($result = $mysqli->query($query)) { /* fetch associative array */ while ($row = $result->fetch_assoc()) { printf ("%s (%s)\n". } 214 . "my_password". "my_user". } /* close connection */ $mysqli->close(). CountryCode FROM City ORDER by ID DESC LIMIT 50. "my_user". $row["CountryCode"]). To access the other column(s) of the same name. "my_password". 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. $row["CountryCode"]). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Note Field names returned by this function are case-sensitive.MySQL Improved Extension (Mysqli) Returns an associative array that corresponds to the fetched row or NULL if there are no more rows. } /* free result set */ mysqli_free_result($result). Procedural style <?php $link = mysqli_connect("localhost".

168.MySQL Improved Extension (Mysqli) /* close connection */ mysqli_close($link).6.1. A mysqli_result example comparing iterator usage <?php $c = mysqli_connect('127. • mysqli_result::fetch_field_direct mysqli_fetch_field_direct 215 .1'.1.0. $row['host']). } echo "\n==================\n".111. ?> The above examples will output: Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) Example 2.1' 'root'@'127.168.host FROM mysql. 'pass'). mysqli_fetch_field_direct Copyright 1997-2012 the PHP Documentation Group. $row['user'].0.0. $row['user']. while ($row = $result->fetch_assoc()) { printf("'%s'@'%s'\n". } ?> The above example will output something similar to: 'root'@'192.0.11.0. $row['host']).1' 'dude'@'localhost' 'lebowski'@'localhost' See Also mysqli_fetch_array mysqli_fetch_row mysqli_fetch_object mysqli_query mysqli_data_seek 2.'user'.user') as $row ) { printf("'%s'@'%s'\n". // Using iterators (support was added with PHP 5. // Not using iterators $result = $c->query('SELECT user.1' 'root'@'127.host FROM mysql.4) foreach ( $c->query('SELECT user.1' 'dude'@'localhost' 'lebowski'@'localhost' ================== 'root'@'192. mysqli_result::fetch_field_direct.user').0.

mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". 216 . An integer representing the bit-flags for the field.10. SurfaceArea from Country ORDER BY Name LIMIT 5". as specified in the table definition. Object oriented style <?php $mysqli = new mysqli("localhost". Returns an object which contains field definition information from the specified result set. Table 2.MySQL Improved Extension (Mysqli) Fetch meta-data for a single field Description Object oriented style object mysqli_result::fetch_field_direct(int fieldnr). exit(). Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available. Object attributes Attribute name orgname table orgtable def max_length length charsetnr flags type decimals Examples Description The name of the column Original column name if an alias was specified The name of the table this field belongs to (if not calculated) Original table name if an alias was specified The default value for this field. The width of the field. The data type used for this field The number of decimals used (for integer fields) Example 2.112. "my_password". The field number. "my_user". int fieldnr). represented as a string The maximum width of the field for the result set. } $query = "SELECT Name. This value must be in the range from 0 to number of fields .1. mysqli_store_result or mysqli_use_result. Parameters result fieldnr Return Values Procedural style only: A result set identifier returned by mysqli_query. "world"). Procedural style object mysqli_fetch_field_direct(mysqli_result result. The character set number for the field.

printf("Type: %d\n". mysqli_free_result($result). $finfo->flags). } $query = "SELECT Name. Len: %d\n". $finfo->max_length). $finfo->table). printf("Name: %s\n".11. Procedural style <?php $link = mysqli_connect("localhost". exit(). printf("Name: %s\n". printf("Flags: %d\n". } /* close connection */ $mysqli->close(). ?> Example 2. $finfo->max_length). printf("max. } /* close connection */ mysqli_close($link). ?> The above examples will output: Name: Table: max. mysqli_fetch_field Copyright 1997-2012 the PHP Documentation Group. $finfo->name). "world"). 1). "my_password". $result->close(). printf("Table: %s\n". $query)) { /* Get field information for column 'SurfaceArea' */ $finfo = mysqli_fetch_field_direct($result. $finfo->type). printf("max. $finfo->type).113. printf("Flags: %d\n". mysqli_result::fetch_field. $finfo->name). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($result = mysqli_query($link. "my_user". $finfo->table). Len: Flags: Type: SurfaceArea Country 10 32769 4 See Also mysqli_num_fields mysqli_fetch_field mysqli_fetch_fields 2. printf("Type: %d\n". mysqli_connect_error()). Len: %d\n". • mysqli_result::fetch_field mysqli_fetch_field Returns the next field in the result set 217 .7.MySQL Improved Extension (Mysqli) if ($result = $mysqli->query($query)) { /* Get field information for column 'SurfaceArea' */ $finfo = $result->fetch_field_direct(1). $finfo->flags). printf("Table: %s\n". SurfaceArea from Country ORDER BY Name LIMIT 5".

Return Values Returns an object which contains field definition information or FALSE if no field information is available. 218 . Call this function repeatedly to retrieve information about all columns in the result set.3. "my_password". SurfaceArea from Country ORDER BY Code LIMIT 5". "world"). "my_user". } $query = "SELECT Name. Procedural style object mysqli_fetch_field(mysqli_result result). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($result = $mysqli->query($query)) { /* Get field information for all columns */ while ($finfo = $result->fetch_field()) { printf("Name: %s\n". as specified in the table definition. The width of the field. exit().6) The maximum width of the field for the result set.11. mysqli_connect_error()). always "def" (since PHP 5. Table 2.6) The catalog name. $finfo->name).3. currently always "" Database (since PHP 5. Parameters result Procedural style only: A result set identifier returned by mysqli_query. The character set number for the field.MySQL Improved Extension (Mysqli) Description Object oriented style object mysqli_result::fetch_field().114. An integer representing the bit-flags for the field. Object oriented style <?php $mysqli = new mysqli("localhost". Returns the definition of one column of a result set as an object. mysqli_store_result or mysqli_use_result. The data type used for this field The number of decimals used (for integer fields) Example 2. Object properties Property name orgname table orgtable def db catalog max_length length charsetnr flags type decimals Examples Description The name of the column Original column name if an alias was specified The name of the table this field belongs to (if not calculated) Original table name if an alias was specified Reserved for default value.

printf("Flags: %d\n". "my_user". $finfo->flags). } $query = "SELECT Name. printf("max. %d\n\n". mysqli_result::fetch_fields. Len: Flags: Type: Name: Table: max. $finfo->type). printf("Table: %s\n". "my_password".8. $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { printf("Name: %s\n". } /* close connection */ $mysqli->close(). $finfo->max_length). Len: %d\n". $finfo->name). %d\n". $finfo->table). mysqli_connect_error()). ?> %s\n". SurfaceArea from Country ORDER BY Code LIMIT 5".11. $finfo->type). • mysqli_result::fetch_fields mysqli_fetch_fields 219 . } /* close connection */ mysqli_close($link). "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". exit(). } mysqli_free_result($result). %d\n". printf("Type: %d\n\n". Procedural style <?php $link = mysqli_connect("localhost". Len: Flags: Type: Name Country 11 1 254 SurfaceArea Country 10 32769 4 See Also mysqli_num_fields mysqli_fetch_field_direct mysqli_fetch_fields mysqli_field_seek 2. Example 2.MySQL Improved Extension (Mysqli) printf("Table: printf("max. $finfo->max_length). Len: printf("Flags: printf("Type: } $result->close(). mysqli_fetch_fields Copyright 1997-2012 the PHP Documentation Group. $finfo->table). $finfo->flags). if ($result = mysqli_query($link. ?> The above examples will output: Name: Table: max.115.

exit(). if ($result = $mysqli->query($query)) { /* Get field information for all columns */ $finfo = $result->fetch_fields(). foreach ($finfo as $val) { printf("Name: %s\n".MySQL Improved Extension (Mysqli) Returns an array of objects representing the fields in a result set Description Object oriented style array mysqli_result::fetch_fields(). "my_password". The width of the field. Table 2. Parameters result Procedural style only: A result set identifier returned by mysqli_query. Return Values Returns an array of objects which contains field definition information or FALSE if no field information is available. 220 . "world"). The data type used for this field The number of decimals used (for integer fields) Example 2. SurfaceArea from Country ORDER BY Code LIMIT 5". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". The character set number for the field.12.116. as specified in the table definition. } $query = "SELECT Name. This function serves an identical purpose to the mysqli_fetch_field function with the single difference that. Object properties Property name orgname table orgtable max_length length charsetnr flags type decimals Examples Description The name of the column Original column name if an alias was specified The name of the table this field belongs to (if not calculated) Original table name if an alias was specified The maximum width of the field for the result set. $val->name). Procedural style array mysqli_fetch_fields(mysqli_result result). mysqli_connect_error()). An integer representing the bit-flags for the field. mysqli_store_result or mysqli_use_result. "my_user". instead of returning one object at a time for each field. the columns are returned as an array of objects. Object oriented style <?php $mysqli = new mysqli("localhost".

$val->name). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $val->flags). mysqli_connect_error()). Example 2.11.9. printf("Flags: %d\n". $val->max_length). Len: Flags: Type: Name Country 11 1 254 SurfaceArea Country 10 32769 4 See Also mysqli_num_fields mysqli_fetch_field_direct mysqli_fetch_field 2. exit(). $val->table). } /* close connection */ $mysqli->close(). "world"). } $query = "SELECT Name. "my_password". $val->max_length). mysqli_result::fetch_object.117. $val->type). printf("Type: %d\n\n". Len: Flags: Type: Name: Table: max. Len: %d\n". ?> %s\n". mysqli_fetch_object Copyright 1997-2012 the PHP Documentation Group. $val->flags). • mysqli_result::fetch_object mysqli_fetch_object 221 . foreach ($finfo as $val) { printf("Name: %s\n".MySQL Improved Extension (Mysqli) printf("Table: printf("max. %d\n\n". printf("Table: %s\n". } mysqli_free_result($result). %d\n". Procedural style <?php $link = mysqli_connect("localhost". if ($result = mysqli_query($link. "my_user". $query)) { /* Get field information for all columns */ $finfo = mysqli_fetch_fields($result). ?> The above examples will output: Name: Table: max. %d\n". $val->table). $val->type). } /* close connection */ mysqli_close($link). Len: printf("Flags: printf("Type: } $result->close(). SurfaceArea from Country ORDER BY Code LIMIT 5". printf("max.

set the properties of and return. Changelog Version 5. The name of the class to instantiate. a stdClass object is returned. "world"). mysqli_connect_error()). Object oriented style <?php $mysqli = new mysqli("localhost". exit(). An optional array of parameters to pass to the constructor for class_name objects.MySQL Improved Extension (Mysqli) Returns the current row of a result set as an object Description Object oriented style object mysqli_result::fetch_object(string class_name. Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset. Example 2. Parameters result class_name params Return Values Procedural style only: A result set identifier returned by mysqli_query.118. Note that mysqli_fetch_object sets the properties of the object before calling the object constructor. Procedural style object mysqli_fetch_object(mysqli_result result. 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. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Note This function sets NULL fields to the PHP NULL value.0. "my_password". array params). } 222 .0 Examples Description Added the ability to return as a different object. Note Field names returned by this function are case-sensitive. array params). string class_name. "my_user". mysqli_store_result or mysqli_use_result. If not specified.

5". if ($result = mysqli_query($link.10. } /* free result set */ mysqli_free_result($result). $obj->Name. } $query = "SELECT Name. CountryCode FROM City ORDER by ID DESC LIMIT 50. "world"). ?> The above examples will output: Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) See Also mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_row mysqli_query mysqli_data_seek 2.MySQL Improved Extension (Mysqli) $query = "SELECT Name. } /* close connection */ $mysqli->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".119. exit(). mysqli_connect_error()).5". • mysqli_result::fetch_row mysqli_fetch_row Get a result row as an enumerated array 223 . $obj->CountryCode). mysqli_result::fetch_row. $obj->CountryCode). ?> Example 2. Procedural style <?php $link = mysqli_connect("localhost". } /* close connection */ mysqli_close($link). CountryCode FROM City ORDER by ID DESC LIMIT 50. mysqli_fetch_row Copyright 1997-2012 the PHP Documentation Group. "my_user". } /* free result set */ $result->close(). "my_password". $query)) { /* fetch associative array */ while ($obj = mysqli_fetch_object($result)) { printf ("%s (%s)\n". $obj->Name. if ($result = $mysqli->query($query)) { /* fetch object array */ while ($obj = $result->fetch_object()) { printf ("%s (%s)\n".11.

Each subsequent call to this function will return the next row within the result set. "my_password". where each column is stored in an array offset starting from 0 (zero). Fetches one row of data from the result set and returns it as an enumerated array. mysqli_connect_error()). CountryCode FROM City ORDER by ID DESC LIMIT 50. $row[0]. CountryCode FROM City ORDER by ID DESC LIMIT 50. or NULL if there are no more rows. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". "world"). } $query = "SELECT Name. mysqli_connect_error()).5". Examples Example 2.5". Procedural style <?php $link = mysqli_connect("localhost". if ($result = $mysqli->query($query)) { /* fetch object array */ while ($row = $result->fetch_row()) { printf ("%s (%s)\n". if ($result = mysqli_query($link. Note This function sets NULL fields to the PHP NULL value. 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. $query)) { /* fetch associative array */ while ($row = mysqli_fetch_row($result)) { 224 . Object oriented style <?php $mysqli = new mysqli("localhost".MySQL Improved Extension (Mysqli) Description Object oriented style mixed mysqli_result::fetch_row(). } /* free result set */ $result->close().120. mysqli_store_result or mysqli_use_result. exit().121. "world"). } $query = "SELECT Name. $row[1]). Parameters result Procedural style only: A result set identifier returned by mysqli_query. exit(). Procedural style mixed mysqli_fetch_row(mysqli_result result). "my_password". } /* close connection */ $mysqli->close(). ?> Example 2. "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".

mysqli_result::$field_count. Returns the number of fields from specified result set. ?> The above examples will output: Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) See Also mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_object mysqli_query mysqli_data_seek 2. $row[1]). Parameters result Procedural style only: A result set identifier returned by mysqli_query. Procedural style int mysqli_num_fields(mysqli_result result). $row[0].MySQL Improved Extension (Mysqli) printf ("%s (%s)\n". • mysqli_result::$field_count mysqli_num_fields Get the number of fields in a result Description Object oriented style int mysqli_result->field_count . 225 .11. mysqli_num_fields Copyright 1997-2012 the PHP Documentation Group.11. } /* free result set */ mysqli_free_result($result). Return Values The number of fields from a result set. mysqli_store_result or mysqli_use_result. } /* close connection */ mysqli_close($link).

MySQL Improved Extension (Mysqli)

Examples

Example 2.122. Object oriented style
<?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(); ?>

Example 2.123. 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); ?>

The above examples will output:
Result set has 5 fields.

See Also mysqli_fetch_field

2.11.12. mysqli_result::field_seek, mysqli_field_seek
Copyright 1997-2012 the PHP Documentation Group. • mysqli_result::field_seek mysqli_field_seek Set result pointer to a specified field offset

226

MySQL Improved Extension (Mysqli)

Description Object oriented style
bool mysqli_result::field_seek(int fieldnr);

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

result fieldnr Return Values

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 TRUE on success or FALSE on failure. Examples

Example 2.124. Object oriented style
<?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 Code LIMIT 5"; if ($result = $mysqli->query($query)) { /* Get field information for 2nd column */ $result->field_seek(1); $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(); ?>

Example 2.125. 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());

227

MySQL Improved Extension (Mysqli)

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); printf("Type: %d\n\n", $finfo->type); mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>

The above examples will output:
Name: Table: max. Len: Flags: Type: SurfaceArea Country 10 32769 4

See Also mysqli_fetch_field

2.11.13. mysqli_result::free, mysqli_free_result
Copyright 1997-2012 the PHP Documentation Group. • mysqli_result::free mysqli_free_result Frees the memory associated with a result Description Object oriented style
void mysqli_result::free(); void mysqli_result::close(); void mysqli_result::free_result();

Procedural style
void mysqli_free_result(mysqli_result result);

Frees the memory associated with the result.

Note
You should always free your result with mysqli_free_result, when your result object is not needed anymore. Parameters 228

MySQL Improved Extension (Mysqli)

result

Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result.

Return Values No value is returned. See Also mysqli_query mysqli_stmt_store_result mysqli_store_result mysqli_use_result

2.11.14. mysqli_result::$lengths, mysqli_fetch_lengths
Copyright 1997-2012 the PHP Documentation Group. • mysqli_result::$lengths mysqli_fetch_lengths Returns the lengths of the columns of the current row in the result set Description Object oriented style
array mysqli_result->lengths ;

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

Example 2.126. Object oriented style
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

229

MySQL Improved Extension (Mysqli)

/* 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($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(); ?>

Example 2.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(); } $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); ?>

The above examples will output:
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

2.11.15. mysqli_result::$num_rows, mysqli_num_rows
Copyright 1997-2012 the PHP Documentation Group. • mysqli_result::$num_rows mysqli_num_rows Gets the number of rows in a result 230

"world"). } if ($result = mysqli_query($link. mysqli_connect_error()). 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. Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = mysqli_num_rows($result). mysqli_store_result or mysqli_use_result. "my_user". 231 .128. $row_cnt). "my_user". /* close result set */ $result->close(). Procedural style <?php $link = mysqli_connect("localhost". The behaviour of mysqli_num_rows depends on whether buffered or unbuffered result sets are being used.\n". Examples Example 2. } /* close connection */ $mysqli->close(). Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = $result->num_rows. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style int mysqli_num_rows(mysqli_result result). mysqli_connect_error()). $row_cnt).\n". exit(). "world"). the number will be returned as a string. printf("Result set has %d rows. printf("Result set has %d rows. For unbuffered result sets. "SELECT Code. "my_password". } if ($result = $mysqli->query("SELECT Code. exit(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".MySQL Improved Extension (Mysqli) Description Object oriented style int mysqli_result->num_rows . "my_password". Note If the number of rows is greater than MAXINT . Returns the number of rows in the result set. Object oriented style <?php $mysqli = new mysqli("localhost". ?> Example 2.129. Return Values Returns number of rows in the result set.

public bool reconnect . MySQLi Driver. } /* close connection */ mysqli_close($link). The mysqli_driver class (mysqli_driver) Copyright 1997-2012 the PHP Documentation Group. public int report_mode .MySQL Improved Extension (Mysqli) /* close result set */ mysqli_free_result($result). See Also mysqli_affected_rows mysqli_store_result mysqli_use_result mysqli_query 2. array arguments. } client_info client_version driver_version embedded reconnect The Client API header version The Client version The MySQLi Driver version Whether MySQLi Embedded support is enabled Allow or prevent reconnect (see the mysqli. Methods void mysqli_driver::embedded_server_end(). public readonly string driver_version . public readonly string client_version .reconnect INI directive) 232 . bool mysqli_driver::embedded_server_start(bool start. public readonly string embedded . mysqli_driver { mysqli_driver Properties public readonly string client_info .12. ?> The above examples will output: Result set has 239 rows. array groups).

array arguments. Procedural style void mysqli_embedded_server_end(). only its argument list is available.1. See also mysqli_report. mysqli_embedded_server_start Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented. array groups). array arguments. only its argument list is available. MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes). Warning This function is currently not documented. 2. MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors).2.MySQL Improved Extension (Mysqli) report_mode Set to MYSQLI_REPORT_OFF . Procedural style bool mysqli_embedded_server_start(bool start. array groups). mysqli_embedded_server_end Copyright 1997-2012 the PHP Documentation Group.12. 2. mysqli_driver::embedded_server_end. mysqli_driver::embedded_server_start. • mysqli_driver::embedded_server_end mysqli_embedded_server_end Stop embedded server Description Object oriented style void mysqli_driver::embedded_server_end().12. 233 . • mysqli_driver::embedded_server_start mysqli_embedded_server_start Initialize and start embedded server Description Object oriented style bool mysqli_driver::embedded_server_start(bool start.

• mysqli_warning::next The next purpose 234 . Methods public mysqli_warning::__construct(). Represents a MySQL warning.1. } message sqlstate errno Message string SQL state Error number 2. public void mysqli_warning::next(). mysqli_warning::next Copyright 1997-2012 the PHP Documentation Group. • mysqli_warning::__construct The __construct purpose Description public mysqli_warning::__construct(). mysqli_warning { mysqli_warning Properties public message .13. public errno . mysqli_warning::__construct Copyright 1997-2012 the PHP Documentation Group.13. Parameters This function has no parameters. only its argument list is available.2. Return Values 2.13. public sqlstate . Warning This function is currently not documented.MySQL Improved Extension (Mysqli) 2. The mysqli_warning class (mysqli_warning) Copyright 1997-2012 the PHP Documentation Group.

MySQL Improved Extension (Mysqli) Description public void mysqli_warning::next(). mysqli_bind_param Copyright 1997-2012 the PHP Documentation Group. See Also mysqli_stmt_bind_param 2.1. Aliases and deprecated Mysqli Functions Copyright 1997-2012 the PHP Documentation Group. 2. mysqli_bind_result Copyright 1997-2012 the PHP Documentation Group. 235 .14. Parameters This function has no parameters. • mysqli_bind_param Alias for mysqli_stmt_bind_param Description This function is an alias of mysqli_stmt_bind_param.14. Notes Note mysqli_bind_result is deprecated and will be removed. • mysqli_bind_result Alias for mysqli_stmt_bind_result Description This function is an alias of mysqli_stmt_bind_result.14. Warning This function is currently not documented. only its argument list is available.2. Notes Note mysqli_bind_param is deprecated and will be removed. Return Values 2.

3.3.14.0. • mysqli_connect Alias of mysqli::__construct Description This function is an alias of: mysqli::__construct 2.6.14.14.14.4. mysqli_disable_rpl_parse Copyright 1997-2012 the PHP Documentation Group. only its argument list is available. 2. Warning This function has been DEPRECATED and REMOVED as of PHP 5. mysqli_enable_reads_from_master Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented. See Also mysqli_real_escape_string 2.5. 236 .MySQL Improved Extension (Mysqli) See Also mysqli_stmt_bind_result 2. • mysqli_disable_rpl_parse Disable RPL parse Description bool mysqli_disable_rpl_parse(mysqli link). mysqli_connect Copyright 1997-2012 the PHP Documentation Group. • mysqli_client_encoding Alias of mysqli_character_set_name Description This function is an alias of mysqli_character_set_name. mysqli_client_encoding Copyright 1997-2012 the PHP Documentation Group.

• mysqli_execute Alias for mysqli_stmt_execute Description 237 .14. 2. mysqli_enable_rpl_parse Copyright 1997-2012 the PHP Documentation Group.0. 2.14.8. Warning This function is currently not documented.3.9. 2.0. only its argument list is available. Warning This function is currently not documented.7. • mysqli_escape_string Alias of mysqli_real_escape_string Description This function is an alias of: mysqli_real_escape_string. only its argument list is available. mysqli_escape_string Copyright 1997-2012 the PHP Documentation Group.MySQL Improved Extension (Mysqli) • mysqli_enable_reads_from_master Enable reads from master Description bool mysqli_enable_reads_from_master(mysqli link). Warning This function has been DEPRECATED and REMOVED as of PHP 5. mysqli_execute Copyright 1997-2012 the PHP Documentation Group.14.3. • mysqli_enable_rpl_parse Enable RPL parse Description bool mysqli_enable_rpl_parse(mysqli link). Warning This function has been DEPRECATED and REMOVED as of PHP 5.

FALSE otherwise. Examples 238 . mysqli_get_cache_stats Copyright 1997-2012 the PHP Documentation Group. only its argument list is available. Notes Note mysqli_fetch is deprecated and will be removed.11. Returns client Zval cache statistics. Notes Note mysqli_execute is deprecated and will be removed.14. Parameters Return Values Returns an array with client Zval cache stats if success. mysqli_fetch Copyright 1997-2012 the PHP Documentation Group. • mysqli_fetch Alias for mysqli_stmt_fetch Description This function is an alias of mysqli_stmt_fetch. • mysqli_get_cache_stats Returns client Zval cache statistics Description array mysqli_get_cache_stats(). See Also mysqli_stmt_execute 2. See Also mysqli_stmt_fetch 2.10.14.MySQL Improved Extension (Mysqli) This function is an alias of mysqli_stmt_execute. Available only with mysqlnd. Warning This function is currently not documented.

MySQL Improved Extension (Mysqli) Example 2. print_r(mysqli_get_cache_stats()).130. ?> The above example will output something similar to: 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 239 . A mysqli_get_cache_stats example <?php $link = mysqli_connect().

• 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.MySQL Improved Extension (Mysqli) [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 [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 ) See Also Stats description 2. mysqli_get_metadata Copyright 1997-2012 the PHP Documentation Group. 240 .12.14.

Warning This function is currently not documented. mysqli_report Copyright 1997-2012 the PHP Documentation Group. mysqli_master_query Copyright 1997-2012 the PHP Documentation Group. string query).14.0. 2. • mysqli_master_query Enforce execution of a query on the master in a master/slave setup Description bool mysqli_master_query(mysqli link.3. Warning This function has been DEPRECATED and REMOVED as of PHP 5. mysqli_param_count Copyright 1997-2012 the PHP Documentation Group.14.MySQL Improved Extension (Mysqli) See Also mysqli_stmt_result_metadata 2. • mysqli_report Enables or disables internal report functions Description 241 . See Also mysqli_stmt_param_count 2. Notes Note mysqli_param_count is deprecated and will be removed.14. • mysqli_param_count Alias for mysqli_stmt_param_count Description This function is an alias of mysqli_stmt_param_count.15. only its argument list is available.13.14.

rather than per-process. "my_user". exit().15 & 5. Object oriented style <?php /* activate reporting */ mysqli_report(MYSQLI_REPORT_ALL). "my_password". } /* this query should report an error */ $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000"). Supported flags Name MYSQLI_REPORT_OFF MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT MYSQLI_REPORT_INDEX MYSQLI_REPORT_ALL Description Turns reporting off Report errors from mysqli function calls Throw mysqli_sql_exception for errors instead of warnings Report if no index or bad index was used in a query Set all options (report all) Return Values Returns TRUE on success or FALSE on failure. 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 Table 2. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* this query should report a bad index */ $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"). ?> See Also mysqli_driver::$report_mode mysqli_debug 242 . $mysqli->close(). $result->close().2.3.13. mysqli_report is a powerful function to improve your queries and code during development and testing phase.4 Description Changing the reporting mode is now be per-request. Examples Example 2.131. mysqli_connect_error()). $mysqli = new mysqli("localhost". Changelog Version 5.MySQL Improved Extension (Mysqli) bool mysqli_report(int flags). "world").

17. mysqli_rpl_parse_enabled Copyright 1997-2012 the PHP Documentation Group. mysqli_rpl_probe Copyright 1997-2012 the PHP Documentation Group. mysqli_send_long_data Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented.14. only its argument list is available. 243 . 2.14. Warning This function has been DEPRECATED and REMOVED as of PHP 5. • mysqli_rpl_probe RPL probe Description bool mysqli_rpl_probe(mysqli link).16.18.MySQL Improved Extension (Mysqli) mysqli_dump_debug_info 2.3. Warning This function has been DEPRECATED and REMOVED as of PHP 5.0. • mysqli_send_long_data Alias for mysqli_stmt_send_long_data Description This function is an alias of mysqli_stmt_send_long_data.14. • mysqli_rpl_parse_enabled Check if RPL parse is enabled Description int mysqli_rpl_parse_enabled(mysqli link). only its argument list is available.3. Warning This function is currently not documented. 2.0. Notes Note mysqli_send_long_data is deprecated and will be removed.

3. • mysqli_slave_query Force execution of a query on a slave in a master/slave setup Description bool mysqli_slave_query(mysqli link. mysqli_set_opt Copyright 1997-2012 the PHP Documentation Group. string query). 2. Warning This function has been DEPRECATED and REMOVED as of PHP 5.19. 244 .20. • mysqli_set_opt Alias of mysqli_options Description This function is an alias of mysqli_options.MySQL Improved Extension (Mysqli) See Also mysqli_stmt_send_long_data 2.14. mysqli_slave_query Copyright 1997-2012 the PHP Documentation Group. only its argument list is available. Warning This function is currently not documented.0.14.

as the driver uses the PHP memory management system. MySQL Native Driver (Mysqlnd) Copyright 1997-2012 the PHP Documentation Group. the MySQL database extensions would call down to the MySQL Client library file at run time. and is therefore released under the PHP license. Also. However.1. it always ensures the most efficient use of memory. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library. especially when it comes to memory usage. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. each row is stored in memory twice. it is important to note that it does not provide a new API to the PHP programmer. With MySQL Native Driver there is now an alternative. MySQL Native Driver is part of the official PHP sources as of PHP 5. MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). In the past. MySQL Native Driver is written in C as a PHP extension. as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library. So you do not need MySQL installed in order to build PHP or run PHP database applications. 3.Chapter 3. Therefore. mysqli and PDO MYSQL all communicate with the MySQL server. Special features MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. This removes licensing issues that have been problematic in the past. in the past. Because MySQL Native Driver is written as a PHP extension. it is tightly coupled to the workings of PHP. Also. mysqli_get_client_stats. 245 . you should not think of MySQL Native Driver as an API. when your PHP application was running. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server.0. The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. It also supports the PHP memory limit. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. whereas with the MySQL Native Driver each row is only stored once in memory.3. This ultimately led to MySQL support being disabled by default in PHP. mysqli and PDO MYSQL. These special features are listed below: • • • Improved persistent connections The special function mysqli_fetch_all Performance statistics calls: mysqli_get_cache_stats. The MySQL database extensions MySQL extension. so the file needed to be installed on your system. the MySQL Native Driver has been developed as part of the PHP project. Why use it? Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library. This leads to gains in efficiency. Overview Copyright 1997-2012 the PHP Documentation Group. this was done by the extension using the services provided by the MySQL Client Library. One example of the memory efficiency is the fact that when using the MySQL Client Library. What it is not Although MySQL Native Driver is written as a PHP extension. you needed to build the MySQL database extensions against a copy of the MySQL Client Library. The programmer APIs for MySQL database connectivity are provided by the MySQL extension. mysqli_get_connection_stats The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

with support for all MySQL extensions (i. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd.3. Passing in mysqlnd to the appropriate configure switch enables this support. Extensions such as ext/mysql. Changelog Version 5. can also take advantage of this feature. For example./configure --with-mysql=mysqlnd \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ [other options] Installation on Windows In the official PHP Windows distributions from 5..2 MySQL Native Driver supports the compressed client server protocol. All MySQL database extensions will use MySQL Native Driver in this case. mysqli and PDO_MYSQL). Passing in mysqlnd to configure is now optional. mysql. This is done through configuration options prior to building the PHP source code. The behaviour of these functions is affected by settings in php. The MySQL Native Driver is now the default for all MySQL extensions (i.2.3.3. SSL Support MySQL Native Driver has supported SSL since PHP version 5.3.0. In order to use the MySQL Native Driver..1.3 onwards.3 Compressed Protocol Support As of PHP 5. ext/mysqli. 3. 3. Runtime Configuration Copyright 1997-2012 the PHP Documentation Group. mysql. the following command would be given: . to build the MySQL extension.ini. Changelog Table 3.4.0 Installation on Unix The MySQL database extensions must be configured to use the MySQL Client Library. mysqli and PDO_MYSQL). PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. so no additional configuration is required to use it.e. Installation Copyright 1997-2012 the PHP Documentation Group.0 Description The MySQL Native Driver was added. Table 3.1. that are configured to use MySQL Native Driver. MySQL Native Driver did not support this in 5.2.e.3.MySQL Native Driver (Mysqlnd) MySQL Native Driver also allows for persistent connections when used with the mysqli extension. mysqli and PDO MYSQL using the MySQL Native Driver.0 and 5.3. 5. Named Pipes Support Named pipes support for Windows was added in PHP version 5.4. MySQL Native Driver Configuration Options 246 . MySQL Native Driver is enabled by default.

L .collect_statistics Default "1" Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM Changelog Available since PHP 5. i .file] but overwrites old file. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword.file] .Similar to a[. d . mysqlnd.0. mysqli_get_connection_stats.Similar to A[.net_cmd_buffer_size mysqlnd.collect_memory_s Enable the collection of various memory statistics which can be accessed through tatistics boolean mysqli_get_client_stats.debug = "option1[.Enables output from DBUG_<N> macros for the current state.modes. and does not append. 247 • • • • • • • • • .0. a[. This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics.net_read_timeout mysqlnd.collect_statisti Enables the collection of various client statistics which can be accessed through cs boolean mysqli_get_client_stats.3.3. mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well. mysqlnd. Available since PHP 5.functions] .Marks each debugger output line with the name of the source file containing the macro causing the output. The options for the format string are as follows: • A[. mysqlnd.changes. Also ensures that data is written after each write.3.0.file] . This is done by closing and reopening the trace file (this is slow).parameter_option2]]". An empty list of keywords implies output for all macros. mysqlnd."2048".net/manual/en/configuration. and does not append. Available since PHP 5.php. The format of the directive is mysqlnd.Appends trace output to the specified file. see the http://www. Here's a short explanation of the configuration directives.3.parameter_option1][:option2[.debug mysqlnd.1 . O[.0.3.3. This configuration setting enables all MySQL Native Driver statistics except those relating to memory management. 5.0 .3. Available since PHP 5.Marks each debugger output line with the current function nesting depth o[.debug string Records communication from all extensions using mysqlnd to the specified log file.file] but overwrites old file. mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well.0.0. Available since PHP 5. Available since PHP 5. mysqli_get_connection_stats.Marks each debugger output line with the name of the source file line number of the macro causing the output. It helps ensure a complete log file should the application crash.MySQL Native Driver (Mysqlnd) Name mysqlnd."4096" "32768" For further details and definitions of the PHP_INI_* modes.Limits debugger actions to the specified list of functions.net_read_buffer_size "0" "31536000" 5. An empty list of functions implies that all functions are selected.3.Marks each debugger output line with the PID of the current process.collect_memory_statist "0" ics mysqlnd.file] . f[. n . F .Appends trace output to specified file.file] .

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). COM_QUERY (“normal” query).2.ini. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above. mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer.net_read_timeout mysqlnd and the MySQL Client Library. size). x . This is set via php. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd. does not fit into the buffer. for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and./tmp/mysqlnd. ext/mysqli. mysqlnd will grow the buffer to the size required for sending the command. In later versions the default is 4096 bytes. mysqlnd. PHP streams may not have this limitation. 248 .ini setting mysqlnd.1. mysqlnd tells PHP Streams to use mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE. for example. sets a read timeout of 60s for streams.3. Example: d:t:x:O. you should consider increasing the default size to avoid re-allocations. This default applies to all streams that set no other timeout value.net_read_timeout.net_cmd_buffer_size bytes for almost every connection. The value can also be set using mysqli_option(link. 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. only for Windows. PHP. PDO_MySQL) that uses mysqlnd.net_cmd_buffer_size (in php. As of PHP 5. command_buffer_too_small will be incremented by one.0: the packet transports a very long error message.trace Note This feature is only available with a debug build of PHP.ini setting: mysqlnd. The default can changed either through the php. In PHP 5. The default buffer size is 2048 bytes in PHP 5. mysqlnd integer uses PHP streams.N] . MYSQLI_OPT_NET_CMD_BUFFER_SIZE. mysqlnd. If a MySQL Client Server protocol command. mysqlnd is unable to decode the packet and the client application will get an error. mysqlnd now uses the same very long timeout. Please check the streams documentation.3.0.net_read_timeout gets used by any extension (ext/mysql.Enables function control flow tracing. and defaults to 200. 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. The value is configurable through a new php. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams.This option activates profiling. by default. mysqlnd. 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. int size).0. prior to MySQL 5. The maximum nesting depth is specified by N. such as TCP/IP timeouts.net_read_timeout.2 mysqlnd does not allow setting buffers smaller than 4096 bytes. if in doubt.MySQL Native Driver (Mysqlnd) • • t[. whereas libmysql uses its own wrapper around the operating level network calls.3. default_socket_timeout.3. libmysql use different networking APIs. As a consequence.net_cmd_buffer_s mysqlnd allocates an internal command/network buffer of ize long mysqlnd. Whenever the buffer gets extended for one connection.ini) bytes for every connection.

The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. Statistics Copyright 1997-2012 the PHP Documentation Group. 3. mysqlnd has to call read() multiple times. For example: shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" . mysqlnd reads the body in chunks of MIN(header.5.4. these statistics can be obtained through three API calls: • • • mysqli_get_client_stats mysqli_get_connection_stats mysqli_get_cache_stats 249 . Other extension-driver combinations use COM_PING on initial use of a persistent connection. Using Persistent Connections If mysqli is used with mysqlnd. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable. This ensures that re-authentication of the connection takes place. size).size. The MySQL client server protocol encapsulates all its commands in packets. The value can also be set using mysqli_optionS(link. it is possible to switch this off at compile time. Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT. MYSQLI_OPT_NET_READ_BUFFER_SIZE.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd. Persistent Connections Copyright 1997-2012 the PHP Documentation Group. when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mys 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. As there is some overhead associated with the COM_CHANGE_USER call.net_read_buffer_size bytes. 3. The statistics gathered are of three main types: • • • Client statistics Connection statistics Zval cache statistics If you are using the mysqli extension. Using Statistical Data MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. mysqlnd.MySQL Native Driver (Mysqlnd) size long Maximum read chunk size in bytes when reading the body of a MySQL command packet.

You can configure the PDO MySQL Driver. The function call does not require any parameters. Accessing Connection Statistics To access connection statistics call mysqli_get_connection_stats. These statistics can be accessed by calling mysqli_get_cache_stats. both function calls of ext/mysql and ext/mysqli will change the statistics. you need to call mysqli_get_client_stats. This takes the database connection handle as the parameter. The Zval cache statistics obtained may lead to a tweaking of php. Buffered result sets are cached on the client. The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value. Accessing Client Statistics To access client statistics. use unbuffered results. Prepared Statements use unbuffered result sets by default. ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Accessing Zval Cache Statistics The MySQL Native Driver also collects statistics from its internal Zval cache. However. 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.the server also needs to keep other resources open. you can use mysqli_stmt_store_result to enable buffered result sets. Network Statistic Scope Description Notes bytes_se Connection Number of bytes sent from PHP to the MySQL serv. ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. all three extensions will change the statistics. If you experience a high server load and the figures for unbuffered result sets are high. Clients typically scale better than servers. When doing so. For example. you should consider moving the load to the clients.Can be used to check the efficiency of the compresnt er sion protocol bytes_re Connection Number of bytes received from MySQL server ceived packConnection Number of MySQL Client Server protocol packets ets_sent sent packConnection Number of MySQL Client Server protocol packets ets_rece received 250 Can be used to check the efficiency of the compression protocol Used for debugging Client Server protocol implementation Used for debugging Client Server protocol implementation . The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set. but increase load on the server. Buffered and Unbuffered Result Sets Result sets can be buffered or unbuffered. resulting in better performance. mysqli_get_connection_stats and mysqli_get_cache_stats functions. when compiling both ext/ mysql and ext/mysqli against MySQL Native Driver. Using default settings. before a result set can be freed. “Load” does not only refer to memory buffers . After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. Client statistics can also be accessed by calling the phpinfo function.MySQL Native Driver (Mysqlnd) Note Statistics are aggregated among all extensions that use MySQL Native Driver. for example file handles and threads.ini settings related to the Zval cache. once the results have been fetched by the client. The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value. Statistics returned by MySQL Native Driver The following tables show a list of statistics returned by the mysqli_get_client_stats. Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client.

Note that the total size in bytes includes the size set_row_ transport an error or an EOF packet. ceive the expected packet but. packConnection Number of MySQL Client Server protocol EOF Used for debugging CS protocol implementation. bytes_re Connection Total size in bytes of MySQL Client Server protocol Used for debugging CS protocol implementation. see protocol overhead). see protocol overhead). EOF can transport an the header packet (4 bytes. The length of the status message can the header packet (4 bytes. UPDATE.the header packet (4 bytes. bytes_re Connection Total size in bytes of MySQL Client Server protocol Only useful for debugging CS protocol implementaceived_r result set row data packets. ived_rse t_field_ meta Only useful for debugging CS protocol implementation.Note that the total size in bytes includes the size of of_packe ing on the server version. ived_rse t_row Only useful for debugging CS protocol implementation. The packet may also tion. OK packets can contain a Note that the total size in bytes includes the size of k_packet status message. bytes_re Connection Total size in bytes of MySQL Client Server protocol Used for debugging CS protocol implementation. error message). Note that the total size in bytes includes the size set_fiel course the size varies with the fields in the result set. d_meta_p The packet may also transport an error or an EOF acket packet in case of COM_LIST_FIELDS. bytes_re Connection Total size in bytes of MySQL Client Server protocol Only useful for debugging CS protocol implementa251 . prohead_out tocol_overhead_out = packets_sent * 4 bytes_re Connection Total size of bytes of MySQL Client Server protocol Used for debugging CS protocol implementation. see protocol overhead). packConnection Number of MySQL Client Server protocol result set ets_rece row data packets and their total size in bytes. see protocol overhead). see protocol overhead). er_packe FILE.Used for debugging CS protocol implementation. an error message. packConnection Number of MySQL Client Server protocol OK pack. Like with other packet statistics the number Note that the total size in bytes includes the size of ived_eof of packets will be increased even if PHP does not re. see protocol overhead). ceived_o OK packets received. Currently only the Packet Header mentation er(4 bytes) is considered as overhead. see protocol overhead). INSERT. SELECT. packConnection Number of MySQL Client Server protocol result set ets_rece meta data (field information) packets. vary and thus the size of an OK packet is not fixed. prohead_in tocol_overhead_in = packets_received * 4 proConnection MySQL Client Server protocol overhead in bytes for Used for debugging Client Server protocol impletocol_ov outgoing traffic. ived_rse t_header Used for debugging CS protocol implementation. EOF can vary in size depend. Note that the total size in bytes includes the size of the header packet (4 bytes.MySQL Native Driver (Mysqlnd) Statistic ived Scope Description Notes proConnection MySQL Client Server protocol overhead in bytes for Used for debugging Client Server protocol impletocol_ov incoming traffic. see protocol overhead). You can reverse of the header packet (4 bytes. see protocol overhead). Note that the total size in bytes includes the size of ived_ok the header packet (4 bytes. for example.the header packet (4 bytes. t error message. Currently only the Packet Header (4 mentation erbytes) is considered as overhead. Of tion. Also.Note that the total size in bytes includes the size of set_head ies depending on the payload (LOAD LOCAL IN. bytes_re Connection Total size in bytes of MySQL Client Server protocol Only useful for debugging CS protocol implementaceived_r result set meta data (field information) packets. ets_rece ets received. ets_rece packets. packet engineer the number of error and EOF packets by substracting rows_fetched_from_server_normal and rows_fetched_from_server_ps from bytes_received_rset_row_packet. Note that the total size in bytes includes the size of the header packet (4 bytes. Note that the total size in bytes includes the size of the header packet (4 bytes. The size of the packets var. ceived_r result set header packets. of the header packet (4 bytes. see protocol overhead). ceived_e EOF packets received. t packConnection Number of MySQL Client Server protocol result set ets_rece header packets.

bytes_re Connection Number of bytes of payload fetched by the PHP cliceived_r ent from mysqlnd using the text protocol. $res = $mysqli->query("SELECT 'abc'"). Note that although a full result set may have been pulled from MySQL by mysqlnd. The only error recoded is command_buffer_too_small (see below). see protocol overhead). The packet may tion. 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. of the header packet (4 bytes. There is no way to tion. for example. Every fetch operation will increase the value. eal_data _normal 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 the total size in bytes includes the size hange_us also transport an error or EOF. this statistic only counts actual data pulled from mysqlnd by the PHP client. pare_res ponse bytes_re Connection Total size in bytes of MySQL Client Server protocol Only useful for debugging CS protocol implementaceived_c COM_CHANGE_USER packets. You may be able to guess that an error has occurred if. such as in the following example: $mysqli = new mysqli(). Only useful for debugging CS protocol implementation. See also ps_prepared_never_executed. er_packe t packConnection Number of MySQL Client Server protocol ets_rece COM_CHANGE_USER packets ived_cha nge_user Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size (prepared statement init packets). The statistic will not be increased if the result set is only buffered on the client. _command know which specific commands and how many of them have been sent. but not fetched. The packet may of the header packet (4 bytes. There is no safe way to know how many errors happened. you always connect to MySQL 5. also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.MySQL Native Driver (Mysqlnd) Statistic ceived_p repare_res ponse_pa cket Scope Description Notes OK for Prepared Statement Initialization packets tion. bytes_received_prepare_response_pac ket != packets_received_prepare_response * 12. packConnection Number of MySQL Client Server protocol comOnly useful for debugging CS protocol implementaets_sent mands sent from PHP to MySQL. $res = $mysqli->query("SELECT 'abc'"). $res->close(). An example of a code sequence that will increase the value is as follows: $mysqli = new mysqli(). packConnection Number of MySQL Client Server protocol OK for ets_rece Prepared Statement Initialization packets (prepared ived_pre statement init packets). $res->fetch_assoc(). see protocol overhead).0 or newer and. ps_prepared_once_executed.0 on. Note that the total size in bytes includes the size of the header packet (4 bytes. see protocol overhead). There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. see protocol overhead).1 and 12 bytes from MySQL 5. Note that the total size in bytes includes the size of the header packet (4 bytes. $res->close(). 252 .

there is an error reading the result set header packet from the line.4. If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. this statistic only counts actual data pulled from mysqlnd by the PHP client. bytes_re Connection Number of bytes of the payload fetched by the PHP ceived_r client from mysqlnd using the prepared statement eal_data protocol. bad_inde Connection Number of queries that have generated a result set x_used and did not use a good index (see also mysqld start option –log-slow-queries). mysqli_store_result.to identify a client that causes a high database load. UPDATE. You may use it as an indirect measure for the numlt_set_q Examples of queries that do not generate a result set: ber of queries PHP has sent to MySQL. Result Set Statistic Scope Description Notes resConnection Number of queries that have generated a result set.3. _ps 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. ueries INSERT.MySQL Native Driver (Mysqlnd) Statistic Scope Description Notes This statistic is available as of PHP version 5. Note that although a full result set may have been pulled from MySQL by mysqlnd.4. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. You may use it as an indirect measure for the numult_set_ Examples of queries that generate a result set: SE. for example. See also bytes_received_real_data_normal. SHOW. Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. for example. The stat. bufConnection Number of buffered result sets returned by “normal” Examples of API calls that will buffer result sets on fered_se queries. mysqli_query. queries LECT.ber of queries PHP has sent to MySQL. This is also the reason why memory_get_usage reports a higer memory con253 . istic will not be incremented if there is an error reading the result set header packet from the line. The downside is the additional memory consumption on the client for buffering data.3. mysqli_stmt_get_result. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT) slow_que Connection SQL statements that took more than Not reported through mysqli_report ries long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. The value will not be increased if the result set is not subsequently read by the PHP client. SHOW. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT). This statistic is available as of PHP version 5. ts in the following notes. LOAD DATA. “Normal” means “not prepared statement” the client: mysql_query. non_resu Connection Number of queries that did not generate a result set. The statistic will not be incremented if to identify a client that causes a high database load. no_index Connection Number of queries that have generated a result set _used but did not use an index (see also mysqld start option –log-queries-not-using-indexes).

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_prepa Connection Number of statements prepared but never executed. red_once _execute d Prepared statements occupy server resources. if statement execution is split up in separate prepare and execute 254 . See also rows_skipped_normal. 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! unbufConnection Number of unbuffered result sets returned by normal Examples of API calls that will not buffer result sets fered_se (non prepared statement) queries. If the application does not fetch all rows from an unbuffered result set. ps_unbuf Connection Number of unbuffered result sets returned by prefered_se pared statements.MySQL Native Driver (Mysqlnd) Statistic Scope Description Notes sumption when using mysqlnd instead of the MySQL Client Library. mysqlnd does implicitly fetch the result set to clear the line. on the client: mysqli_use_result ts ps_buffe Connection Number of buffered result sets returned by prepared red_sets statements. ts flushed_ Connection Number of result sets from normal (non prepared norstatement) queries with unread data which have been mal_sets flushed silently for you. rows_skipped_ps. red_neve r_execut ed ps_prepa Connection Number of prepared statements executed only one. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. Flushing happens only with unbuffered result sets. See also rows_skipped_normal. You should not prepare a statement if you do not plan to execute it. Flushing happens only with unbuffered result sets. If the application does not fetch all rows from an unbuffered result set. rows_skipped_ps. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. mysqlnd does implicitly fetch the result set to clear the line. 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 • flushed_ Connection Number of result sets from prepared statements with ps_sets unread data which have been flushed silently for you. 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. Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_result By default prepared statements are unbuffered. By default prepared statements are unbuffered.

MySQL Native Driver (Mysqlnd) Statistic Scope Description Notes stages. prepared statements that are executed only once may cause performance hurts. the parse tree to be reused during multiple statement executions. have been fetched by the client application but have rows_fet been flushed implicitly. mysqli_query. Consequently. mysqli_store_result om_clien This is the number of rows that have been fetched from MySQL and buffered on client. The idea is to prepare once and “cache” results. for example.Examples of queries that will buffer results: fered_fr ing from a "normal" query or a prepared statement. 255 . 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. ched_fro m_server _ps See also packets_received_rset_row rows_buf Connection Total number of succesfully buffered rows originat. 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 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. Some of the rows may not _normal. rows_fet Connection Total number of result set rows successfully fetched ched_fro from MySQL regardless if the client application has m_server consumed them or not.

_normal_ 256 . rows_buf fered_fr om_clien t_ps Scope Description Notes rows_fet Connection Total number of rows fetched by the client from a ched_fro buffered result set created by a normal query or a m_client prepared statement.MySQL Native Driver (Mysqlnd) Statistic .

MySQL Native Driver (Mysqlnd)

Statistic , rows_fet ched_fro m_client _ps_buff ered

Scope

Description

Notes

rows_fet Connection Total number of rows fetched by the client from a ched_fro unbuffered result set created by a "normal" query or m_client a prepared statement. _normal_ unbuffered, rows_fet ched_fro m_client _ps_unbu ffered rows_fet Connection Total number of rows fetch by the client from a cursched_fro or created by a prepared statement. m_client _ps_curs or rows_ski Connection Reserved for future use (currently not supported) pped_nor mal, rows_ski pped_ps copy_on_ Process write_sa ved, copy_on_ write_pe rformed 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. The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)

explicit_free _result, implicit_free _result

Connection, Total number of freed result sets. Process (only during prepared statement cleanup)

proto_te Connection Total number of columns of a certain type fetched xt_fetch from a normal query (MySQL text protocol). ed_null, proto_te xt_fetch ed_bit, proto_te xt_fetch ed_tinyi nt proto_te xt_fetch

Mapping from C API / MySQL meta data type to statistics name: • • • • • 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 -

257

MySQL Native Driver (Mysqlnd)

Statistic , proto_te xt_fetch

Scope

Description

Notes proto_text_fetched_int24 • • • MYSQL_TYPE_LONG - proto_text_fetched_int MYSQL_TYPE_LONGLONG proto_text_fetched_bigint MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL 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_TIMESTAMP proto_text_fetched_timestamp MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR proto_text_fetched_string MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, 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_geometry 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.

258

MySQL Native Driver (Mysqlnd)

Statistic , proto_te xt_fetch ed_int proto_te xt_fetch ed_bigin t, proto_te xt_fetch ed_decim al, proto_te xt_fetch ed_float proto_te xt_fetch ed_doubl e, proto_te xt_fetch ed_date, proto_te xt_fetch ed_year proto_te xt_fetch ed_time, proto_te xt_fetch ed_datet ime, proto_te xt_fetch ed_times tamp proto_te xt_fetch ed_strin g, proto_te xt_fetch ed_blob, proto_te xt_fetch ed_enum proto_te xt_fetch ed_set, proto_te xt_fetch ed_geome try, proto_te xt_fetch ed_other

Scope

Description

Notes

proto_bi Connection Total number of columns of a certain type fetched For type mapping see proto_text_* described in nary_fet from a prepared statement (MySQL binary protocol). the preceding text. ched_nul l, proto_bi nary_fet 259

MySQL Native Driver (Mysqlnd)

Statistic

Scope

Description

Notes

260

MySQL Native Driver (Mysqlnd)

Statistic , proto_bi nary_fet ched_tin yint proto_bi nary_fet ched_sho rt, proto_bi nary_fet ched_int 24, proto_bi nary_fet

Scope

Description

Notes

261

proto_bi nary_fet ched_yea r.MySQL Native Driver (Mysqlnd) Statistic . proto_bi nary_fet ched_big int. proto_bi nary_fet Scope Description Notes 262 . proto_bi nary_fet ched_dat e. proto_bi nary_fet ched_blo b. proto_bi nary_fet ched_dat etime. proto_bi nary_fet ched_dou ble. proto_bi nary_fet ched_flo at. proto_bi nary_fet ched_dec imal. proto_bi nary_fet ched_tim estamp. proto_bi nary_fet ched_str ing. proto_bi nary_fet ched_tim e. proto_bi nary_fet ched_enu m.

active_persistent_connections. $link->connect(..) $link = new mysqli(.).close implicitly to avoid returning a connection with unknown options 263 ..) impliConnection Total number of implicitly closed connections cit_clos (ext/mysqli only). ections actConnection Total number of active persistent connections. Examples of code snippets that cause an explicit close : $link = new mysqli(. e The total number of active non-persistent connections is active_connections ..... proto_bi nary_fet ched_oth er Scope Description Notes Connection Statistic Scope Description Notes Reused connections and all other kinds of connections are included. e Examples of code snippets that cause an implicit close : • • • $link = new mysqli(.. $link->real_connect(. connect_fai lure reconnect Process Total number of (real_)connect attempts made on an The code sequence $link = new already opened connection handle.Note that connect_success holds the sum of nect_suc tempts..). conConnection Total number of successful / failed connection atnect_suc tempt... successful persistent and non-persistent connection cess attempts. actConnection Total number of active persistent and non-persistent ive_conn connections.) will explicitly close the existing connection before a new connection is established.) will cause a reconnect.... cess.MySQL Native Driver (Mysqlnd) Statistic ..)... ive_pers istent_conn ections expliConnection Total number of explicitly closed connections cit_clos (ext/mysqli only). $link->close(...) unset($link) Persistent connection: pooled connection has been created with real_connect and there may be unknown options set . $link->real_connect(.. But $link = new mysqli(.).. pconConnection Total number of successful persistent connection at.. The number of successful non-persistent connection attempts is connect_success pconnect_success. mysqli(.) will not because $link->connect(. proto_bi nary_fet ched_geo metry.).. $link->connect(.

In case of a failure mysqlnd emits a PHP warning “Error while sending %s packet..Connection Connection failures indicated by the C API call nect_clo mysql_real_connect during an attempt to esse tablish a connection. COM_* Commands Statistic Scope Description Notes The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. for example. while fetching data.). cuted_co mysqli_options(MYSQLI_INIT_COMMAND unt . in_middl Process e_of_com mand_clo se A connection has been closed in the middle of a command execution (outstanding result sets not fetched. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. init_com Connection Total number of failed init commands.MySQL Native Driver (Mysqlnd) Statistic Scope Description Notes • • 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 discon. while transferring data with LOAD DATA).” Usage examples: • Check if PHP sends certain commands to MySQL. 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 Connection Total number of attempts to send a certain COM_* command from PHP to MySQL. PID=%d. . for exmand_exe ample. after sending a query and before retrieving an answer. Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you. • • • 264 . init_com Connection Total number of init command executions.. It is called disconnect_close because the connection handle passed to the C API call will be closed. mand_fai led_coun t The number of successful executions is init_command_executed_count init_command_failed_count.

com_crea te_db. com_fiel d_list. com_shut down. com_proc Scope Description Notes 265 . com_quer y.MySQL Native Driver (Mysqlnd) Statistic . com_stat istics. com_drop _db. com_init _db. com_refr esh.

MySQL Native Driver (Mysqlnd) Statistic . com_conn ect. com_proc Scope Description Notes 266 .

com_debu g. Scope Description Notes 267 .MySQL Native Driver (Mysqlnd) Statistic .

MySQL Native Driver (Mysqlnd) Statistic . Scope Description Notes 268 .

com_regi ster_sla ve. com_chan ge_user. com_conn ect_out. com_tabl e_dump. com_dela yed_inse rt. com_stmt Scope Description Notes 269 .MySQL Native Driver (Mysqlnd) Statistic . com_binl og_dump.

com_stmt Scope Description Notes 270 .MySQL Native Driver (Mysqlnd) Statistic .

com_stmt _set_opt ion. mem_erea lloc_cou nt. mem_mall Memory management calls. Notes A close is always considered explicit but for a failed prepare. com_daem on Scope Description Notes Miscellaneous Statistic Scope Description Total number of close prepared statements.MySQL Native Driver (Mysqlnd) Statistic . com_stmt _send_lo ng_data. com_stmt _reset. implicit_stmt _close mem_emal Process loc_coun t. mem_erea lloc_amm ount. com_stmt _fetch. mem_ecal loc_ammo unt. mem_ecal loc_coun t. mem_efre e_count. Development only. expliProcess cit_stmt _close. mem_emal loc_ammo unt. 271 . com_stmt _close.

MySQL Native Driver (Mysqlnd) Statistic . mem_call Scope Description Notes 272 . mem_mall oc_ammou nt.

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).net_cmd_buffer_size in PHP 5. mysqlnd will grow the buffer to what is needed for sending the command. mem_free _count Scope Description Notes comConnection Number of network command buffer extensions mand_buf while sending commands from PHP to MySQL.it should happen rarely.3. If a MySQL Client Server protocol command.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_B UFFER_SIZE. you should consider to increase the default size to avoid re-allocations. mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. for example. In PHP 5.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.3. connection_reu sed 273 .0.MySQL Native Driver (Mysqlnd) Statistic . mem_real loc_coun t. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one. COM_QUERY (normal query). There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd. mem_call oc_ammou nt. fer_too_ small mysqlnd allocates an internal command/network buffer of mysqlnd.3. The default buffer size is 2048 bytes in PHP 5. int size). As of PHP 5. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd. No bug report on this exists .0. mem_real loc_ammo unt.net_cmd_buffer_size (php.ini) bytes for every connection. The default can changed either through the php.3.ini) bytes for almost every connection.net_cmd_buffer_size (php. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. does not fit into the buffer.ini setting mysqlnd. In future versions the default will be 4kB or larger. 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.

For example. SELECT LIMIT part_n. • Load Balancing • • • • Read/Write Splitting. There are no restrictions on manipulating mysqlnd internal function tables. mysqlnd plugins do not have some of MySQL Proxy's disadvantages.. 3. using SELECT .php. The ability to manipulate mysqlnd internal function tables in this way allows maximum flexibility for plugins. The following list represents some possible applications of mysqlnd plugins. Mysqlnd plugins can undertake typical MySQL Proxy tasks such as load balancing. Internal mysqlnd function calls can also be intercepted. No application changes are needed because plugins operate on a different layer. This extension inspects queries and executes only those that are allowed according to a ruleset. It sends the queries to distinct MySQL servers and merges the result at the client. As a result. It is possible to set things up so that when certain mysqlnd functions are called by the extensions that use mysqlnd. Mysqlnd plugins operate in the layer between PHP applications and the MySQL server. An example of this is the PECL/mysqlnd_qc (Query Cache) extension.7. and PDO_MYSQL. • Performance • • • Caching. Plugins can be made 100% transparent to PHP applications.net/manual/en/book. A mysqlnd plugin can be thought of as an extension to mysqlnd. the call is directed to the appropriate function in the mysqlnd plugin. This is comparable to MySQL Proxy. For mysqlnd. it is possible for a mysqlnd plugin to intercept all calls made to these extensions from the client application. This extension splits read/write queries for a replication setup. This extension will attempt to split a SELECT statement into n-parts. Failover Round-Robin. with plugins. Throttling Sharding. the MySQL server.stream) should be consulted on such details as timeout settings.MySQL Native Driver (Mysqlnd) 3. 274 . LIMIT part_1.6. mysqlnd). An example of this is the PECL/mysqlnd_ms (Master Slave) extension. not the documentation for the MySQL Client Library. Plugins can intercept the majority of mysqlnd functions. written in C. MySQL Native Driver Plugin API Copyright 1997-2012 the PHP Documentation Group. that use the mysqlnd plugin API (which is built into MySQL Native Driver. MySQL Proxy operates on a layer between any MySQL client application. Due to the different architecture and location. a PHP application and. monitoring and performance optimizations. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. least loaded Monitoring • • • Query Logging Query Analysis Query Auditing. the PHP streams documentation (http://www. The mysqlnd functions are called by the PHP MySQL extensions such as ext/mysql. This section provides a collection of miscellaneous notes on MySQL Native Driver usage. there is no single point of failure. for example. Mysqlnd plugins are in fact PHP Extensions. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension.. and no new programming language to learn (Lua). or replaced. • Using mysqlnd means using PHP streams for underlying connectivity. The mysqlnd plugin can be thought of as operating in a layer below mysqlnd. or mysqlnd. The MySQL Native Driver Plugin API is a feature of MySQL Native Driver. Notes Copyright 1997-2012 the PHP Documentation Group. ext/mysqli. no dedicated proxy server to deploy.

which mirrors the libmysql client and Connector/C APIs. Plugins can therefore parse. MySQL Proxy can also share one-time computed results among multiple application servers. as all state can be retained. a mysqlnd plugin gets installed on the PHP application server. manipulate and even replace the communication 275 . 2. scale by client) MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications.Multi Connect plugin. without the need to program at the level of the wire protocol. MySQL Proxy does have some disadvantages: • • MySQL Proxy is a new component and technology to master and deploy. MySQL Proxy can be customized with C and Lua programming.Prepared Statement Handle Cache plugin. PECL/mysqlnd_ms . MySQL Proxy runs as a daemon . 3. Lua is the preferred scripting language of MySQL Proxy. such as Memcache. as it is sometimes called.7. Mysqlnd plugins and MySQL Proxy are different technologies using different approaches. reverse engineer. PECL/mysqlnd_sip . With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. along with the rest of PHP.SQL Injection Protection plugin. or wire protocol. a mysqlnd plugin is bound to the request-based lifecycle of PHP. A comparison of mysqlnd plugins with MySQL Proxy Copyright 1997-2012 the PHP Documentation Group. PECL/mysqlnd_pscache .1. You can intercept all C API calls. As a PHP Extension. Actions are limited to those that can be achieved by manipulating the communication protocol. Deploying MySQL Proxy on the application server has two advantages: 1. monitoring. MySQL Proxy can either be run on the PHP application server or can be installed on a dedicated machine to handle multiple PHP application servers. It is also possible to write plugins in PHP using PECL/mysqlnd_uh. MySQL Proxy works on top of the wire protocol. This C API is basically a wrapper around the MySQL Client Server protocol. PECL/mysqlnd_uh . This gives MySQL Proxy an advantage in this case.a background process. PHP makes use of the C API. For most PHP experts Lua is a new language to learn. Another daemon would need to be used for this purpose. Mysqlnd plugins work on top of the C API. MySQL Proxy requires knowledge of the Lua scripting language. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. MySQL Proxy can recall earlier decisions.Query Cache plugin. and performance enhancements.MySQL Native Driver (Mysqlnd) MySQL Native Driver Plugins Available There are a number of mysqlnd plugins already available. A mysqlnd plugin can be written in C. Mysqlnd implements the wire protocol. An important difference is that MySQL Proxy works with all MySQL clients. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well.User Handler plugin. No single point of failure Easy to scale out (horizontal scale out. Both are valid tools for solving a variety of common tasks such as load balancing.Master Slave plugin. However. therefore you can hook all PHP calls. These include: • • • • • • PECL/mysqlnd_mc . However. whereas mysqlnd plugins are specific to PHP applications. PECL/mysqlnd_qc .

c mysqlnd. ext/mysqlnd.3. However. or through source snapshot downloads. As plugins allow you to create implementations that use two levels (C API and wire protocol).c mysqlnd_wireprotocol. which is an integer such as 50007.7 5.0.0.5 5. MySQL Native Driver Overview Before developing mysqlnd plugins.3.0.0 5. and as such is available to the public either via SVN.3. It is developed as part of the PHP source repository.3 5. any subsequent changes to the wire protocol do not require changes to the plugin itself. This section provides an overview of the mysqlnd plugin architecture. PHP Version 5.0. it is useful to know a little of how mysqlnd itself is organized.7.c 276 . Mysqlnd consists of the following modules: Modules Statistics Connection Resultset Resultset Metadata Statement Network Wire protocol mysqlnd_statistics.c mysqlnd_result_meta.3.c mysqlnd_net.7. The following table shows PHP versions and the corresponding mysqlnd version contained within. 3.7-dev . If a mysqlnd plugin is implemented using the C API.MySQL Native Driver (Mysqlnd) protocol. developers should refer to the mysqlnd version number for compatibility and version tests. The mysqlnd plugin API is simply part of the MySQL Native Driver PHP extension. or through MYSQLND_VERSION_ID.2 5. 3. Development started on the mysqlnd plugin API in December 2009.3. Obtaining the mysqlnd plugin API Copyright 1997-2012 the PHP Documentation Group.0. which is a string of the format “mysqlnd 5. as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.0.7 5.2.3.c mysqlnd_result.c mysqlnd_ps. they have greater flexibility than MySQL Proxy. this is usually not required.5 5. MySQL Native Driver Plugin Architecture Copyright 1997-2012 the PHP Documentation Group.091210 .$Revision: 300535”. 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.4 MySQL Native Driver version 5.1 5.7 Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION.

As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required. The function table is a global shared resource. The extension can perform any variable setup and resource allocation required for request processing. query). When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension. Members of the struct represent object properties. and replacing it by a custom function table. backing it up. unsigned int query_len TSRMLS_DC) { php_printf("my_conn_class::query(query = %s)\n". query). /* backup original function table */ memcpy(&org_methods. there are some conventions that need to be followed that will be discussed later. In an multi-threaded environment. void minit_register_hooks(TSRMLS_D) { /* active function table */ struct st_mysqlnd_conn_methods * current_methods = mysqlnd_conn_get_methods(). there are no fixed rules on inheritance in the C object oriented paradigm. This is achieved by obtaining the mysqlnd function table.MySQL Native Driver (Mysqlnd) C Object Oriented Paradigm At the code level. During the lifetime of the PHP engine it will receive a number of requests.the parent methods. 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. In C you use a struct to represent an object. it is vital to call the parent method prior to any other activity in the derived method. Unlike with other languages such as C++ or Java. Each request constitutes another life cycle. 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. current_methods. such as for Connection::stmt_init(). /* install new methods */ current_methods->query = MYSQLND_METHOD(my_conn_class. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. 277 . mysqlnd uses a C pattern for implementing object orientation. The function table may change at any time in the future. it is still possible to call the original function table entries . const char *query. In some cases. with a TSRM build. However. } Connection function table manipulations must be done during Module Initialization (MINIT). sizeof(struct st_mysqlnd_conn_methods). How a plugin works A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. 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. Struct members pointing to functions represent methods. the manipulation of a global shared resource during the request processing will almost certainly result in conflicts. MYSQLND_METHOD(my_conn_class. On each request the PHP engine will call the request initialization function of each extension. Calling parent methods If the original function table entries are backed up. which calls the functions of the plugin as required. query)(MYSQLND *conn.

query(conn. my_plugin_id). mysqlnd reserves space for one void * pointer per plugin. When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data.see Extending Connection: methods */ } static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) { MY_CONN_PROPERTIES** props. sizeof(MY_CONN_PROPERTIES). 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. void minit_register_hooks(TSRMLS_D) { /* obtain unique plugin ID */ my_plugin_id = mysqlnd_plugin_register(). props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data( conn. These functions are named using the convention: mnd_*loc(). } return props. such as the ability to use a debug allocator in a non-debug build. which is allowed. Users of mysqlnd objects cannot simply add properties to the objects. } The plugin developer is responsible for the management of plugin data memory. } MY_CONN_PROPERTIES. if (!props || !(*props)) { *props = mnd_pecalloc(1. (*props)->query_counter = 0. Use of the mysqlnd memory allocator is recommended for plugin data. The mysqlnd allocator has some useful features. It is not possible to add a member to a C struct at run time. query_len = strlen(query). /* plugin id */ unsigned int my_plugin_id. /* snip . return org_methods.MySQL Native Driver (Mysqlnd) query = "SELECT 'query rewritten' FROM DUAL". Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. query_len). conn->persistent). 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() mysqlnd_stmt_get_methods() mysqlnd_net_get_methods() or Resultset Meta MINIT (MYSQLND_RES_METADAT A) Statement (MYSQLND_STMT) MINIT Network (MYSQLND_NET) MINIT or later 278 No No Yes . /* return with call to parent */ } Extending properties A mysqlnd object is represented by a C struct. query. 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.

Wire Protocol. Each object uses its own function table. it can be useful to subclass constructors. Regardless of all warnings. construction. Other classes use copies of a globally shared function table. All instances of such a class will share the same function table. after method execution yes. Constructors Allocation. 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. in particular in threaded environments. such as Resultset. after method execution yes. Network.MySQL Native Driver (Mysqlnd) object method function table manipulation Wire protocol (MYSQLND_PROTOCOL) MINIT or later Yes mysqlnd_protocol_get_methods( ) or object method function table manipulation You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table. There is no need to copy a function table for each and every object. reset Connection (MYSQLND) Resultset(MYSQLND_RES) Allocation: • • Connection::result_init() • • Reset and re-initialized during: • • • Result::use_result() Result::store_result Yes. you should at least call the parent constructor before doing anything in your constructor. If you do not care about warnings and insist on hooking the constructors. 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() Yes. but call parent! No No Connection::stmt_init() Connection::init() Connection::init() It is strongly recommended that you do not entirely replace a constructor. after method execution yes. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables. and you can additionally refine methods of an object without impacting other instances of the same class. free_stmt_content() free() . The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. after method execution yes. end_psession() free_result() free() dtor(). The constructors perform memory allocations. Destruction Derived method must call parent? Connection Resultset Resultset Meta Statement Network yes. after method execution 279 Destructor free_contents(). The class function table copy is created together with the object. such function tables must only be manipulated during MINIT. Some classes contain a pointer to the method function table. To avoid chaos. This gives you two options: you can manipulate the default function table of an object at MINIT. The advantage of the shared function table approach is performance.

This has been fixed in PHP 5.4.4.3. free your memory and call the parent implementation immediately following this.3. As with constructors you may replace the methods entirely but this is not recommended. However.3. The mysqlnd plugin API Copyright 1997-2012 the PHP Documentation Group. 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.0 to 5.MySQL Native Driver (Mysqlnd) Wire protocol yes. Caution Due to a bug in PHP versions 5. they are the best possible place for you to hook in and free your plugin data. 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. mysqlnd_plugin_get_plugin_<object>_data(). Components often found in plugins mechanisms are: • • • • A plugin manager A plugin API Application services (or modules) Application service APIs (or module APIs) 280 . The recommended method for plugins is to simply hook the methods. The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. after method execution free() The destructors are the appropriate place to free properties.3. plugins do not associate plugin data with a persistent connection. The following is a list of functions provided in the mysqlnd plugin API: • • • • • • • • • • • • • mysqlnd_plugin_register() mysqlnd_plugin_count() mysqlnd_plugin_get_plugin_connection_data() mysqlnd_plugin_get_plugin_result_data() mysqlnd_plugin_get_plugin_stmt_data() mysqlnd_plugin_get_plugin_net_data() mysqlnd_plugin_get_plugin_protocol_data() mysqlnd_conn_get_methods() mysqlnd_result_get_methods() mysqlnd_result_meta_get_methods() mysqlnd_stmt_get_methods() mysqlnd_net_get_methods() mysqlnd_protocol_get_methods() There is no formal definition of what a plugin is and how a plugin mechanism works.7. 3.

a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded.0.query() 1.0. 2.2. ext/mysqlnd_plugin.2. The PHP MySQL extension itself returns to the PHP application. ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. Mysqlnd calls its connect method. By default the plugins call the parent implementation of the query method in their derived version of the method. Whatever PHP MySQL extension had been used by the application. ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user.query() mysqlnd_cache.query() mysqlnd. and can point into another plugin's data. it receives a connection to 127. Both subclass Connection::query(). Issues: an example of chaining and cooperation Extension ext/mysqlnd ext/mysqlnd_cache mysqlnd.0. which exposes the mysqlnd C plugin API to PHP: • • • • • • • • Any PHP MySQL application tries to establish a connection to 192.MySQL Native Driver (Mysqlnd) The mysqlnd plugin concept employs these features. These pointers are not restricted in any way.query() mysqlnd_cache.query() pointer mysqlnd.29.1.168.query() mysqlnd.1) by calling the original mysqlnd method for establishing a connection. ext/mysqlnd_plugin performs the equivalent of parent::connect(127.0.0. plugins can use pointers freely. 2. 3.query call stack if calling parent mysqlnd. 281 . ext/mysqlnd_monitor mysqlnd_monitor. There are no security limits or restrictions. It is recommended you only deploy plugins from a trusted source.2.query() 1. which has been subclassed by ext/mysqlnd_plugin. PHP Extension Recap This is a recap of what happens when using an example plugin. No Restrictions A plugin has full access to the inner workings of mysqlnd. ext/mysqli or PDO_MYSQL.29 The PHP application will either use ext/mysql.0.query In this scenario. It is recommended that you write cooperative plugins. ext/mysqlnd_plugin returns as well. The circle is closed.168. Plugin registration happens at MINIT using the logic shown previously. Simple offset arithmetic can be used to read another plugin's data. and additionally enjoys an open architecture. Plugins are not aware of each other and do not set extension dependencies.168. mysqlnd_monitor. Everything can be overwritten to implement friendly or hostile algorithms.1 and returns the connection established by parent::connect().29 to 127. and that you always call the parent method. As discussed previously. The userspace hook changes the connection host IP from 192. All three PHP MySQL extensions use mysqlnd to establish the connection to 192.query mysqlnd_cache. PHP calls extensions in alphabetical order by default. The plugins should always cooperate with mysqlnd itself.

) { . The following code shows the basic structure of the MINIT function that will be used in the typical mysqlnd plugin: /* my_php_mysqlnd_plugin.. ini entries. classes */ /* register mysqlnd plugin */ mysqlnd_plugin_id = mysqlnd_plugin_register(). Getting started building a mysqlnd plugin Copyright 1997-2012 the PHP Documentation Group. Optimization: calling methods from C using zend_call_method 282 . memcpy(org_conn_m. } } mysqlnd_plugin_set_conn_proxy(new proxy()).h) 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().5.. It is important to remember that a mysqlnd plugin is itself a PHP extension. conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn. */) { /* ... sizeof(struct st_mysqlnd_conn_methods)).MySQL Native Driver (Mysqlnd) 3. conn_m = mysqlnd_get_conn_methods(). b. */) { /* . resources..7.c */ enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn. */ } enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn. 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 . 3..zend_interfaces. if userspace callback not set You need to carry out the following: 1... conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn. 2.. } /* my_mysqlnd_plugin. conn_m. 4.. connect)(/* . connect).c */ static PHP_MINIT_FUNCTION(mysqlnd_plugin) { /* globals. 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. Calls userspace callback Or orginal mysqlnd method. 3.. query)(/* . 2. */ } Task analysis: from C to userspace class proxy extends mysqlnd_plugin_connection { public function connect($host. Process: 1. 5. query). .

zv_host /*. To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters.. db. .*/).MySQL Native Driver (Mysqlnd) The following code snippet shows the prototype for the zend_call_method function. mysql_flags TSRMLS_CC). } return ret. /*. unsigned int mysql_flags TSRMLS_DC ). */ } Calling userspace: structs as arguments /* my_mysqlnd_plugin. MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy. 1). You may need more. /* .. ZVAL_STRING(zv_host. zv_retval.. passwd_len. zval_ptr_dtor(&zv_conn). You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros. host. unsigned int db_len.... */ TSRMLS_DC) { enum_func_status ret = FAIL.*/) { /* . /* ..*/). Calling PHP userspace This code snippet shows the optimized method for calling a userspace function from C: /* my_mysqlnd_plugin. le_mysqlnd_plugin_conn). MAKE_STD_ZVAL(zv_host). zval* arg1.h. const char * passwd. db_len. zval * global_user_conn_proxy = fetch_userspace_proxy(). */ if (global_user_conn_proxy) { /* .. passwd.. */ if (global_user_conn_proxy) { /* . const char * db.connect)( /* . unsigned int port.... taken from zend_interfaces.connect)( MYSQLND *conn. zend_function **fn_proxy. zend_class_entry *obj_ce... unsigned int passwd_len. ZEND_API zval* zend_call_method( zval **object_pp. port.*/).c */ MYSQLND_METHOD(my_conn_class.c */ MYSQLND_METHOD(my_conn_class. zv_host /*. /* . .. int function_name_len. */ zval* zv_conn.. zval* arg2 TSRMLS_DC ). */. ZEND_REGISTER_RESOURCE(zv_conn. } Calling userspace: simple arguments /* my_mysqlnd_plugin. be transparent */ ret = org_methods.. */ zval* zv_host.. } else { /* or original mysqlnd method = do nothing.*/) { /* . host. */ 283 ... char *function_name. zval_ptr_dtor(&zv_host). host.connect(conn. zval **retval_ptr_ptr. const char *host. user. connect)( MYSQLND *conn. if (global_user_conn_proxy) { /* call userspace proxy */ ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy.. (void *)conn. zv_retval.. zv_conn.c */ MYSQLND_METHOD(my_conn_class. Zend API supports only two arguments. for example: enum_func_status (*func_mysqlnd_conn__connect)( MYSQLND *conn.. const char *host. const char *host /* . const char * socket. */ } /* . int param_count.. /* ... MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy. socket.. const char * user..

The mysqlnd connection object pointer can be compared to a standard I/O file handle. As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks. } 284 . The struct MYSQLND represents a mysqlnd connection object. connect) { /* . &host.. $host. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC. */ zval* mysqlnd_rsrc. le_mysqlnd_plugin_conn). } public function query($conn. $query) { /* "post" hook */ $ret = parent::query($conn. printf("Query = '%s'\n".) { /* "pre" hook */ printf("Connecting to host = '%s'\n".. return $ret. MYSQLND* conn.c */ PHP_METHOD("mysqlnd_plugin_connection". else RETVAL_FALSE. /* simplified! */ TSRMLS_CC)) RETVAL_TRUE.. &mysqlnd_rsrc. &mysqlnd_rsrc. } } mysqlnd_plugin_set_conn_proxy(new proxy()).MySQL Native Driver (Mysqlnd) } /* . if (PASS == org_methods. "rs"... int host_len. PHP users must be able to call the parent implementation of an overwritten method. For example.. .connect(conn. char* host. debug_print_backtrace(). Like a standard I/O file handle a mysqlnd connection object shall be linked to the userspace using the PHP resource variable type. $host). $query). &host_len) == FAILURE) { RETURN_NULL().. */ } The first argument of many mysqlnd methods is a C "object". simplified! . the first argument of the connect() method is a pointer to MYSQLND. Buildin class: mysqlnd_plugin_connection::connect() /* my_mysqlnd_plugin_classes. MYSQLND* conn. host. $query). "Mysqlnd Connection". } ZEND_FETCH_RESOURCE(conn. From C to userspace and back class proxy extends mysqlnd_plugin_connection { public function connect($conn. return parent::connect($conn). -1..

Chapter 4. Optionally. the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions.x and 5. and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. When writing transactional database code using a table type that does not support transactions. any DDL queries issued will implicitly commit any pending transactions. } ?> PDO::MYSQL_ATTR_LOCAL_IN Enable LOAD LOCAL INFILE. the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix. Using driverspecific attributes with another driver may result in unexpected behaviour. 4. If unspecified.1. $ . FILE (integer) Note. where the optional [=DIR] is the MySQL base install directory. Example 4.x. PDO will emulate them for you. PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.1 and higher. MySQL will pretend that a transaction was initiated successfully. If you're writing portable code. PDO::getAttribute may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver.0 Description MySQL client libraries 4.1. then the MySQL native driver will be used. array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true)). Use --with-pdo-mysql[=DIR] to install the PDO MySQL extension. the MySQL driver will use the buffered ERED_QUERY (integer) versions of the MySQL API. Warning Beware: Some MySQL table types (storage engines) do not support transactions. these driver-specific constants should only be used if you are using this driver. you should use PDOStatement::fetchAll instead. I should use \$stmt->fetchAll() instead"). Forcing queries to be buffered in mysql <?php if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') { $stmt = $db->prepare('select * from foo'. including PDO_MYSQL. this constant can only be used in the driver_options array when constructing a new 285 ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql. Changelog Version 5. In addition. the default locations are searched. PDO::MYSQL_ATTR_USE_BUFF If this attribute is set to TRUE on a PDOStatement.1 and below are no longer supported. } else { die("my application only works with mysql. if your code can run against multiple drivers. If mysqlnd is passed as [=DIR]. PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4. The constants below are defined by this driver.sock Table 4. MySQL Functions (PDO_MYSQL) (MySQL (PDO)) Copyright 1997-2012 the PHP Documentation Group.x databases. Optionally.4. If you're using an older version of the mysql client libraries. In addition.

this constant can only be used in the driver_options array when constructing a new database handle.default_socket pdo_mysql. This is not supported when compiled against mysqlnd. because mysqlnd does not read the mysql configuration files. see the http://www.2.default_socket Sets a Unix domain socket.php.debug Default "/tmp/mysql. • PDO_MYSQL DSN Connecting to MySQL databases Description The PDO_MYSQL Data Source Name (DSN) is composed of the following elements: 286 . Enable network communication compression. PDO::MYSQL_ATTR_DIRECT_Q UERY (integer) PDO::MYSQL_ATTR_FOUND_RO WS (integer) PDO::MYSQL_ATTR_IGNORE_S PACE (integer) PDO::MYSQL_ATTR_COMPRESS (integer) Perform direct queries.debug boolean Enables debugging for PDO_MYSQL.modes. This constant is not supported when compiled against ER_SIZE (integer) mysqlnd. Makes all functions names reserved words. PDO_MYSQL DSN Copyright 1997-2012 the PHP Documentation Group. This option is not available if AULT_FILE (integer) mysqlnd is used. The behaviour of these functions is affected by settings in php. don't use prepared statements. not the number of changed rows. pdo_mysql. This value can either be set at compile time if a domain socket is string found at configure. Table 4.1. PDO_MYSQL Configuration Options Name pdo_mysql. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.MySQL Functions (PDO_MYSQL) (MySQL (PDO)) database handle. This option is not available if mysqlnd is used. because mysqlnd does not read the mysql configuration files.sock" NULL Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM For further details and definitions of the PHP_INI_* modes.ini. Note. PDO::MYSQL_ATTR_MAX_BUFF Maximum buffer size.cnf. Defaults to 1 MiB. Permit spaces after function names. This ini setting is Unix only. 4. PDO::MYSQL_ATTR_READ_DEF Read options from the named option file instead of from my. Here's a short explanation of the configuration directives.cnf or the file specified with AULT_GROUP (integer) MYSQL_READ_DEFAULT_FILE . PDO::MYSQL_ATTR_INIT_COM Command to execute when connecting to the MySQL server.net/manual/en/configuration. PDO::MYSQL_ATTR_READ_DEF Read options from the named group from my. pdo_mysql.changes. Will automatically be re-executed MAND (integer) when reconnecting. Return the number of found (matched) rows.

Prior to PHP 5. Example 4. ). Example 4. $password = 'password'.3.3.6.MySQL Functions (PDO_MYSQL) (MySQL (PDO)) DSN prefix host port dbname unix_socket charset The DSN prefix is mysql:. $password. The port number where the database server is listening.3.dbname=testdb'.3. $options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'.dbname=testdb 287 .2. ?> Changelog Version 5.dbname=testdb More complete examples: mysql:host=localhost.3.port=3307. $username. $username = 'username'.dbname=testdb mysql:unix_socket=/tmp/mysql. Setting the connection character set to UTF-8 prior to PHP 5. Warning The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII. The name of the database. The character set. $dbh = new PDO($dsn. $options). The MySQL Unix socket (shouldn't be used with host or port). The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option.6 <?php $dsn = 'mysql:host=localhost. PDO_MYSQL DSN examples The following example shows a PDO_MYSQL DSN for connecting to MySQL databases: mysql:host=localhost.sock. this element was silently ignored. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5. such as ISO-8859-1 and UTF-8. charset was ignored.6 and later versions.3. as the following example shows. The hostname on which the database server resides.6 Examples Description Prior to version 5.6.

MySQL Functions (PDO_MYSQL) (MySQL (PDO)) Notes Unix only: When the host name is set to "localhost". If PDO_MYSQL is compiled against libmysql then the location of the socket file is at libmysql's compiled in location.default_socket setting. 288 . then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.

you should use the mysql or mysqli extensions shipped with the PHP sources. See Preface. Windows specific driver is no longer required. 289 . Later versions of the main PHP mysql/mysqli drivers are compatible with Windows and a separate.Chapter 5. For PHP for all platforms. Connector/PHP The MySQL Connector/PHP is a version of the mysql and mysqli extensions for PHP optimized for the Windows operating system. including Windows.

) • • • 290 . for more information. Possible solutions are: downgrade to MySQL 4. switch to PHP 5 and the newer mysqli extension. Error: Client does not support authentication protocol: This is most often encountered when trying to use the older mysql extension with MySQL 4. Fatal error: Call to unsupported or undefined function mysql_connect() in .Chapter 6. as needed. Error: Undefined reference to 'uncompress': This means that the client library is compiled with support for a compressed client/server protocol. go into the php.. or configure the MySQL server with --old-passwords. (See Client does not support authentication protocol.0. You can either compile a dynamic MySQL module and load it into PHP or recompile PHP with built-in MySQL support..: This means that your PHP version isn't compiled with MySQL support. This process is described in detail in the PHP manual.1.1 and later.ini file and set the maximum execution time up from 30 seconds to something higher. The fix is to add -lz last when linking with -lmysqlclient. Common Problems with MySQL and PHP • Error: Maximum Execution Time Exceeded: This is a PHP limit. It is also not a bad idea to double the RAM allowed per script to 16MB instead of 8MB.

you should try the following procedure. Edit the Makefile and search for a line that starts with EXTRA_LIBS. 1./configure --with-mysqli=/usr/bin/mysql_config --with-mysql=/usr 2. so that the line looks like this (all on one line): EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lresolv -lm -ldl -lnsl -lxml2 3. Enabling Both mysql and mysqli in PHP If you're experiencing problems with enabling both the mysql and the mysqli extension when building PHP on Linux yourself. Build and install PHP: make make install 291 . Configure PHP like this: .Chapter 7. 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.

Sign up to vote on this title
UsefulNot useful