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: 2013-01-11 (revision: 33939)

Table of Contents
Preface and Legal Notices ................................................................................................................. ix 1. Introduction .................................................................................................................................... 1 2. MySQL Extension (mysql) ............................................................................................................... 3 2.1. Installing/Configuring ............................................................................................................ 4 2.1.1. Requirements ........................................................................................................... 4 2.1.2. Installation ................................................................................................................ 4 2.1.3. Runtime Configuration ............................................................................................... 6 2.1.4. Resource Types ........................................................................................................ 7 2.2. Predefined Constants ........................................................................................................... 7 2.3. Examples ............................................................................................................................ 8 2.3.1. MySQL extension overview example .......................................................................... 8 2.4. MySQL Functions ................................................................................................................ 9 2.4.1. mysql_affected_rows .......................................................................................... 9 2.4.2. mysql_client_encoding .................................................................................... 11 2.4.3. mysql_close ........................................................................................................ 12 2.4.4. mysql_connect .................................................................................................... 13 2.4.5. mysql_create_db ................................................................................................ 16 2.4.6. mysql_data_seek ................................................................................................ 17 2.4.7. mysql_db_name .................................................................................................... 19 2.4.8. mysql_db_query .................................................................................................. 20 2.4.9. mysql_drop_db .................................................................................................... 22 2.4.10. mysql_errno ...................................................................................................... 23 2.4.11. mysql_error ...................................................................................................... 25 2.4.12. mysql_escape_string ....................................................................................... 26 2.4.13. mysql_fetch_array ........................................................................................... 27 2.4.14. mysql_fetch_assoc ........................................................................................... 29 2.4.15. mysql_fetch_field ........................................................................................... 31 2.4.16. mysql_fetch_lengths ....................................................................................... 33 2.4.17. mysql_fetch_object ......................................................................................... 34 2.4.18. mysql_fetch_row .............................................................................................. 36 2.4.19. mysql_field_flags ........................................................................................... 37 2.4.20. mysql_field_len .............................................................................................. 39 2.4.21. mysql_field_name ............................................................................................. 40 2.4.22. mysql_field_seek ............................................................................................. 41 2.4.23. mysql_field_table ........................................................................................... 42 2.4.24. mysql_field_type ............................................................................................. 43 2.4.25. mysql_free_result ........................................................................................... 45 2.4.26. mysql_get_client_info ................................................................................... 46 2.4.27. mysql_get_host_info ....................................................................................... 47 2.4.28. mysql_get_proto_info ..................................................................................... 48 2.4.29. mysql_get_server_info ................................................................................... 49 2.4.30. mysql_info ........................................................................................................ 50 2.4.31. mysql_insert_id .............................................................................................. 51 2.4.32. mysql_list_dbs ................................................................................................ 53 2.4.33. mysql_list_fields ........................................................................................... 54 2.4.34. mysql_list_processes ..................................................................................... 56 2.4.35. mysql_list_tables ........................................................................................... 57 2.4.36. mysql_num_fields ............................................................................................. 58 2.4.37. mysql_num_rows ................................................................................................ 59 2.4.38. mysql_pconnect ................................................................................................ 61 2.4.39. mysql_ping ........................................................................................................ 62

iii

MySQL and PHP

2.4.40. mysql_query ...................................................................................................... 64 2.4.41. mysql_real_escape_string ............................................................................. 66 2.4.42. mysql_result .................................................................................................... 68 2.4.43. mysql_select_db .............................................................................................. 69 2.4.44. mysql_set_charset ........................................................................................... 70 2.4.45. mysql_stat ........................................................................................................ 71 2.4.46. mysql_tablename .............................................................................................. 73 2.4.47. mysql_thread_id .............................................................................................. 74 2.4.48. mysql_unbuffered_query ................................................................................. 75 2.5. Changelog ......................................................................................................................... 77 3. MySQL Improved Extension (Mysqli) .......................................................................................... 79 3.1. Examples .......................................................................................................................... 82 3.2. Overview ........................................................................................................................... 82 3.3. Quick start guide ............................................................................................................... 86 3.3.1. Dual procedural and object-oriented interface ........................................................... 86 3.3.2. Connections ............................................................................................................ 88 3.3.3. Executing statements .............................................................................................. 90 3.3.4. Prepared Statements ............................................................................................... 93 3.3.5. Stored Procedures .................................................................................................. 99 3.3.6. Multiple Statements ............................................................................................... 103 3.3.7. API support for transactions ................................................................................... 105 3.3.8. Metadata ............................................................................................................... 106 3.4. Installing/Configuring ........................................................................................................ 108 3.4.1. Requirements ........................................................................................................ 108 3.4.2. Installation ............................................................................................................. 108 3.4.3. Runtime Configuration ........................................................................................... 110 3.4.4. Resource Types .................................................................................................... 111 3.5. The mysqli Extension and Persistent Connections ............................................................. 111 3.6. Predefined Constants ....................................................................................................... 112 3.7. Notes .............................................................................................................................. 115 3.8. The MySQLi Extension Function Summary ....................................................................... 116 3.9. The mysqli class (mysqli) ............................................................................................... 122 3.9.1. mysqli::$affected_rows, mysqli_affected_rows ....................................... 125 3.9.2. mysqli::autocommit, mysqli_autocommit ..................................................... 127 3.9.3. mysqli::change_user, mysqli_change_user ................................................. 129 3.9.4. mysqli::character_set_name, mysqli_character_set_name ..................... 131 3.9.5. mysqli::$client_info, mysqli_get_client_info ....................................... 133 3.9.6. mysqli::$client_version, mysqli_get_client_version ........................... 134 3.9.7. mysqli::close, mysqli_close ........................................................................ 134 3.9.8. mysqli::commit, mysqli_commit ..................................................................... 135 3.9.9. mysqli::$connect_errno, mysqli_connect_errno ....................................... 137 3.9.10. mysqli::$connect_error, mysqli_connect_error ..................................... 138 3.9.11. mysqli::__construct, mysqli_connect ....................................................... 139 3.9.12. mysqli::debug, mysqli_debug ....................................................................... 142 3.9.13. mysqli::dump_debug_info, mysqli_dump_debug_info ............................... 143 3.9.14. mysqli::$errno, mysqli_errno ..................................................................... 144 3.9.15. mysqli::$error_list, mysqli_error_list ................................................. 145 3.9.16. mysqli::$error, mysqli_error ..................................................................... 147 3.9.17. mysqli::$field_count, mysqli_field_count ............................................. 148 3.9.18. mysqli::get_charset, mysqli_get_charset ............................................... 150 3.9.19. mysqli::get_client_info, mysqli_get_client_info ............................... 151 3.9.20. mysqli_get_client_stats ............................................................................. 152 3.9.21. mysqli_get_client_version, mysqli::$client_version ......................... 155 3.9.22. mysqli::get_connection_stats, mysqli_get_connection_stats ........... 155

iv

MySQL and PHP

3.9.23. mysqli::$host_info, mysqli_get_host_info ............................................. 158 3.9.24. mysqli::$protocol_version, mysqli_get_proto_info ............................. 159 3.9.25. mysqli::$server_info, mysqli_get_server_info ..................................... 161 3.9.26. mysqli::$server_version, mysqli_get_server_version ......................... 162 3.9.27. mysqli::get_warnings, mysqli_get_warnings ........................................... 163 3.9.28. mysqli::$info, mysqli_info ......................................................................... 164 3.9.29. mysqli::init, mysqli_init ........................................................................... 166 3.9.30. mysqli::$insert_id, mysqli_insert_id ..................................................... 166 3.9.31. mysqli::kill, mysqli_kill ........................................................................... 168 3.9.32. mysqli::more_results, mysqli_more_results ........................................... 169 3.9.33. mysqli::multi_query, mysqli_multi_query ............................................... 170 3.9.34. mysqli::next_result, mysqli_next_result ............................................... 172 3.9.35. mysqli::options, mysqli_options ............................................................... 173 3.9.36. mysqli::ping, mysqli_ping ........................................................................... 175 3.9.37. mysqli::poll, mysqli_poll ........................................................................... 176 3.9.38. mysqli::prepare, mysqli_prepare ............................................................... 178 3.9.39. mysqli::query, mysqli_query ....................................................................... 180 3.9.40. mysqli::real_connect, mysqli_real_connect ........................................... 183 3.9.41. mysqli::real_escape_string, mysqli_real_escape_string ................... 186 3.9.42. mysqli::real_query, mysqli_real_query ................................................... 188 3.9.43. mysqli::reap_async_query, mysqli_reap_async_query ........................... 189 3.9.44. mysqli::refresh, mysqli_refresh ............................................................... 190 3.9.45. mysqli::rollback, mysqli_rollback ........................................................... 190 3.9.46. mysqli::rpl_query_type, mysqli_rpl_query_type ................................... 192 3.9.47. mysqli::select_db, mysqli_select_db ....................................................... 193 3.9.48. mysqli::send_query, mysqli_send_query ................................................... 195 3.9.49. mysqli::set_charset, mysqli_set_charset ............................................... 195 3.9.50. mysqli::set_local_infile_default, mysqli_set_local_infile_default ........................................................................ 197 3.9.51. mysqli::set_local_infile_handler, mysqli_set_local_infile_handler ........................................................................ 198 3.9.52. mysqli::$sqlstate, mysqli_sqlstate ......................................................... 200 3.9.53. mysqli::ssl_set, mysqli_ssl_set ............................................................... 201 3.9.54. mysqli::stat, mysqli_stat ........................................................................... 202 3.9.55. mysqli::stmt_init, mysqli_stmt_init ....................................................... 204 3.9.56. mysqli::store_result, mysqli_store_result ........................................... 204 3.9.57. mysqli::$thread_id, mysqli_thread_id ..................................................... 205 3.9.58. mysqli::thread_safe, mysqli_thread_safe ............................................... 207 3.9.59. mysqli::use_result, mysqli_use_result ................................................... 207 3.9.60. mysqli::$warning_count, mysqli_warning_count ..................................... 209 3.10. The mysqli_stmt class (mysqli_stmt) ........................................................................... 211 3.10.1. mysqli_stmt::$affected_rows, mysqli_stmt_affected_rows ................. 212 3.10.2. mysqli_stmt::attr_get, mysqli_stmt_attr_get ....................................... 214 3.10.3. mysqli_stmt::attr_set, mysqli_stmt_attr_set ....................................... 215 3.10.4. mysqli_stmt::bind_param, mysqli_stmt_bind_param ............................... 216 3.10.5. mysqli_stmt::bind_result, mysqli_stmt_bind_result ........................... 219 3.10.6. mysqli_stmt::close, mysqli_stmt_close ................................................... 221 3.10.7. mysqli_stmt::data_seek, mysqli_stmt_data_seek ................................... 221 3.10.8. mysqli_stmt::$errno, mysqli_stmt_errno ................................................. 223 3.10.9. mysqli_stmt::$error_list, mysqli_stmt_error_list ............................. 225 3.10.10. mysqli_stmt::$error, mysqli_stmt_error ............................................... 227 3.10.11. mysqli_stmt::execute, mysqli_stmt_execute ......................................... 228 3.10.12. mysqli_stmt::fetch, mysqli_stmt_fetch ................................................. 231 3.10.13. mysqli_stmt::$field_count, mysqli_stmt_field_count ....................... 233

v

MySQL and PHP

3.10.14. mysqli_stmt::free_result, mysqli_stmt_free_result ......................... 233 3.10.15. mysqli_stmt::get_result, mysqli_stmt_get_result ............................. 234 3.10.16. mysqli_stmt::get_warnings, mysqli_stmt_get_warnings ..................... 236 3.10.17. mysqli_stmt::$insert_id, mysqli_stmt_insert_id ............................... 236 3.10.18. mysqli_stmt::more_results, mysqli_stmt_more_results ..................... 237 3.10.19. mysqli_stmt::next_result, mysqli_stmt_next_result ......................... 237 3.10.20. mysqli_stmt::$num_rows, mysqli_stmt_num_rows ................................... 238 3.10.21. mysqli_stmt::$param_count, mysqli_stmt_param_count ....................... 240 3.10.22. mysqli_stmt::prepare, mysqli_stmt_prepare ......................................... 241 3.10.23. mysqli_stmt::reset, mysqli_stmt_reset ................................................. 244 3.10.24. mysqli_stmt::result_metadata, mysqli_stmt_result_metadata ......... 244 3.10.25. mysqli_stmt::send_long_data, mysqli_stmt_send_long_data ............. 246 3.10.26. mysqli_stmt::$sqlstate, mysqli_stmt_sqlstate ................................... 247 3.10.27. mysqli_stmt::store_result, mysqli_stmt_store_result ..................... 249 3.11. The mysqli_result class (mysqli_result) ..................................................................... 251 3.11.1. mysqli_result::$current_field, mysqli_field_tell ............................. 252 3.11.2. mysqli_result::data_seek, mysqli_data_seek ......................................... 254 3.11.3. mysqli_result::fetch_all, mysqli_fetch_all ......................................... 256 3.11.4. mysqli_result::fetch_array, mysqli_fetch_array ................................. 257 3.11.5. mysqli_result::fetch_assoc, mysqli_fetch_assoc ................................. 259 3.11.6. mysqli_result::fetch_field_direct, mysqli_fetch_field_direct ..... 262 3.11.7. mysqli_result::fetch_field, mysqli_fetch_field ................................. 264 3.11.8. mysqli_result::fetch_fields, mysqli_fetch_fields ............................. 266 3.11.9. mysqli_result::fetch_object, mysqli_fetch_object ............................. 268 3.11.10. mysqli_result::fetch_row, mysqli_fetch_row ....................................... 270 3.11.11. mysqli_result::$field_count, mysqli_num_fields ............................... 272 3.11.12. mysqli_result::field_seek, mysqli_field_seek ................................... 273 3.11.13. mysqli_result::free, mysqli_free_result ............................................. 275 3.11.14. mysqli_result::$lengths, mysqli_fetch_lengths ................................. 276 3.11.15. mysqli_result::$num_rows, mysqli_num_rows ......................................... 278 3.12. The mysqli_driver class (mysqli_driver) ..................................................................... 279 3.12.1. mysqli_driver::embedded_server_end, mysqli_embedded_server_end .................................................................................. 280 3.12.2. mysqli_driver::embedded_server_start, mysqli_embedded_server_start .............................................................................. 281 3.13. The mysqli_warning class (mysqli_warning) ................................................................ 281 3.13.1. mysqli_warning::__construct ..................................................................... 282 3.13.2. mysqli_warning::next ................................................................................... 282 3.14. The mysqli_sql_exception class (mysqli_sql_exception) ........................................... 283 3.15. Aliases and deprecated Mysqli Functions ........................................................................ 283 3.15.1. mysqli_bind_param ......................................................................................... 283 3.15.2. mysqli_bind_result ....................................................................................... 284 3.15.3. mysqli_client_encoding ............................................................................... 284 3.15.4. mysqli_connect ............................................................................................... 284 3.15.5. mysqli::disable_reads_from_master, mysqli_disable_reads_from_master ...................................................................... 284 3.15.6. mysqli_disable_rpl_parse ........................................................................... 285 3.15.7. mysqli_enable_reads_from_master ............................................................. 285 3.15.8. mysqli_enable_rpl_parse ............................................................................. 286 3.15.9. mysqli_escape_string ................................................................................... 286 3.15.10. mysqli_execute ............................................................................................. 286 3.15.11. mysqli_fetch ................................................................................................. 287 3.15.12. mysqli_get_cache_stats ............................................................................. 287 3.15.13. mysqli_get_metadata ................................................................................... 290

vi

MySQL and PHP

4.

5. 6. 7. 8.

3.15.14. mysqli_master_query ................................................................................... 3.15.15. mysqli_param_count ..................................................................................... 3.15.16. mysqli_report ............................................................................................... 3.15.17. mysqli_rpl_parse_enabled ......................................................................... 3.15.18. mysqli_rpl_probe ......................................................................................... 3.15.19. mysqli_send_long_data ............................................................................... 3.15.20. mysqli_set_opt ............................................................................................. 3.15.21. mysqli_slave_query ..................................................................................... 3.16. Changelog ..................................................................................................................... MySQL Native Driver (Mysqlnd) ................................................................................................. 4.1. Overview ......................................................................................................................... 4.2. Installation ....................................................................................................................... 4.3. Runtime Configuration ...................................................................................................... 4.4. Persistent Connections ..................................................................................................... 4.5. Statistics .......................................................................................................................... 4.6. Notes .............................................................................................................................. 4.7. MySQL Native Driver Plugin API ...................................................................................... 4.7.1. A comparison of mysqlnd plugins with MySQL Proxy .............................................. 4.7.2. Obtaining the mysqlnd plugin API .......................................................................... 4.7.3. MySQL Native Driver Plugin Architecture ................................................................ 4.7.4. The mysqlnd plugin API ........................................................................................ 4.7.5. Getting started building a mysqlnd plugin ............................................................... MySQL Functions (PDO_MYSQL) (MySQL (PDO)) ...................................................................... 5.1. PDO_MYSQL DSN ............................................................................................................ Connector/PHP ........................................................................................................................... Common Problems with MySQL and PHP ................................................................................... Enabling Both mysql and mysqli in PHP ..................................................................................

290 290 291 292 292 293 293 293 293 295 295 296 297 301 302 316 316 317 318 319 323 325 329 331 335 337 339

vii

viii .

backup.227-19. Oracle and/or its affiliates. MySQL is a trademark of Oracle Corporation and/or its affiliates. The information contained herein is subject to change without notice and is not warranted to be error-free.. perform. This software is developed for general use in a variety of information management applications. or decompilation of this software. modify. Except as expressly permitted in your license agreement or allowed by law. and related documentation and technical data delivered to U. GOVERNMENT RIGHTS Programs. products. Government. All rights reserved. please report them to us in writing. exhibit. and shall not be used without Oracle's express written authorization. redundancy. software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. disassembly. 500 Oracle Parkway. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. or by any means. and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract. unless required by law for interoperability. to the extent applicable by the terms of the Government contract. duplication. publish. copy. Oracle Corporation and its affiliates will not be responsible for any loss. in any form. Oracle USA.S. transmit.S.S. Commercial Computer Software License (December 2007). If this software or related documentation is delivered to the U. products. or display any part. the use. If you use this software in dangerous applications. As such. or distributed to anyone outside Oracle without prior written consent of Oracle or as specifically provided below. license. and services. ix . 2013. This software and documentation may provide access to or information on content. or damages incurred due to your access to or use of third-party content. and services from third parties. reproduce. and. and other measures to ensure the safe use of this software. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. the following notice is applicable: U. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. contains proprietary information that is the exclusive property of Oracle. databases. distribute. Redwood City. broadcast. is prohibited. This document in any form. Reverse engineering. Other names may be trademarks of their respective owners. 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. Legal Notices Copyright © 1997. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content. copied. disclosure. products. software or printed matter. It is not developed or intended for use in any inherently dangerous applications. or services. Your access to and use of this material is subject to the terms and conditions of your Oracle Software License and Service Agreement. costs.S. the additional rights set forth in FAR 52. This document and information contained herein may not be disclosed. modification. CA 94065. which has been executed and with which you agree to comply. including applications which may create a risk of personal injury. then you shall be responsible to take all appropriate fail-safe. Inc. Government or anyone licensing it on behalf of the U. reproduced. you may not use. If you find any errors. translate.Preface and Legal Notices This manual describes the PHP extensions and interfaces that can be used with MySQL.

including translations of the documentation into other languages. provided however that the documentation is disseminated together with the software on the same medium. including HTML and PDF formats. and downloadable versions in variety of formats. electronically for download on a Web site with the software) or on a CD-ROM or similar medium. Any other use. see the MySQL Documentation Library. Conversion to other formats is allowed as long as the actual content is not altered or edited in any way. requires the prior written consent from an authorized representative of Oracle. x . For help with using MySQL. 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. For additional licensing information.Legal Notices This documentation is NOT distributed under a GPL license. see Preface and Legal Notices. please visit MySQL Contact & Questions. in another publication. in whole or in part. such as any dissemination of printed copies or use of this documentation. For more information on the terms of this license. or for details on how the MySQL documentation is built and produced. except if you distribute the documentation in a manner similar to how Oracle disseminates it (that is. For additional documentation on MySQL products. please visit either the MySQL Forums or MySQL Mailing Lists where you can discuss your issues with other MySQL users. including licenses for third-party libraries used by MySQL products. You shall not publish or distribute this documentation in any form or on any media. Oracle and/or its affiliates reserve any and all rights to this documentation not expressly granted above.

This extension is available as of PHP 5. It is intended for use with MySQL 4. The PHP distribution and documentation are available from the PHP Web site. • Chapter 5.0.1. but instead it's a MySQL driver for the PHP database abstraction layer PDO (PHP Data Objects).1. This extension is deprecated as of PHP 5. as well as the Prepared Statements and Multiple Statements APIs. this extension is available as of PHP 5. and its use is highly discouraged. this extension provides an advanced.0/.1.1. MySQL Functions (PDO_MYSQL) (MySQL (PDO)): Not its own API. It is available for most operating systems and Web servers. A copy of the Creative Commons Attribution 3. This extension fully supports the authentication protocol used in MySQL 5.org/licenses/by/3.0. 1 . PHP provides three different MySQL API extensions: • Chapter 3.0 License or later. For further information. Introduction PHP is a server-side. you will likely configure the MySQL server to set the old_passwords system variable to 1 (see Client does not support authentication protocol). see Choosing an API. HTML-embedded scripting language that may be used to create dynamic Web pages. MySQL Extension (mysql): Available for PHP versions 4 and 5. including MySQL. this extension is intended for use with MySQL versions prior to MySQL 4.0 license is distributed with this manual. object-oriented programming interface.1 and later. To use this extension with MySQL 4.0. and provides MySQL-specific functionality. and can access most common databases.0. nor does it support prepared statements or multiple statements.0. • Chapter 2.Chapter 1. Improved”. In addition. All users are encouraged to migrate to either mysqli or PDO_MySQL. The latest version is presently available at http://creativecommons.1.5. This extension does not support the improved authentication protocol used in MySQL 4. Portions of this section are Copyright (c) 1997-2012 the PHP Documentation Group This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution 3. MySQL Improved Extension (Mysqli): Stands for “MySQL. PHP may be run as a separate program or compiled as a module for use with a Web server. The PDO MySQL driver sits in the layer below PDO itself.

2 .

................................1.... 61 3 ........4................ mysql_affected_rows ....................19.................................. mysql_data_seek ............................................ 39 2............................26..................................... 45 2............................................ 23 2.........4......................................................................................1............... mysql_field_table ........................................4............................................ 26 2................... mysql_get_proto_info ................................... mysql_list_tables .......................20..................... mysql_get_client_info ......4............ mysql_fetch_array ................. 7 2............................................................................................................ 22 2................................................................... mysql_errno .....10...29.....................4..................................................................................................................................... 31 2.............................................35..................................... mysql_fetch_assoc ............21....Chapter 2.....7.......................... 29 2.............30........................... mysql_drop_db .................. Predefined Constants .......... 19 2.................................................. Examples .33......4.................................................................................. mysql_info .................................................................. Requirements .24...... 16 2.............................................................. mysql_list_fields .............4........................................................17.......18...................................4..... 37 2.................................................................................... mysql_create_db ................... 51 2...... mysql_get_host_info ......4...................................... mysql_field_seek ............4...4....4....................2.............4........................5..................................................... mysql_db_query ........................................ 53 2. 54 2...........................................................4.............................. 4 2........................... mysql_field_len ...............................................................4................................. 8 2....................................... 8 2............... 9 2.................. 34 2.......................... 46 2..................38................28............................................ MySQL Extension (mysql) Table of Contents 2............ 12 2... 27 2.........1......4.........................4........................34..............................................................................1.................................................... mysql_get_server_info ..................... 25 2................................4............. mysql_field_name ...................................................................... Installation ..........27.........4..................................4................. 58 2.........4.......................6..... mysql_fetch_lengths ............................................................................................... Runtime Configuration ..4........ 50 2................... Installing/Configuring ....... mysql_client_encoding .............4......................... 41 2...........................................................................3.................3...................................... 6 2...................................................... mysql_db_name ...... 59 2.. mysql_num_fields ..................................4................................ mysql_pconnect .4.... mysql_escape_string ................................................................ mysql_error ........................11....... 7 2........................1........................................................... 47 2....4.......1.........4.................................1......................... 56 2........................................25....................................................................... Resource Types ...................... MySQL Functions .......4............................... 33 2......... 57 2.....32............................................9................................4.............. 49 2.......... MySQL extension overview example .... mysql_insert_id ............................22................................13...... mysql_close ......................................2.....14................... 42 2.......................................4.........16..................................23................................................................................................1................3...........................................4... mysql_field_flags ................37....... mysql_list_dbs ....................... 36 2..................................4..................12....4.................................. 13 2.......... mysql_fetch_field ......................... 11 2............................................................................ mysql_fetch_row ...............................4....................................... 48 2....................................... 9 2....................4.....................15..8................... 43 2...4..........4.....4............................. mysql_num_rows ........ mysql_free_result ................4.............. 4 2............................ mysql_field_type .........4...... 20 2................ mysql_connect ........................... mysql_fetch_object ................................31...................................................... 17 2....3.........................................36..........4..... 40 2................................................... 4 2........................................... mysql_list_processes .............................................................................2......................................................

.................. [1] In order to have these functions available.................1........44.................................0.................4... Installing/Configuring Copyright 1997-2012 the PHP Documentation Group.............. 2.. 4 ....... mysql_query .............4.....4.......com/doc/. [1] For compiling............... More information about MySQL can be found at http://www................................com/...... either the mysqli or PDO_MySQL extension should be used..... mysql_stat .45.......................5..40..............................................1. 2................... mysql_unbuffered_query ........ mysql_tablename . mysql_result .... [1] Note: [DIR] is the path to the MySQL client library files (headers and libraries)..................... mysql_real_escape_string ......... 2.......................................... [1] This extension is deprecated as of PHP 5............... 2..4................2............................0 and greater............................ 2............................... mysql_ping ....................... Changelog ................................................... and is not recommended for writing new code as it will be removed in the future................. 2..........4................ mysql_select_db ..1.. 2...... Copyright 1997-2012 the PHP Documentation Group.......4.. Requirements Copyright 1997-2012 the PHP Documentation Group.........................mysql..............43.................. Installation Copyright 1997-2012 the PHP Documentation Group......1.....4........39.............46............ Documentation for MySQL can be found at http://dev........ Although this MySQL extension is compatible with MySQL 4..Installing/Configuring 2..........4...... These functions allow you to access MySQL database servers................ use the MySQLi extension........2.. 2................................. 2........ 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.................................. simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installation directory.. [1] 2.............................1......................................................... Installation on Linux Systems Copyright 1997-2012 the PHP Documentation Group......................... 62 64 66 68 69 70 71 73 74 75 77 2.......... See also the MySQL API Overview for further help while choosing a MySQL API...... 2.....1..........47...42............. 2.... which can be downloaded from MySQL............................ Instead..... For that.......41........ mysql_set_charset . 2...... you must compile PHP with MySQL support.....................mysql............... it doesn't support the extra functionality that these versions provide........1......................4....................4..................5......48................................ mysql_thread_id ..

2.3.dll). 5./php_mysql.1. ext/mysql compile time support matrix PHP Version Default Configure Configure Options: mysqlnd Options: libmysql Not Available Changelog 4. 5. PHP needs access to the MySQL client library.0.x.x.3.dll and/or libmysql.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.2.2.2.x 5.1. PHP 4 Copyright 1997-2012 the PHP Documentation Group.2.x libmysql mysqlnd --withmysql=mysqlnd --with-mysql --withmysql=[DIR] --withmysql=[DIR] 2.1.x.x libmysql --without-mysql MySQL enabled to disable by default.x libmysql Not Available 5.2.x Copyright 1997-2012 the PHP Documentation Group.1. Installation on Windows Systems Copyright 1997-2012 the PHP Documentation Group.dll'".2. Although copying libmysql.1.1.0+ Copyright 1997-2012 the PHP Documentation Group.1.x.2. and the MySQL client libraries are no longer bundled mysqlnd is now available mysqlnd is now the default 5.0. this is because php_mysql. See also the Manual Windows Installation Instructions. MySQL client libraries are bundled --withmysql=[DIR] MySQL is no longer enabled by default.x. 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 '. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. 2. the PHP directive extension_dir should be set to the directory where the PHP extensions are located.2.dll to the Windows system directory also works (because the system directory is by default in the system's PATH). A file named libmysql. PHP 5. As with enabling any PHP extension (such as php_mysql. it's not recommended.Installation Table 2.2. [1] 5 .2. Also. 5. so the php_mysql.dll DLL must be enabled inside of php. [1] MySQL is no longer enabled by default.dll cannot be found by the system. [1] The PHP MySQL extension is compiled into PHP. [1] 2. 2. PHP 5.3. 5.ini.4.1.

3.net/manual/en/ configuration. you have to install external (not bundled) libmysql with compiled charset support. local files with LOAD DATA statements Whether to allow persistent connections to MySQL.3.default_port mysql. MySQL Configuration Options Name mysql. 6 .0. Note If you need charsets other than latin (default). Table 2.0.1. Include php_mysql.default_host mysql.1.changes. 2.max_persistent mysql.2.allow_local_infile integer mysql. See the recode extension for more information. 2. Runtime Configuration Copyright 1997-2012 the PHP Documentation Group.2.dll.default_password mysql.max_links mysql.1.3.Runtime Configuration The MySQL Native Driver is enabled by default. Here's a short explanation of the configuration directives. Available since PHP 4.trace_mode mysql. mysql.connect_timeout Default "1" "1" "-1" "-1" "0" NULL NULL NULL NULL NULL "60" Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_SYSTEM in PHP <= 4.ini. MySQL Installation Notes Copyright 1997-2012 the PHP Documentation Group. from PHP's perspective. Available since PHP 4.0.3. Changelog For further details and definitions of the PHP_INI_* modes. but libmysql.3. Available since PHP 4.allow_persistent boolean Allow accessing.modes.allow_persistent mysql. see the http://www. [1] The behaviour of these functions is affected by settings in php.default_socket mysql.php.default_user mysql. [1] Warning Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension.dll is no longer required or used.2.allow_local_infile mysql.

mysql. Predefined Constants Copyright 1997-2012 the PHP Documentation Group. the port will be obtained from the MYSQL_TCP_PORT environment variable. Win32 will only use the MYSQL_PORT constant.0) The default TCP port number to use when connecting to the database server if no other port is specified.trace_mode boolean The maximum number of persistent MySQL connections per process. The default user name to use when connecting to the database server if no other name is specified.trace_mode is enabled. The following constants are defined: Table 2. (Introduced in PHP 4. Doesn't apply in SQL safe mode. Doesn't apply in SQL safe mode. [1] There are two resource types used in the MySQL module. [1] The constants below are defined by this extension. If no default is specified. and SQL-Errors will be displayed.connect_timeout integer 2. non free result sets.Resource Types mysql.3. in that order. The default socket name to use when connecting to a local database server if no other socket name is specified.default_host string mysql. the mysql-tcp entry in /etc/services or the compiletime MYSQL_PORT constant. Trace mode. Resource Types Copyright 1997-2012 the PHP Documentation Group. Since PHP 4. The maximum number of MySQL connections per process. warnings for table/ index scans. the second a resource which holds the result of a query. including persistent connections.max_links integer mysql.4.2. 2.0 it is possible to specify additional client flags for the mysql_connect and mysql_pconnect functions. When mysql. and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime. Connect timeout in seconds.default_port string mysql.default_socket string mysql. The default password to use when connecting to the database server if no other password is specified.1.max_persistent integer mysql. On Linux this timeout is also used for waiting for the first answer from the server. The first one is the link identifier for a database connection.default_user string mysql.3.default_password string mysql. Doesn't apply in SQL safe mode. MySQL client constants Constant MYSQL_CLIENT_COMPRESS MYSQL_CLIENT_IGNORE_SPACE Description Use compression protocol Allow space after function names 7 .3. The default server host to use when connecting to the database server if no other host is specified.

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

If no connection is found or established. MySQL Functions Copyright 1997-2012 the PHP Documentation Group.0.ini. the last link opened by mysql_connect is assumed. mysql_affected_rows Copyright 1997-2012 the PHP Documentation Group. If it doesn't exist. [1] Note Most MySQL functions accept link_identifier as the last optional parameter. If it is not successful. [1] • mysql_affected_rows Get number of affected rows in previous MySQL operation Warning This extension is deprecated as of PHP 5. the MySQLi or PDO_MySQL extension should be used. Return Values 9 . Get the number of affected rows by the last INSERT. Instead. If it is not provided. REPLACE or DELETE query associated with link_identifier.4. connection is tried to establish with default parameters defined in php. 2. // Closing connection mysql_close($link). an E_WARNING level error is generated. and will be removed in the future. If the link identifier is not specified. Parameters link_identifier The MySQL connection. See also MySQL: choosing an API guide and related FAQ for more information. functions return FALSE . it will try to create one as if mysql_connect was called with no arguments. UPDATE. Alternatives to this function include: mysqli_affected_rows PDOStatement::rowCount Description int mysql_affected_rows( resource link_identifier = =NULL). If no such link is found. ?> 2.1.5. // Free resultset mysql_free_result($result).MySQL Functions } echo "</table>\n".4. last opened connection is used.

only the number of rows that were literally affected by the query. 'mysql_password'). and -1 if the last query failed. if (!$link) { die('Could not connect: ' . This function returns the number of deleted records plus the number of inserted records. When using UPDATE. mysql_affected_rows()).3.mysql_affected_rows Returns the number of affected rows on success. mysql_affected_rows example <?php $link = mysql_connect('localhost'. printf("Records deleted: %d\n". This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched. ?> The above example will output something similar to: Records deleted: 10 Records deleted: 0 Example 2. mysql_affected_rows example using transactions <?php $link = mysql_connect('localhost'. ?> The above example will output something similar to: 10 . mysql_affected_rows()). 'mysql_password'). mysql_affected_rows()). } mysql_select_db('mydb'). printf("Records deleted: %d\n". 'mysql_user'.2. mysql_error()). } mysql_select_db('mydb').1. The REPLACE statement first deletes the record with the same primary key and then inserts the new record. Examples Example 2. mysql_query("COMMIT"). If the last query was a DELETE query with no WHERE clause. /* with a where clause that is never true. ON DUPLICATE KEY UPDATE" queries. the return value will be 1 if an insert was performed. In the case of "INSERT . or 2 for an update of an existing row. 'mysql_user'... mysql_error()). /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'). all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.2. it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'). /* Update records */ mysql_query("UPDATE mytable SET used=1 WHERE id < 10"). if (!$link) { die('Could not connect: ' . MySQL will not update columns where the new value is the same as the old value. printf ("Updated records: %d\n".

If no such link is found.4. Parameters link_identifier The MySQL connection. an E_WARNING level error is generated. If the link identifier is not specified.5. or DELETE query. Alternatives to this function include: mysqli_character_set_name Description string mysql_client_encoding( resource link_identifier = =NULL). mysql_client_encoding Copyright 1997-2012 the PHP Documentation Group. you need to call mysql_affected_rows after your INSERT. 11 . Instead.mysql_client_encoding Updated Records: 10 Notes Transactions If you are using transactions. See Also mysql_num_rows mysql_info 2. not after the COMMIT. 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. SELECT Statements To retrieve the number of rows returned by a SELECT.2. the MySQLi or PDO_MySQL extension should be used. Retrieves the character_set variable from MySQL. and will be removed in the future. it is possible to use mysql_num_rows. UPDATE. it will try to create one as if mysql_connect was called with no arguments.0. If no connection is found or established. [1] • mysql_client_encoding Returns the name of the character set Warning This extension is deprecated as of PHP 5. the last link opened by mysql_connect is assumed. See also MySQL: choosing an API guide and related FAQ for more information.

the MySQLi or PDO_MySQL extension should be used. as non-persistent open links are automatically closed at the end of the script's execution. [1] • mysql_close Close MySQL connection Warning This extension is deprecated as of PHP 5. mysql_close closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. Using mysql_close isn't usually necessary. 'mysql_user'. and will be removed in the future. mysql_client_encoding example <?php $link = mysql_connect('localhost'.3. See also freeing resources. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_close PDO: Assign the value of NULL to the PDO object Description bool mysql_close( resource link_identifier = =NULL). the last opened link is used.mysql_close Return Values Returns the default character set name for the current connection.5. $charset = mysql_client_encoding($link). Examples Example 2. 'mysql_password'). If link_identifier isn't specified.4.4. ?> The above example will output something similar to: The current character set is: latin1 See Also mysql_set_charset mysql_real_escape_string 2. Parameters 12 . mysql_close Copyright 1997-2012 the PHP Documentation Group. echo "The current character set is: $charset\n". Instead.0.

'mysql_user'. Examples Example 2. Alternatives to this function include: mysqli_connect PDO::__construct Description 13 . [1] • mysql_connect Open a connection to a MySQL Server Warning This extension is deprecated as of PHP 5.4.4. Instead. if (!$link) { die('Could not connect: ' . the MySQLi or PDO_MySQL extension should be used. } echo 'Connected successfully'. the last link opened by mysql_connect is assumed. and will be removed in the future. an E_WARNING level error is generated. See Also mysql_connect mysql_free_result 2. mysql_connect Copyright 1997-2012 the PHP Documentation Group. mysql_error()). If the link identifier is not specified. mysql_close($link).mysql_connect link_identifier The MySQL connection. See also MySQL: choosing an API guide and related FAQ for more information. mysql_close example <?php $link = mysql_connect('localhost'.0. 'mysql_password'). Return Values Returns TRUE on success or FALSE on failure. ?> The above example will output: Connected successfully Notes Note mysql_close will not close persistent links created by mysql_pconnect. If no connection is found or established.5.5.

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

mysql_close($link). 'mysql_user'. } echo 'Connected successfully'. mysql_error()).0. 'mysql_password'). if (!$link) { die('Could not connect: ' . // variant 2: with localhost $link = mysql_connect('localhost:/tmp/mysql. if (!$link) { die('Could not connect: ' . mysql_connect example using hostname:port syntax <?php // we connect to example. if (!$link) { die('Could not connect: ' . 'mysql_user'. mysql_error()). if (!$link) { die('Could not connect: ' . ?> Notes Note Whenever you specify "localhost" or "localhost:port" as server.mysql_connect Example 2. 'mysql_user'. } echo 'Connected successfully'. 'mysql_user'. 'mysql_user'. mysql_close($link).g.8. } echo 'Connected successfully'. mysql_error()). if (!$link) { die('Could not connect: ' . the MySQL client library will override this and try to connect to a local socket (named pipe on 15 . 'mysql_password').com:3307'. 'mysql_password'). mysql_close($link).0.1:3307'. } echo 'Connected successfully'. 'mysql_password'). ?> Example 2.sock // variant 1: omit localhost $link = mysql_connect(':/tmp/mysql'.sock'.com and port 3307 $link = mysql_connect('example. // we connect to localhost at port 3307 $link = mysql_connect('127. /tmp/mysql. mysql_close($link). ?> Example 2. mysql_error()). 'mysql_password'). mysql_connect example <?php $link = mysql_connect('localhost'.6. mysql_error()). mysql_close($link).7. mysql_connect example using ":/path/to/socket" syntax <?php // we connect to localhost and socket e. } echo 'Connected successfully'.

Note Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. unless it's closed earlier by explicitly calling mysql_close. use "127.mysql_create_db Windows). Note You can suppress the error message on failure by prepending a @ to the function name. Note The link to the server will be closed as soon as the execution of the script ends.0. Instead. mysql_create_db attempts to create a new database on the server associated with the specified link identifier. [1] • mysql_create_db Create a MySQL database Warning This extension is deprecated as of PHP 5. the MySQLi or PDO_MySQL extension should be used.5. Parameters database_name The name of the database being created. 16 .0.0. resource link_identifier = =NULL).4. you should set the correct path as mysql.1" instead of "localhost".default_host string in your PHP configuration and leave the server field blank. mysql_create_db Copyright 1997-2012 the PHP Documentation Group. On Windows. Alternatives to this function include: mysqli_query PDO::query Description bool mysql_create_db( string database_name. and will be removed in the future.5. See also MySQL: choosing an API guide and related FAQ for more information. See Also mysql_pconnect mysql_close 2. if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. If you want to use TCP/IP. If the MySQL client library tries to connect to the wrong local socket.

the last link opened by mysql_connect is assumed. } else { echo 'Error creating database: ' . if (mysql_query($sql.x client library. "\n". <?php $link = mysql_connect('localhost'.mysql_data_seek link_identifier The MySQL connection.4. } ?> The above example will output something similar to: Database my_db created successfully Notes Note For backward compatibility. $link)) { echo "Database my_db created successfully\n". mysql_data_seek Copyright 1997-2012 the PHP Documentation Group. If the link identifier is not specified. mysql_error() . Return Values Returns TRUE on success or FALSE on failure.9. 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. mysql_create_db alternative example The function mysql_create_db is deprecated. If no such link is found.6. mysql_error()). it will try to create one as if mysql_connect was called with no arguments. } $sql = 'CREATE DATABASE my_db'. 'mysql_user'. an E_WARNING level error is generated. If no connection is found or established. 'mysql_password'). It is preferable to use mysql_query to issue an sql CREATE DATABASE statement instead. if (!$link) { die('Could not connect: ' . Examples Example 2. [1] 17 . See Also mysql_query mysql_select_db 2.

would return that row.0. if (!$link) { die('Could not connect: ' . Parameters result The result resource that is being evaluated. mysql_data_seek example <?php $link = mysql_connect('localhost'. row_number starts at 0. Alternatives to this function include: mysqli_data_seek PDO::FETCH_ORI_ABS Description bool mysql_data_seek( resource result. However if the result set is empty (mysql_num_rows == 0). $result = mysql_query($query). 'mysql_password'). such as mysql_fetch_assoc. "\n". if (!$db_selected) { die('Could not select database: ' . 18 . mysql_error()).1. if (!$result) { die('Query failed: ' .10. 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. and will be removed in the future. $i >= 0. The desired row number of the new result pointer. row_number Return Values Returns TRUE on success or FALSE on failure. mysql_error()). mysql_error() . Examples Example 2. $i--) { if (!mysql_data_seek($result. int row_number). 'mysql_user'. Instead. } $query = 'SELECT last_name. the MySQLi or PDO_MySQL extension should be used.mysql_data_seek • mysql_data_seek Move internal result pointer Warning This extension is deprecated as of PHP 5. The row_number should be a value in the range from 0 to mysql_num_rows 1. } /* fetch rows in reverse order */ for ($i = mysql_num_rows($result) . } $db_selected = mysql_select_db('sample_db'). a seek to 0 will fail with a E_WARNING and mysql_data_seek will return FALSE . $i)) { echo "Cannot seek to row $i: " . See also MySQL: choosing an API guide and related FAQ for more information. The next call to a MySQL fetch function. mysql_error()).5. This result comes from a call to mysql_query. first_name FROM friends'.

The index into the result set. and will be removed in the future. Alternatives to this function include: Query: SELECT DATABASE() Description string mysql_db_name( resource result. ' ' .0. See Also mysql_query mysql_num_rows mysql_fetch_row mysql_fetch_assoc mysql_fetch_array mysql_fetch_object 2. the MySQLi or PDO_MySQL extension should be used. Instead. 19 . $row['first_name'] .5.mysql_db_name continue. not with mysql_unbuffered_query. Parameters result row The result pointer from a call to mysql_list_dbs. Retrieve the database name from a call to mysql_list_dbs.4. } if (!($row = mysql_fetch_assoc($result))) { continue. int row. "<br />\n". mysql_db_name Copyright 1997-2012 the PHP Documentation Group. } mysql_free_result($result). } echo $row['last_name'] . [1] • mysql_db_name Retrieves database name from the call to mysql_list_dbs Warning This extension is deprecated as of PHP 5. See also MySQL: choosing an API guide and related FAQ for more information. ?> Notes Note The function mysql_data_seek can be used in conjunction only with mysql_query.7. mixed field = =NULL).

0. [1] • mysql_db_query Selects a database and executes a query on it Warning This extension is deprecated as of PHP 5.11. Changelog Version 5. $i) . mysql_db_name example <?php error_reporting(E_ALL). the MySQLi or PDO_MySQL extension should be used.5.mysql_db_query field Return Values The field name.5. Examples Example 2. Returns the database name on success. $db_list = mysql_list_dbs($link). If FALSE is returned. $cnt = mysql_num_rows($db_list). } ?> Notes Note For backward compatibility. Alternatives to this function include: 20 . $i = 0. $i++. the following deprecated alias may be used: mysql_dbname See Also mysql_list_dbs mysql_tablename 2. Instead. 'password'). mysql_db_query Copyright 1997-2012 the PHP Documentation Group. use mysql_error to determine the nature of the error.8. $link = mysql_connect('dbhost'. 'username'. "\n". and emits an E_DEPRECATED level error.4. and will be removed in the future. while ($i < $cnt) { echo mysql_db_name($db_list.0 Description The mysql_list_dbs function is deprecated. and FALSE on failure. See also MySQL: choosing an API guide and related FAQ for more information.

If the link identifier is not specified.6 Description This function now throws an E_DEPRECATED notice. link_identifier The MySQL connection. This function is deprecated.mysql_db_query mysqli_select_db then the query PDO::__construct Description resource mysql_db_query( string database. If no connection is found or established. Relying on this feature is highly discouraged. or FALSE on error. exit. 'mysql_user'. resource link_identifier = =NULL). Warning This function has been DEPRECATED as of PHP 5. Return Values Returns a positive MySQL result resource to the query result.0 4. string query. do not use this function.12. The function also returns TRUE / FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure. mysql_db_query selects a database.0. Examples Example 2. } if (!mysql_select_db('mysql_dbname'. Changelog Version 5.3. 21 . $link)) { echo 'Could not select database'. Data inside the query should be properly escaped. the last link opened by mysql_connect is assumed. it will try to create one as if mysql_connect was called with no arguments. The MySQL query.3. Use mysql_select_db and mysql_query instead.0. an E_WARNING level error is generated. If no such link is found. 'mysql_password')) { echo 'Could not connect to mysql'. and executes a query on it. mysql_db_query alternative example <?php if (!$link = mysql_connect('mysql_host'. Parameters database query The name of the database that will be selected.

See also MySQL: choosing an API guide and related FAQ for more information. Instead. resource link_identifier = =NULL). } while ($row = mysql_fetch_assoc($result)) { echo $row['foo']. mysql_drop_db Copyright 1997-2012 the PHP Documentation Group. $link). and will be removed in the future. $result = mysql_query($sql. you can't use this function to temporarily run a sql query on another database. exit. Users are strongly encouraged to use the database.5. mysql_drop_db attempts to drop (remove) an entire database from the server associated with the specified link identifier.9. Parameters 22 .4. ?> Notes Note Be aware that this function does NOT switch back to the database you were connected before. mysql_error(). In other words.mysql_drop_db exit. you would have to manually switch back. if (!$result) { echo "DB Error. This function is deprecated. } mysql_free_result($result). the MySQLi or PDO_MySQL extension should be used. [1] • mysql_drop_db Drop (delete) a MySQL database Warning This extension is deprecated as of PHP 5. could not query the database\n". } $sql = 'SELECT foo FROM bar WHERE id = 42'. it is preferable to use mysql_query to issue an sql DROP DATABASE statement instead. See Also mysql_query mysql_select_db 2.0.table syntax in their sql queries or mysql_select_db instead of this function. Alternatives to this function include: Execute a DROP DATABASE query Description bool mysql_drop_db( string database_name. echo 'MySQL Error: ' .

and will be removed in the future. If no such link is found. if (!$link) { die('Could not connect: ' . 'mysql_user'. } ?> Notes Warning This function will not be available if the MySQL extension was built against a MySQL 4. the following deprecated alias may be used: mysql_dropdb See Also mysql_query 2. If the link identifier is not specified. if (mysql_query($sql. the MySQLi or PDO_MySQL extension should be used. See also MySQL: 23 . mysql_error() . it will try to create one as if mysql_connect was called with no arguments.x client library. If no connection is found or established.10. } $sql = 'DROP DATABASE my_db'.mysql_errno database_name link_identifier The name of the database that will be deleted.4. mysql_drop_db alternative example <?php $link = mysql_connect('localhost'. the last link opened by mysql_connect is assumed. } else { echo 'Error dropping database: ' . Instead.13. Note For backward compatibility. mysql_error()). Examples Example 2.5. an E_WARNING level error is generated. $link)) { echo "Database my_db was successfully dropped\n". [1] • mysql_errno Returns the numerical value of the error message from previous MySQL operation Warning This extension is deprecated as of PHP 5. mysql_errno Copyright 1997-2012 the PHP Documentation Group. 'mysql_password'). The MySQL connection. Return Values Returns TRUE on success or FALSE on failure.0. "\n".

$link)) { echo mysql_errno($link) . Instead. Examples Example 2. if (!mysql_query("SELECT * FROM nonexistenttable". use mysql_errno to retrieve the error code. ": " . mysql_error($link) . } ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu. ": " . make sure you check the value before calling another MySQL function. so if you want to use it. it will try to create one as if mysql_connect was called with no arguments. mysql_error($link). If no connection is found or established. an E_WARNING level error is generated. Parameters link_identifier The MySQL connection.mysql_errno choosing an API guide and related FAQ for more information. "\n". Errors coming back from the MySQL database backend no longer issue warnings. Return Values Returns the error number from the last MySQL function. } mysql_select_db("kossu". the last link opened by mysql_connect is assumed. "\n". mysql_errno example <?php $link = mysql_connect("localhost". Returns the error number from the last MySQL function. "mysql_password"). Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error and mysql_errno).14. Alternatives to this function include: mysqli_errno PDO::errorCode Description int mysql_errno( resource link_identifier = =NULL). $link). If no such link is found.nonexistenttable' doesn't exist See Also mysql_error 24 . "mysql_user". or 0 (zero) if no error occurred. $link)) { echo mysql_errno($link) . If the link identifier is not specified. if (!mysql_select_db("nonexistentdb".

0. "\n". mysql_error example <?php $link = mysql_connect("localhost". it will try to create one as if mysql_connect was called with no arguments. [1] • mysql_error Returns the text of the error message from previous MySQL operation Warning This extension is deprecated as of PHP 5.mysql_error MySQL error codes 2. make sure you check the value before calling another MySQL function.5. Alternatives to this function include: mysqli_error PDO::errorInfo Description string mysql_error( resource link_identifier = =NULL). echo mysql_errno($link) . use mysql_error to retrieve the error text. Return Values Returns the error text from the last MySQL function.4. $link). Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error and mysql_errno). mysql_query("SELECT * FROM nonexistenttable". mysql_select_db("nonexistentdb". mysql_error($link). Instead. so if you want to use it.11. Examples Example 2. ": " . $link). "mysql_user". the last link opened by mysql_connect is assumed. "\n". If no such link is found. the MySQLi or PDO_MySQL extension should be used. mysql_error($link) . mysql_error Copyright 1997-2012 the PHP Documentation Group. ": " . Parameters link_identifier The MySQL connection. See also MySQL: choosing an API guide and related FAQ for more information. an E_WARNING level error is generated. "mysql_password"). or '' (empty string) if no error occurred. If the link identifier is not specified. $link). Errors coming back from the MySQL database backend no longer issue warnings. ?> 25 .15. mysql_select_db("kossu". echo mysql_errno($link) . Returns the error text from the last MySQL function. If no connection is found or established. and will be removed in the future. Instead.

4. so that it is safe to place it in a mysql_query. Changelog The string that is to be escaped. This function is deprecated. This function will escape the unescaped_string. mysql_escape_string Copyright 1997-2012 the PHP Documentation Group. the MySQLi or PDO_MySQL extension should be used. Instead. Parameters unescaped_string Return Values Returns the escaped string.nonexistenttable' doesn't exist See Also mysql_errno MySQL error codes 2.0.0.3.mysql_escape_string The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu. Warning This function has been DEPRECATED as of PHP 5. and will be removed in the future.5. Alternatives to this function include: mysqli_escape_string PDO::quote Description string mysql_escape_string( string unescaped_string). See also MySQL: choosing an API guide and related FAQ for more information. 26 . Relying on this feature is highly discouraged. 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. [1] • mysql_escape_string Escapes a string for use in a mysql_query Warning This extension is deprecated as of PHP 5.12. mysql_escape_string does not take a connection argument and does not respect the current charset setting.

This function became deprecated. $escaped_item = mysql_escape_string($item).16. Alternatives to this function include: mysqli_fetch_array PDOStatement::fetch Description 27 . Instead.4. Examples Example 2. a numeric array.13.3. ?> The above example will output: Escaped string: Zak\'s Laptop Notes Note mysql_escape_string does not escape % and _. do not use this function.3. printf("Escaped string: %s\n". mysql_fetch_array Copyright 1997-2012 the PHP Documentation Group. use mysql_real_escape_string. [1] • mysql_fetch_array Fetch a result row as an associative array.mysql_fetch_array Version 5.0 Description This function now throws an E_DEPRECATED notice.0. 2. mysql_escape_string example <?php $item = "Zak's Laptop".0 4. Instead. See also MySQL: choosing an API guide and related FAQ for more information. the MySQLi or PDO_MySQL extension should be used. and will be removed in the future.5. $escaped_item). or both Warning This extension is deprecated as of PHP 5. See Also mysql_real_escape_string addslashes The magic_quotes_gpc directive.

"mysql_password") or die("Could not connect: " . ?> Example 2. and MYSQL_BOTH .17. while ($row = mysql_fetch_array($result. "mysql_user". "mysql_password") or die("Could not connect: " . Query with aliased duplicate field names SELECT table1.field AS foo. the last column will take precedence. This result comes from a call to mysql_query. MYSQL_NUM)) { printf("ID: %s Name: %s". MYSQL_ASSOC)) { printf("ID: %s Name: %s". $row[0]. $row["name"]). name FROM mytable"). 28 .18. you only get associative indices (as mysql_fetch_assoc works). mysql_error()). MYSQL_NUM . $row[1]).field AS bar FROM table1. } mysql_free_result($result). Parameters result The result resource that is being evaluated. The type of array that is to be fetched. while ($row = mysql_fetch_array($result. mysql_select_db("mydb"). For aliased columns. $result = mysql_query("SELECT id. result_type Return Values Returns an array of strings that corresponds to the fetched row. using MYSQL_NUM . Examples Example 2. int result_type = =MYSQL_BOTH). table2.19. mysql_fetch_array with MYSQL_ASSOC <?php mysql_connect("localhost". you only get number indices (as mysql_fetch_row works). table2 Example 2. By using MYSQL_BOTH (default). $row["id"]. mysql_fetch_array with MYSQL_NUM <?php mysql_connect("localhost".mysql_fetch_array array mysql_fetch_array( resource result. Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. "mysql_user". It's a constant and can take the following values: MYSQL_ASSOC . The type of returned array depends on how result_type is defined. you'll get an array with both associative and number indices. or FALSE if there are no more rows. $result = mysql_query("SELECT id. name FROM mytable"). Using MYSQL_ASSOC . If two or more columns of the result have the same field names. mysql_select_db("mydb"). you cannot access the contents with the original column name. mysql_error()). To access the other column(s) of the same name. you must use the numeric index of the column or make an alias for the column.

14. [1] • mysql_fetch_assoc Fetch a result row as an associative array Warning This extension is deprecated as of PHP 5. name FROM mytable"). ?> Notes Performance An important thing to note is that using mysql_fetch_array is not significantly slower than using mysql_fetch_row. "mysql_user". $row["name"]). mysql_fetch_array with MYSQL_BOTH <?php mysql_connect("localhost".4. while it provides a significant added value. See also MySQL: choosing an API guide and related FAQ for more information.20. mysql_select_db("mydb"). $result = mysql_query("SELECT id. mysql_error()). Note Field names returned by this function are case-sensitive. ?> Example 2. See Also mysql_fetch_row mysql_fetch_assoc mysql_data_seek mysql_query 2. Instead. $row[0]. "mysql_password") or die("Could not connect: " . mysql_fetch_assoc Copyright 1997-2012 the PHP Documentation Group. while ($row = mysql_fetch_array($result.mysql_fetch_assoc } mysql_free_result($result). and will be removed in the future. MYSQL_BOTH)) { printf ("ID: %s Name: %s".0. } mysql_free_result($result).5. the MySQLi or PDO_MySQL extension should be used. Note This function sets NULL fields to the PHP NULL value. Alternatives to this function include: mysqli_fetch_assoc 29 .

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

This function can be used to obtain information about fields in the provided query result. and will be removed in the future. Alternatives to this function include: mysqli_fetch_field PDOStatement::getColumnMeta Description object mysql_fetch_field( resource result.mysql_fetch_field ?> Notes Performance An important thing to note is that using mysql_fetch_assoc is not significantly slower than using mysql_fetch_row. Note Field names returned by this function are case-sensitive.15. int field_offset = =0). See Also mysql_fetch_row mysql_fetch_array mysql_data_seek mysql_query mysql_error 2. [1] • mysql_fetch_field Get column information from a result and return as an object Warning This extension is deprecated as of PHP 5. the MySQLi or PDO_MySQL extension should be used.0. while it provides a significant added value. Note This function sets NULL fields to the PHP NULL value.4. Returns an object containing field information. Instead. 31 . This result comes from a call to mysql_query. mysql_fetch_field Copyright 1997-2012 the PHP Documentation Group. See also MySQL: choosing an API guide and related FAQ for more information.5. Parameters result The result resource that is being evaluated.

} mysql_select_db('database').1 if the column is numeric • blob .name of the table the column belongs to. if (!$result) { die('Query failed: ' . mysql_error()). while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />\n".1 if the column is a non-unique key • numeric . If the field offset is not specified.1 if the column is a unique key • multiple_key . if (!$conn) { die('Could not connect: ' .22. the next field that was not yet retrieved by this function is retrieved. } /* get column metadata */ $i = 0. $result = mysql_query('select * from table'). Return Values Returns an object containing field information. $i).maximum length of the column • not_null . The properties of the object are: • name . The field_offset starts at 0. 'mysql_password'). which is the alias name if one is defined • max_length .1 if the column is zero-filled Examples Example 2.the type of the column • unsigned .1 if the column cannot be NULL • primary_key .column name • table . } 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 32 .mysql_fetch_field field_offset The numerical field offset.1 if the column is a primary key • unique_key .1 if the column is unsigned • zerofill . 'mysql_user'. if (!$meta) { echo "No information available<br />\n". mysql_error()). mysql_fetch_field example <?php $conn = mysql_connect('localhost'.1 if the column is a BLOB • type . $meta = mysql_fetch_field($result.

Note If field or tablenames are aliased in the SQL query the aliased name will be returned. ?> Notes Note Field names returned by this function are case-sensitive. mysql_fetch_lengths Copyright 1997-2012 the PHP Documentation Group. The original name can be retrieved for instance by using mysqli_result::fetch_field. mysql_fetch_lengths stores the lengths of each result column in the last row returned by mysql_fetch_row. $i++. Instead. Alternatives to this function include: mysqli_fetch_lengths PDOStatement::getColumnMeta Description array mysql_fetch_lengths( resource result). [1] • mysql_fetch_lengths Get the length of each output in a result Warning This extension is deprecated as of PHP 5. starting at offset 0. } mysql_free_result($result).16.5. and will be removed in the future. Parameters 33 . See Also mysql_field_seek 2. and mysql_fetch_object in an array. See also MySQL: choosing an API guide and related FAQ for more information.0. mysql_fetch_assoc. Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.mysql_fetch_lengths primary_key: $meta->primary_key table: $meta->table type: $meta->type unique_key: $meta->unique_key unsigned: $meta->unsigned zerofill: $meta->zerofill </pre>". the MySQLi or PDO_MySQL extension should be used.4. mysql_fetch_array.

An array of lengths on success or FALSE on failure. Alternatives to this function include: 34 .23.17.4. This result comes from a call to mysql_query.email FROM people WHERE id = '42'").0. Instead. } $row = mysql_fetch_assoc($result). print_r($row).5. if (!$result) { echo 'Could not run query: ' . A mysql_fetch_lengths example <?php $result = mysql_query("SELECT id. Examples Example 2. mysql_error(). ?> The above example will output something similar to: Array ( [id] => 42 [email] => user@example. mysql_fetch_object Copyright 1997-2012 the PHP Documentation Group. $lengths = mysql_fetch_lengths($result).mysql_fetch_object result Return Values The result resource that is being evaluated. exit. See also MySQL: choosing an API guide and related FAQ for more information. the MySQLi or PDO_MySQL extension should be used. print_r($lengths).com ) Array ( [0] => 2 [1] => 16 ) See Also mysql_field_len mysql_fetch_row strlen 2. [1] • mysql_fetch_object Fetch a result row as an object Warning This extension is deprecated as of PHP 5. and will be removed in the future.

or FALSE if there are no more rows. mysql_fetch_object example <?php mysql_connect("hostname". This result comes from a call to mysql_query. $result = mysql_query("select * from mytable"). mysql_select_db("mydb"). "user". array params). "password"). ?> Description Added the ability to return as a different object. Parameters result The result resource that is being evaluated. An optional array of parameters to pass to the constructor for class_name objects. Example 2. If not specified. while ($row = mysql_fetch_object($result)) { echo $row->user_id.0 Examples Example 2. echo $row->fullname. The name of the class to instantiate. set the properties of and return. } mysql_free_result($result).25. string class_name. Changelog Version 5.24. class_name params Return Values Returns an object with string properties that correspond to the fetched row.0.mysql_fetch_object mysqli_fetch_object PDOStatement::fetch(PDO::FETCH_OBJ) Description object mysql_fetch_object( resource result. 35 . } mysql_connect("hostname". Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. "user". a stdClass object is returned. mysql_select_db("mydb"). mysql_fetch_object example <?php class foo { public $name. "password").

and will be removed in the future. with one difference an object is returned. the MySQLi or PDO_MySQL extension should be used.5. and almost as quick as mysql_fetch_row (the difference is insignificant). See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_row mysql_data_seek mysql_query 2. var_dump($obj). See also MySQL: choosing an API guide and related FAQ for more information. and not by their offsets (numbers are illegal property names). the function is identical to mysql_fetch_array. Note mysql_fetch_object is similar to mysql_fetch_array.mysql_fetch_row $result = mysql_query("select name from mytable limit 1"). Note This function sets NULL fields to the PHP NULL value.18. 'foo'). instead of an array. Alternatives to this function include: mysqli_fetch_row PDOStatement::fetch(PDO::FETCH_NUM) Description array mysql_fetch_row( resource result).0. $obj = mysql_fetch_object($result. 36 .4. that means that you can only access the data by the field names. Indirectly. ?> Notes Performance Speed-wise. Note Field names returned by this function are case-sensitive. Instead. mysql_fetch_row Copyright 1997-2012 the PHP Documentation Group. [1] • mysql_fetch_row Get a result row as an enumerated array Warning This extension is deprecated as of PHP 5.

mysql_field_flags Copyright 1997-2012 the PHP Documentation Group. starting at offset 0. exit. and will be removed in the future. Fetching one row with mysql_fetch_row <?php $result = mysql_query("SELECT id. or FALSE if there are no more rows. Instead.26. the MySQLi or PDO_MySQL extension should be used. if (!$result) { echo 'Could not run query: ' . // the email value ?> The result resource that is being evaluated. } $row = mysql_fetch_row($result). Examples Example 2.4. See also MySQL: 37 . mysql_fetch_row fetches one row of data from the result associated with the specified result identifier. [1] • mysql_field_flags Get the flags associated with the specified field in a result Warning This extension is deprecated as of PHP 5.19. The row is returned as an array.email FROM people WHERE id = '42'"). Each result column is stored in an array offset. Parameters result Return Values Returns an numerical array of strings that corresponds to the fetched row.mysql_field_flags Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. // 42 echo $row[1].5.0. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_result 2. This result comes from a call to mysql_query. mysql_error(). echo $row[0]. Notes Note This function sets NULL fields to the PHP NULL value.

"primary_key". "zerofill". mysql_error(). 0). exit. "unique_key". field_offset Return Values Returns a string of flags associated with the result or FALSE on failure. echo $flags. if (!$result) { echo 'Could not run query: ' . so that you can split the returned value using explode. If field_offset does not exist. int field_offset). "blob". } $flags = mysql_field_flags($result. A mysql_field_flags example <?php $result = mysql_query("SELECT id. "binary". "multiple_key". Parameters result The result resource that is being evaluated. "auto_increment" and "timestamp". an error of level E_WARNING is also issued.email FROM people WHERE id = '42'"). The field_offset starts at 0. "unsigned". mysql_field_flags returns the field flags of the specified field. ?> The above example will output something similar to: not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment ) 38 . The numerical field offset.mysql_field_flags choosing an API guide and related FAQ for more information. The flags are reported as a single word per flag separated by a single space. print_r(explode(' '. Alternatives to this function include: mysqli_fetch_fields [flags] PDOStatement::getColumnMeta [flags] Description string mysql_field_flags( resource result. Examples Example 2. This result comes from a call to mysql_query.27. if your version of MySQL is current enough to support them: "not_null". "enum". $flags)). The following flags are reported.

and will be removed in the future. mysql_field_len Copyright 1997-2012 the PHP Documentation Group. field_offset Return Values The length of the specified field index on success or FALSE on failure.mysql_field_len Notes Note For backward compatibility. int field_offset).28. the MySQLi or PDO_MySQL extension should be used. The numerical field offset.4. the following deprecated alias may be used: mysql_fieldflags See Also mysql_field_type mysql_field_len 2. Instead. [1] • mysql_field_len Returns the length of the specified field Warning This extension is deprecated as of PHP 5. an error of level E_WARNING is also issued. mysql_field_len example 39 .5.20.0. See also MySQL: choosing an API guide and related FAQ for more information. Examples Example 2. mysql_field_len returns the length of the specified field. Alternatives to this function include: mysqli_fetch_field_direct [length] PDOStatement::getColumnMeta [len] Description int mysql_field_len( resource result. The field_offset starts at 0. Parameters result The result resource that is being evaluated. If field_offset does not exist. This result comes from a call to mysql_query.

[1] • mysql_field_name Get the name of the specified field in a result Warning This extension is deprecated as of PHP 5. The field_offset starts at 0. mysql_field_name returns the name of the specified field index. } // Will get the length of the id field as specified in the database // schema. mysql_field_name Copyright 1997-2012 the PHP Documentation Group. ?> Notes Note For backward compatibility. the following deprecated alias may be used: mysql_fieldlen See Also mysql_fetch_lengths strlen 2. an error of level E_WARNING is also issued.mysql_field_name <?php $result = mysql_query("SELECT id. If field_offset does not exist. exit.0. Parameters result The result resource that is being evaluated. int field_offset). 0). if (!$result) { echo 'Could not run query: ' . echo $length.5. See also MySQL: choosing an API guide and related FAQ for more information. field_offset 40 . mysql_error().email FROM people WHERE id = '42'"). and will be removed in the future. Instead. the MySQLi or PDO_MySQL extension should be used. $length = mysql_field_len($result.4.21. Alternatives to this function include: mysqli_fetch_field_direct [name] or [orgname] PDOStatement::getColumnMeta [name] Description string mysql_field_name( resource result. This result comes from a call to mysql_query. The numerical field offset.

'mysql_password').29. } $res = mysql_query('select * from users'.22. if (!$db_selected) { die("Could not set $dbname: " . Note For backward compatibility. ?> The above example will output: user_id password Notes Note Field names returned by this function are case-sensitive. mysql_error()).mysql_field_seek Return Values The name of the specified field index on success or FALSE on failure. "\n". $link). mysql_field_name example <?php /* The users table consists of three fields: * user_id * username * password. $link). } $dbname = 'mydb'. mysql_error()). $db_selected = mysql_select_db($dbname. 2). 'mysql_user'. Examples Example 2. 0) . [1] • mysql_field_seek Set result pointer to a specified field offset 41 . echo mysql_field_name($res. the following deprecated alias may be used: mysql_fieldname See Also mysql_field_type mysql_field_len 2. echo mysql_field_name($res.4. if (!$link) { die('Could not connect to MySQL server: ' . mysql_field_seek Copyright 1997-2012 the PHP Documentation Group. */ $link = mysql_connect('localhost'.

Alternatives to this function include: mysqli_field_seek PDOStatement::fetch using optional parameters Description bool mysql_field_seek( resource result. The field_offset starts at 0. an error of level E_WARNING is also issued. field_offset Return Values Returns TRUE on success or FALSE on failure. the MySQLi or PDO_MySQL extension should be used. Seeks to the specified field offset. the field offset specified in mysql_field_seek will be returned.0. See also MySQL: choosing an API guide and related FAQ for more information. int field_offset). If field_offset does not exist.23. Instead. Instead. the MySQLi or PDO_MySQL extension should be used.4. See also MySQL: choosing an API guide and related FAQ for more information. The numerical field offset. 42 . [1] • mysql_field_table Get name of the table the specified field is in Warning This extension is deprecated as of PHP 5. int field_offset). and will be removed in the future.mysql_field_table Warning This extension is deprecated as of PHP 5.5. See Also mysql_fetch_field 2. This result comes from a call to mysql_query. Parameters result The result resource that is being evaluated. Alternatives to this function include: mysqli_fetch_field_direct [table] or [orgtable] PDOStatement::getColumnMeta [table] Description string mysql_field_table( resource result. and will be removed in the future. mysql_field_table Copyright 1997-2012 the PHP Documentation Group.0. If the next call to mysql_fetch_field doesn't include a field offset.5.

$i). country WHERE country. $i).4. ++$i) { $table = mysql_field_table($result. The numerical field offset. $field = mysql_field_name($result. Alternatives to this function include: mysqli_fetch_field_direct [type] 43 . an error of level E_WARNING is also issued. the MySQLi or PDO_MySQL extension should be used. mysql_field_type Copyright 1997-2012 the PHP Documentation Group.* FROM account. and will be removed in the future. Parameters result The result resource that is being evaluated.30. Examples Example 2.cou // get the result from the DB $result = mysql_query($query). $i < mysql_num_fields($result). echo "$table: $field\n". [1] • mysql_field_type Get the type of the specified field in a result Warning This extension is deprecated as of PHP 5. This result comes from a call to mysql_query. the following deprecated alias may be used: mysql_fieldtable See Also mysql_list_tables 2.0.mysql_field_type Returns the name of the table that the specified field is in. The field_offset starts at 0.24. If field_offset does not exist. See also MySQL: choosing an API guide and related FAQ for more information. Instead. country.name = 'Portugal' AND account. field_offset Return Values The name of the table on success. A mysql_field_table example <?php $query = "SELECT account. // Lists the table name and then the field name for ($i = 0.*.5. } ?> Notes Note For backward compatibility.

$len = mysql_field_len($result. $i). } mysql_free_result($result).31. and others as detailed in the MySQL documentation. "real". echo "The table has the following fields:\n". $len .mysql_field_type PDOStatement::getColumnMeta [driver:decl_type] or [pdo_type] Description string mysql_field_type( resource result. $i < $fields. mysql_close(). $i). $i). $rows = mysql_num_rows($result). " " . $fields = mysql_num_fields($result). ?> 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 44 . an error of level E_WARNING is also issued. The field_offset starts at 0. $fields . This result comes from a call to mysql_query. "string". $name . $i). $name = mysql_field_name($result. "blob". int field_offset). $flags . "' table has " . field_offset Return Values The returned field type will be one of "int". If field_offset does not exist. $table = mysql_field_table($result. Parameters result The result resource that is being evaluated. for ($i=0. Examples Example 2. $result = mysql_query("SELECT * FROM func"). but the field type is returned instead. $rows . mysql_field_type is similar to the mysql_field_name function. " record(s)\n". The numerical field offset. " " . mysql_select_db("mysql"). echo "Your '" . echo $type . mysql_field_type example <?php mysql_connect("localhost". The arguments are identical. " " . "mysql_password"). "\n". "mysql_username". " fields and " . $flags = mysql_field_flags($result. $i++) { $type = mysql_field_type($result. 0). $table .

or PDOStatement::closeCursor Description bool mysql_free_result( resource result). Examples Example 2. the following deprecated alias may be used: mysql_fieldtype See Also mysql_field_name mysql_field_len 2. the MySQLi or PDO_MySQL extension should be used.mysql_free_result Notes Note For backward compatibility. SHOW. mysql_free_result will free all memory associated with the result identifier result. All associated result memory is automatically freed at the end of the script's execution.4. 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. Instead. Alternatives to this function include: mysqli_free_result Assign the value of NULL to the PDO object. If a non-resource is used for the result. [1] • mysql_free_result Free result memory Warning This extension is deprecated as of PHP 5.25. A mysql_free_result example <?php The result resource that is being evaluated. and will be removed in the future.0. an error of level E_WARNING will be emitted. It's worth noting that mysql_query only returns a resource for SELECT. This result comes from a call to mysql_query. 45 . EXPLAIN.5.32. See also MySQL: choosing an API guide and related FAQ for more information. mysql_free_result Copyright 1997-2012 the PHP Documentation Group. and DESCRIBE queries. Parameters result Return Values Returns TRUE on success or FALSE on failure.

See also MySQL: choosing an API guide and related FAQ for more information. assuming we're done with it afterwards */ $row = mysql_fetch_assoc($result).33. [1] • mysql_get_client_info Get MySQL client info Warning This extension is deprecated as of PHP 5. } /* Use the result. the following deprecated alias may be used: mysql_freeresult See Also mysql_query is_resource 2. exit.26.5. Return Values The MySQL client version. Examples Example 2. and will be removed in the future. echo $row['email']. if (!$result) { echo 'Could not run query: ' . mysql_get_client_info Copyright 1997-2012 the PHP Documentation Group. Alternatives to this function include: mysqli_get_client_info PDO::getAttribute(PDO::ATTR_CLIENT_VERSION) Description string mysql_get_client_info().mysql_get_client_info $result = mysql_query("SELECT id.0.4.email FROM people WHERE id = '42'"). ?> Notes Note For backward compatibility. mysql_error(). /* Now we free up the result and continue on with our script */ mysql_free_result($result). mysql_get_client_info returns a string that represents the client library version. the MySQLi or PDO_MySQL extension should be used. echo $row['id']. mysql_get_client_info example 46 . Instead.

the MySQLi or PDO_MySQL extension should be used. Parameters link_identifier The MySQL connection. Describes the type of connection in use for the connection. the last link opened by mysql_connect is assumed. Instead. it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established.27. ?> The above example will output something similar to: MySQL client info: 3.39 See Also mysql_get_host_info mysql_get_proto_info mysql_get_server_info 2.mysql_get_host_info <?php printf("MySQL client info: %s\n". an E_WARNING level error is generated. If the link identifier is not specified. If no such link is found. and will be removed in the future.5.4. Examples 47 . [1] • mysql_get_host_info Get MySQL host info Warning This extension is deprecated as of PHP 5. mysql_get_host_info Copyright 1997-2012 the PHP Documentation Group. including the server host name. Alternatives to this function include: mysqli_get_host_info PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS) Description string mysql_get_host_info( resource link_identifier = =NULL).0. mysql_get_client_info()).23. Return Values Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure. See also MySQL: choosing an API guide and related FAQ for more information.

0. it will try to create one as if mysql_connect was called with no arguments. ?> 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 2. and will be removed in the future. Return Values 48 . If no connection is found or established. Instead.28. mysql_get_host_info()).34. 'mysql_user'.4. See also MySQL: choosing an API guide and related FAQ for more information. the last link opened by mysql_connect is assumed. the MySQLi or PDO_MySQL extension should be used.5. 'mysql_password'). mysql_get_proto_info Copyright 1997-2012 the PHP Documentation Group. if (!$link) { die('Could not connect: ' . [1] • mysql_get_proto_info Get MySQL protocol info Warning This extension is deprecated as of PHP 5. mysql_error()). Alternatives to this function include: mysqli_get_proto_info Description int mysql_get_proto_info( resource link_identifier = =NULL). If no such link is found. If the link identifier is not specified. Parameters link_identifier The MySQL connection. } printf("MySQL host info: %s\n". mysql_get_host_info example <?php $link = mysql_connect('localhost'.mysql_get_proto_info Example 2. an E_WARNING level error is generated. Retrieves the MySQL protocol.

4. mysql_get_server_info Copyright 1997-2012 the PHP Documentation Group. and will be removed in the future. mysql_error()). ?> The above example will output something similar to: MySQL protocol version: 10 See Also mysql_get_client_info mysql_get_host_info mysql_get_server_info 2. Instead. mysql_get_proto_info example <?php $link = mysql_connect('localhost'. Parameters link_identifier The MySQL connection.29. If the link identifier is not specified. the last link opened by mysql_connect is assumed. mysql_get_proto_info()). If no such link is found.mysql_get_server_info Returns the MySQL protocol on success or FALSE on failure. [1] • mysql_get_server_info Get MySQL server info Warning This extension is deprecated as of PHP 5. Retrieves the MySQL server version. } printf("MySQL protocol version: %s\n". See also MySQL: choosing an API guide and related FAQ for more information. Examples Example 2.35. if (!$link) { die('Could not connect: ' . the MySQLi or PDO_MySQL extension should be used. it will try to create one as if mysql_connect was called with no arguments. 'mysql_user'. 49 .5. Alternatives to this function include: mysqli_get_server_info PDO::getAttribute(PDO::ATTR_SERVER_VERSION) Description string mysql_get_server_info( resource link_identifier = =NULL).0. 'mysql_password').

} printf("MySQL server version: %s\n".30. mysql_get_server_info()). Return Values Returns the MySQL server version on success or FALSE on failure.mysql_info If no connection is found or established.5. mysql_get_server_info example <?php $link = mysql_connect('localhost'.36. mysql_error()).4. [1] • mysql_info Get information about the most recent query Warning This extension is deprecated as of PHP 5. ?> The above example will output something similar to: MySQL server version: 4. mysql_info Copyright 1997-2012 the PHP Documentation Group.0. the MySQLi or PDO_MySQL extension should be used. if (!$link) { die('Could not connect: ' . Instead. Examples Example 2. 'mysql_user'. 50 . an E_WARNING level error is generated.0. Alternatives to this function include: mysqli_info Description string mysql_info( resource link_identifier = =NULL).1-alpha See Also mysql_get_client_info mysql_get_host_info mysql_get_proto_info phpversion 2. 'mysql_password'). and will be removed in the future. See also MySQL: choosing an API guide and related FAQ for more information. Returns detailed information about the last query.

.mysql_insert_id Parameters link_identifier The MySQL connection.. VALUES (.4. See the example below for which statements provide information..(. mysql_insert_id Copyright 1997-2012 the PHP Documentation Group. See Also mysql_affected_rows mysql_insert_id mysql_stat 2.. Examples Example 2. The numbers are only for illustrating purpose. String format: Records: 23 Duplicates: 0 Warnings: 0 INSERT INTO .. and will be removed in the future. and what the returned value may look like. an E_WARNING level error is generated.. If no connection is found or established. [1] • mysql_insert_id Get the ID generated in the last query Warning This extension is deprecated as of PHP 5.... it will try to create one as if mysql_connect was called with no arguments.. their values will correspond to the query..).0. Statements that are not listed will return FALSE .. Instead. If the link identifier is not specified.5.. SELECT .). If no such link is found...(. See also MySQL: 51 . String format: Records: 37 Duplicates: 0 Warnings: 0 LOAD DATA INFILE . INSERT INTO ...37. Return Values Returns information about the statement on success. VALUES statement only if multiple value lists are specified in the statement. the MySQLi or PDO_MySQL extension should be used.).FALSE value for the INSERT . 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 last link opened by mysql_connect is assumed. Relevant MySQL Statements Statements that return string values..31. or FALSE on failure.

if (!$link) { die('Could not connect: ' . 0 if the previous query does not generate an AUTO_INCREMENT value. mysql_error()). } mysql_select_db('mydb'). use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. Examples Example 2. please see the integer documentation. Alternatives to this function include: mysqli_insert_id PDO::lastInsertId Description int mysql_insert_id( resource link_identifier = =NULL). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). 'mysql_user'. an E_WARNING level error is generated. For more information about PHP's maximum integer values. If no such link is found. Parameters link_identifier The MySQL connection. be sure to call mysql_insert_id immediately after the query that generates the value. 'mysql_password'). mysql_insert_id()).38. Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success. Note Because mysql_insert_id acts on the last performed query. it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established. If the link identifier is not specified. mysql_query("INSERT INTO mytable (product) values ('kossu')"). ?> 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).mysql_insert_id choosing an API guide and related FAQ for more information. 52 . printf("Last inserted record has id %d\n". or FALSE if no MySQL connection was established. Instead. mysql_insert_id example <?php $link = mysql_connect('localhost'. the last link opened by mysql_connect is assumed.

an E_WARNING level error is generated.32.0.4. mysql_list_dbs Copyright 1997-2012 the PHP Documentation Group. Instead.5. and will be removed in the future. Use the mysql_tablename function to traverse this result pointer. or any function for result tables. or FALSE on failure. Returns a result pointer containing the databases available from the current mysql daemon. Parameters link_identifier The MySQL connection. the MySQLi or PDO_MySQL extension should be used. the last link opened by mysql_connect is assumed. Warning This function has been DEPRECATED as of PHP 5. [1] • mysql_list_dbs List databases available on a MySQL server Warning This extension is deprecated as of PHP 5. mysql_list_dbs example 53 . Return Values Returns a result pointer resource on success.mysql_list_dbs Note The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value. such as mysql_fetch_array. Examples Example 2.39. If no such link is found. it will try to create one as if mysql_connect was called with no arguments. See Also mysql_query mysql_info 2. Relying on this function is highly discouraged. Alternatives to this function include: SQL Query: SHOW DATABASES Description resource mysql_list_dbs( resource link_identifier = =NULL). and is not reset between queries. See also MySQL: choosing an API guide and related FAQ for more information. If the link identifier is not specified.0.4. If no connection is found or established.

the MySQLi or PDO_MySQL extension should be used. Alternatives to this function include: SQL Query: SHOW COLUMNS FROM sometable Description resource mysql_list_fields( string database_name. 'mysql_password'). See also MySQL: choosing an API guide and related FAQ for more information. while ($row = mysql_fetch_object($db_list)) { echo $row->Database . $db_list = mysql_list_dbs($link). Instead. "\n".4. } ?> The above example will output something similar to: database1 database2 database3 Notes Note For backward compatibility. 'mysql_password').33. and will be removed in the future. "\n". resource link_identifier = =NULL). } // Deprecated as of PHP 5.0. 'mysql_user'. while ($row = mysql_fetch_assoc($res)) { echo $row['Database'] .4.5. [1] • mysql_list_fields List MySQL table fields Warning This extension is deprecated as of PHP 5. string table_name. $res = mysql_query("SHOW DATABASES"). the following deprecated alias may be used: mysql_listdbs See Also mysql_db_name mysql_select_db 2. mysql_list_fields Copyright 1997-2012 the PHP Documentation Group. 'mysql_user'.0 $link = mysql_connect('localhost'. 54 .mysql_list_fields <?php // Usage without mysql_list_dbs() $link = mysql_connect('localhost'.

40. exit. the last link opened by mysql_connect is assumed. If the link identifier is not specified.mysql_list_fields Retrieves information about the given table name. mysql_field_name and mysql_field_type. } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row). it will try to create one as if mysql_connect was called with no arguments. This function is deprecated. If no such link is found. The returned result can be used with mysql_field_flags. an E_WARNING level error is generated. } } ?> 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] => 55 . The name of the table that's being queried. mysql_error(). Alternate to deprecated mysql_list_fields <?php $result = mysql_query("SHOW COLUMNS FROM sometable"). If no connection is found or established. mysql_field_len. or FALSE on failure. Examples Example 2. Parameters database_name table_name link_identifier The name of the database that's being queried. The MySQL connection. if (!$result) { echo 'Could not run query: ' . Return Values A result pointer resource on success. It is preferable to use mysql_query to issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.

Retrieves the current MySQL server threads. If no connection is found or established. Examples Example 2. mysql_list_processes example 56 .mysql_list_processes [Extra] => ) Notes Note For backward compatibility. the following deprecated alias may be used: mysql_listfields See Also mysql_field_flags mysql_info 2. the last link opened by mysql_connect is assumed. [1] • mysql_list_processes List MySQL processes Warning This extension is deprecated as of PHP 5. Instead.0. it will try to create one as if mysql_connect was called with no arguments. If the link identifier is not specified.41. an E_WARNING level error is generated.34. mysql_list_processes Copyright 1997-2012 the PHP Documentation Group. the MySQLi or PDO_MySQL extension should be used.5.4. Parameters link_identifier The MySQL connection. If no such link is found. and will be removed in the future. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_thread_id Description resource mysql_list_processes( resource link_identifier = =NULL). Return Values A result pointer resource on success or FALSE on failure.

the last link opened by mysql_connect is assumed. $row["db"]. ?> 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 2. mysql_list_tables Copyright 1997-2012 the PHP Documentation Group. Retrieves a list of table names from a MySQL database. If the link identifier is not specified. 57 . $row["Host"].0. $row["Id"]. Parameters database link_identifier The name of the database The MySQL connection.mysql_list_tables <?php $link = mysql_connect('localhost'. It is preferable to use mysql_query to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. [1] • mysql_list_tables List tables in a MySQL database Warning This extension is deprecated as of PHP 5.35. $result = mysql_list_processes($link). 'mysql_user'. the MySQLi or PDO_MySQL extension should be used. Instead. $row["Command"]. } mysql_free_result($result). If no such link is found. Alternatives to this function include: SQL Query: SHOW TABLES FROM sometable Description resource mysql_list_tables( string database.4.5. and will be removed in the future. it will try to create one as if mysql_connect was called with no arguments. This function is deprecated. resource link_identifier = =NULL). $row["Time"]). See also MySQL: choosing an API guide and related FAQ for more information. 'mysql_password'). while ($row = mysql_fetch_assoc($result)){ printf("%s %s %s %s %s\n".

mysql_list_tables alternative example <?php $dbname = 'mysql_dbname'. } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}\n". ?> Description This function became deprecated. Return Values A result pointer resource on success or FALSE on failure.mysql_num_fields If no connection is found or established. the following deprecated alias may be used: mysql_listtables See Also mysql_list_dbs mysql_tablename 2. Notes Note For backward compatibility. such as mysql_fetch_array. 'mysql_password')) { echo 'Could not connect to mysql'. mysql_error(). exit. } mysql_free_result($result).7 Examples Example 2. or any function for result tables.4. Use the mysql_tablename function to traverse this result pointer. exit.36. Changelog Version 4. if (!mysql_connect('mysql_host'. could not list tables\n". echo 'MySQL Error: ' . if (!$result) { echo "DB Error. an E_WARNING level error is generated. $result = mysql_query($sql). [1] • mysql_num_fields Get number of fields in result 58 . mysql_num_fields Copyright 1997-2012 the PHP Documentation Group. } $sql = "SHOW TABLES FROM $dbname". 'mysql_user'.3.42.

See also MySQL: choosing an API guide and related FAQ for more information. Instead. } /* returns 2 because id. the following deprecated alias may be used: mysql_numfields See Also mysql_select_db mysql_query mysql_fetch_field mysql_num_rows 2.email FROM people WHERE id = '42'"). and will be removed in the future.4.0.37. ?> The result resource that is being evaluated.43. Examples Example 2.email === two fields */ echo mysql_num_fields($result). the MySQLi or PDO_MySQL extension should be used. Alternatives to this function include: mysqli_field_count PDOStatement::columnCount Description int mysql_num_fields( resource result). mysql_num_rows Copyright 1997-2012 the PHP Documentation Group. [1] 59 . exit. This result comes from a call to mysql_query.5. Parameters result Return Values Returns the number of fields in the result set resource on success or FALSE on failure. if (!$result) { echo 'Could not run query: ' . Notes Note For backward compatibility. A mysql_num_fields example <?php $result = mysql_query("SELECT id.mysql_num_rows Warning This extension is deprecated as of PHP 5. Retrieves the number of fields from a query. mysql_error().

mysql_num_rows • mysql_num_rows Get number of rows in result Warning This extension is deprecated as of PHP 5.0. the MySQLi or PDO_MySQL extension should be used. Alternatives to this function include: mysqli_stmt_num_rows PDOStatement::rowCount Description int mysql_num_rows( resource result). ?> Notes Note If you use mysql_unbuffered_query. $num_rows = mysql_num_rows($result).5. $link). To retrieve the number of rows affected by a INSERT. Note For backward compatibility. mysql_num_rows example <?php $link = mysql_connect("localhost".44. $result = mysql_query("SELECT * FROM table1". REPLACE or DELETE query. Parameters result The result resource that is being evaluated. This command is only valid for statements like SELECT or SHOW that return an actual result set. Return Values The number of rows in a result set on success or FALSE on failure. Instead. See also MySQL: choosing an API guide and related FAQ for more information. use mysql_affected_rows. the following deprecated alias may be used: mysql_numrows See Also 60 . Examples Example 2. mysql_num_rows will not return the correct value until all the rows in the result set have been retrieved. mysql_select_db("database". "mysql_user". echo "$num_rows Rows\n". UPDATE. and will be removed in the future. $link). This result comes from a call to mysql_query. "mysql_password"). Retrieves the number of rows from a result set.

If the PHP directive mysql. Parameters server The MySQL server.5. an identifier for it will be returned instead of opening a new connection.0. [1] • mysql_pconnect Open a persistent connection to a MySQL server Warning This extension is deprecated as of PHP 5. It can also include a port number. then the default value is 'localhost:3306' 61 .default_host is undefined (default). the function would first try to find a (persistent) link that's already open with the same host. mysql_pconnect acts very much like mysql_connect with two major differences.mysql_pconnect mysql_affected_rows mysql_connect mysql_data_seek mysql_select_db mysql_query 2. username and password. Establishes a persistent connection to a MySQL server. mysql_pconnect Copyright 1997-2012 the PHP Documentation Group. when connecting.4.default_user"). This type of link is therefore called 'persistent'. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.default_password").38. int client_flags = =0). First.default_host"). Instead. the connection to the SQL server will not be closed when the execution of the script ends. Alternatives to this function include: mysqli_connect with p: host prefix PDO::__construct with PDO::ATTR_PERSISTENT as a driver option Description resource mysql_pconnect( string server = =ini_get("mysql.g. See also MySQL: choosing an API guide and related FAQ for more information. the MySQLi or PDO_MySQL extension should be used. Instead. If one is found. string username = =ini_get("mysql. Second. the link will remain open for future use (mysql_close will not close links established by mysql_pconnect). and will be removed in the future. e. string password = =ini_get("mysql.

0 Notes Note Note.39. [1] • mysql_ping Ping a server connection or reconnect if there is no connection Warning This extension is deprecated as of PHP 5. that these kind of links only work if you are using a module version of PHP. The password.4. the MySQLi or PDO_MySQL extension should be used. Changelog Version 5. Default value is an empty password. Note You can suppress the error message on failure by prepending a @ to the function name. MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . See the Persistent Database Connections section for more information.mysql_ping username The username. and will be removed in the future.0 4.3. password client_flags Return Values Returns a MySQL persistent link identifier on success.5. or FALSE on failure. 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. 2. MYSQL_CLIENT_SSL . Instead.5. MYSQL_CLIENT_COMPRESS .0. See also MySQL: 62 . Added the client_flags parameter. See Also mysql_connect Persistent Database Connections Description This function will generate an E_DEPRECATED error. Default value is the name of the user that owns the server process. mysql_ping Copyright 1997-2012 the PHP Documentation Group.

'. exit. } /* Make sure the connection is still alive. Parameters link_identifier The MySQL connection. exit. If no such link is found. try to reconnect */ if (!mysql_ping($conn)) { echo 'Lost connection. A mysql_ping example <?php set_time_limit(0). ?> See Also mysql_thread_id mysql_list_processes 63 . exiting. /* Assuming this query will take a long time */ $result = mysql_query($sql).3. If it has gone down.mysql_ping choosing an API guide and related FAQ for more information. $conn = mysql_connect('localhost'. otherwise FALSE . Checks whether or not the connection to the server is working. 'mysqluser'. 'mypass'). let's run another query */ $result2 = mysql_query($sql2).45. Return Values Returns TRUE if the connection to the server MySQL server is working. Note Automatic reconnection is disabled by default in versions of MySQL >= 5. the last link opened by mysql_connect is assumed. Alternatives to this function include: mysqli_ping Description bool mysql_ping( resource link_identifier = =NULL). it will try to create one as if mysql_connect was called with no arguments. } mysql_free_result($result). an automatic reconnection is attempted. if (!$result) { echo 'Query #1 failed. an E_WARNING level error is generated. Examples Example 2. if not. This function can be used by scripts that remain idle for a long while. $db = mysql_select_db('mydb').0. If no connection is found or established. exiting after query #1'. /* So the connection is still alive. If the link identifier is not specified. to check whether or not the server has closed the connection and reconnect if necessary.

64 . 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. Data inside the query should be properly escaped. or UPDATE statement. The returned result resource should be passed to mysql_fetch_array. SHOW. and other functions for dealing with result tables.40. DELETE. [1] • mysql_query Send a MySQL query Warning This extension is deprecated as of PHP 5. DESCRIBE. Parameters query An SQL query The query string should not end with a semicolon. 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. INSERT. If the link identifier is not specified.mysql_query 2. mysql_query returns TRUE on success or FALSE on error. INSERT. etc.4. mysql_query returns a resource on success. and will be removed in the future. the last link opened by mysql_connect is assumed. EXPLAIN and other statements returning resultset. Instead. it will try to create one as if mysql_connect was called with no arguments. an E_WARNING level error is generated.5. link_identifier The MySQL connection. If no connection is found or established. If no such link is found.0. Alternatives to this function include: mysqli_query PDO::query Description resource mysql_query( string query. REPLACE. UPDATE. DROP. mysql_query will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. See also MySQL: choosing an API guide and related FAQ for more information. Return Values For SELECT. to access the returned data. mysql_query Copyright 1997-2012 the PHP Documentation Group. For other type of SQL statements. resource link_identifier = =NULL). the MySQLi or PDO_MySQL extension should be used. or FALSE on error.

?> See Also mysql_connect mysql_error mysql_real_escape_string mysql_result mysql_fetch_assoc 65 . while ($row = mysql_fetch_assoc($result)) { echo $row['firstname'].= 'Whole query: ' . "\n". Valid Query The following query is valid. echo $row['lastname']. // Perform Query $result = mysql_query($query). for example $firstname = 'fred'. } ?> Example 2. // Check result // This shows the actual query sent to MySQL. Invalid Query The following query is syntactically invalid.47. die($message). $query. etc. and the error. mysql_fetch_array(). echo $row['age']. <?php // This could be supplied by a user.mysql_query Examples Example 2. mysql_real_escape_string($lastname)). mysql_error()). so mysql_query returns a resource. if (!$result) { die('Invalid query: ' .46. } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result). $message . <?php $result = mysql_query('SELECT * WHERE 1=1'). } // 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(). Useful for debugging. lastname. if (!$result) { $message = 'Invalid query: ' . age FROM friends WHERE firstname='%s' AND lastname='%s'". mysql_real_escape_string($firstname). see mysql_real_escape_string() $query = sprintf("SELECT firstname. address. so mysql_query fails and returns FALSE . mysql_error() . $lastname = 'fox'. echo $row['address']. // Formulate Query // This is the best way to perform an SQL query // For more examples. mysql_fetch_row().

resource link_identifier = =NULL). See also MySQL: choosing an API guide and related FAQ for more information.mysql_real_escape_string mysql_unbuffered_query 2. \n. or FALSE on error. '. an E_WARNING level error is generated.0. Security: the default character set The character set must be set either at the server level. which prepends backslashes to the following characters: \x00. Escapes special characters in the unescaped_string.5. Return Values Returns the escaped string. mysql_real_escape_string calls MySQL's library function mysql_real_escape_string. Instead. Alternatives to this function include: mysqli_real_escape_string PDO::quote Description string mysql_real_escape_string( string unescaped_string. it will try to create one as if mysql_connect was called with no arguments. taking into account the current character set of the connection so that it is safe to place it in a mysql_query. or with the API function mysql_set_charset for it to affect mysql_real_escape_string. the MySQLi or PDO_MySQL extension should be used.4. Parameters unescaped_string link_identifier The string that is to be escaped. If no connection is found or established. \. mysql_real_escape_string Copyright 1997-2012 the PHP Documentation Group. the last link opened by mysql_connect is assumed. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. and will be removed in the future. If no such link is found.41. If the link identifier is not specified. Examples 66 . The MySQL connection. this function must be used. \r. See the concepts section on character sets for more information. [1] • mysql_real_escape_string Escapes special characters in a string for use in an SQL statement Warning This extension is deprecated as of PHP 5. " and \x1a. If binary data is to be inserted.

'mysql_password') OR die(mysql_error()). // Query $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'". These are wildcards in MySQL if combined with LIKE. // This means the query sent to MySQL would be: echo $query. mysql_real_escape_string($password)). the last MySQL connection is used. ?> Example 2.48. 'mysql_user'. GRANT. first apply stripslashes to the data. mysql_real_escape_string($user). An example SQL Injection Attack <?php // We didn't check $_POST['password']. it could be anything the user wanted! For example: $_POST['username'] = 'aidan'. Note If magic_quotes_gpc is enabled. Using this function on data which has already been escaped will escape the data twice. or REVOKE. mysql_query($query). $_POST['password'] = "' OR ''='". and FALSE is returned. Notes Note A MySQL connection is required before using mysql_real_escape_string otherwise an error of level E_WARNING is generated.mysql_real_escape_string Example 2. 67 . Note mysql_real_escape_string does not escape % and _. Note If this function is not used to escape data. ?> The query sent to MySQL: SELECT * FROM users WHERE user='aidan' AND password='' OR ''='' This would allow anyone to log in without a valid password. the query is vulnerable to SQL Injection Attacks. Simple mysql_real_escape_string example <?php // Connect $link = mysql_connect('mysql_host'. // Query database to check if there are any matching users $query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'". If link_identifier isn't defined.49.

. they're MUCH quicker than mysql_result. The name or offset of the field being retrieved.4. Instead. the field's name. note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.'). and will be removed in the future. Row numbers start at 0.fieldname). As these functions return the contents of multiple cells in one function call.mysql_result See Also mysql_set_charset mysql_client_encoding addslashes stripslashes The magic_quotes_gpc directive The magic_quotes_runtime directive 2. Parameters result The result resource that is being evaluated. Alternatives to this function include: mysqli_data_seek in conjunction with mysqli_field_seek and mysqli_fetch_field PDOStatement::fetchColumn Description string mysql_result( resource result.5.42. When working on large result sets. Retrieves the contents of one cell from a MySQL result set. mixed field = =0). the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. use the alias instead of the column name. If the column name has been aliased ('select foo as bar from. or the field's table dot field name (tablename. mysql_result Copyright 1997-2012 the PHP Documentation Group. This result comes from a call to mysql_query. The row number from the result that's being retrieved. If undefined. It can be the field's offset. you should consider using one of the functions that fetch an entire row (specified below).0. 68 row field . the first field is retrieved.. Also. int row. [1] • mysql_result Get result data Warning This extension is deprecated as of PHP 5.fieldname argument.

employee').4. the MySQLi or PDO_MySQL extension should be used. or FALSE on failure. } $result = mysql_query('SELECT name FROM work. Instead.5.43. Alternatives to this function include: mysqli_select_db PDO::__construct (part of dsn) Description 69 . mysql_error()). mysql_error()).0. See also MySQL: choosing an API guide and related FAQ for more information. 'mysql_user'. Examples Example 2. mysql_error()). mysql_select_db Copyright 1997-2012 the PHP Documentation Group. if (!$result) { die('Could not query:' .50. 2). 'mysql_password'). } if (!mysql_select_db('database_name')) { die('Could not select database: ' . } echo mysql_result($result. [1] • mysql_select_db Select a MySQL database Warning This extension is deprecated as of PHP 5.mysql_select_db Return Values The contents of one cell from a MySQL result set on success. if (!$link) { die('Could not connect: ' . and will be removed in the future. // outputs third employee's name mysql_close($link). ?> Notes Note Calls to mysql_result should not be mixed with calls to other functions that deal with the result set. mysql_result example <?php $link = mysql_connect('localhost'. See Also mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object 2.

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

an E_WARNING level error is generated.4.7 or later. See also MySQL: choosing an API guide and related FAQ for more information. See the MySQL character set concepts section for more information. Alternatives to this function include: mysqli_character_set_name PDO: Add charset to the connection string. the MySQLi or PDO_MySQL extension should be used. resource link_identifier = =NULL).45. Sets the default character set for the current connection. If the link identifier is not specified. Parameters charset link_identifier A valid character set name.mysql_stat Sets the client character set Warning This extension is deprecated as of PHP 5. Notes Note This function requires MySQL 5. If no connection is found or established. mysql_stat Copyright 1997-2012 the PHP Documentation Group.0. and will be removed in the future. [1] • mysql_stat 71 . it will try to create one as if mysql_connect was called with no arguments. such as charset=utf8 Description bool mysql_set_charset( string charset. the last link opened by mysql_connect is assumed. If no such link is found. Note This is the preferred way to change the charset.5. Instead. The MySQL connection. Return Values Returns TRUE on success or FALSE on failure.0. Using mysql_query to set it (such as SET NAMES utf8) is not recommended. See Also mysql_client_encoding Setting character sets in MySQL List of character sets that MySQL supports 2.

If link_identifier is invalid. print_r($status). See also MySQL: choosing an API guide and related FAQ for more information. and will be removed in the future. Return Values Returns a string with the status for uptime. If no connection is found or established. For a complete list of other status variables. open tables. Alternatives to this function include: mysqli_stat PDO::getAttribute(PDO::ATTR_SERVER_INFO) Description string mysql_stat( resource link_identifier = =NULL). queries. Examples Example 2. ?> 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.0. NULL is returned.52. you have to use the SHOW STATUS SQL command.595 72 . threads. 'mysql_user'. Parameters link_identifier The MySQL connection. If the link identifier is not specified.5.mysql_stat Get current system status Warning This extension is deprecated as of PHP 5. mysql_stat($link)). $status = explode(' '. the last link opened by mysql_connect is assumed. mysql_stat returns the current server status. Instead. If no such link is found. the MySQLi or PDO_MySQL extension should be used. an E_WARNING level error is generated. flush tables and queries per second. mysql_stat example <?php $link = mysql_connect('localhost'. 'mysql_password'). it will try to create one as if mysql_connect was called with no arguments.

' = ' . } ?> 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/ . Alternatives to this function include: SQL Query: SHOW TABLES Description string mysql_tablename( resource result.5. [1] • mysql_tablename Get table name of field Warning This extension is deprecated as of PHP 5.53. the MySQLi or PDO_MySQL extension should be used.mysql_tablename ) Example 2. "\n". 'mysql_password').4. int i).. and will be removed in the future. $result = mysql_query('SHOW STATUS'. $link). mysql_tablename Copyright 1997-2012 the PHP Documentation Group.. 73 .0.46. $row['Value'] . See Also mysql_get_server_info mysql_list_processes 2. Instead. Retrieves the table name from a result. 'mysql_user'. See also MySQL: choosing an API guide and related FAQ for more information. while ($row = mysql_fetch_assoc($result)) { echo $row['Variable_name'] . Alternative mysql_stat example <?php $link = mysql_connect('localhost'.

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

See also MySQL: choosing an API guide and related FAQ for more information. If the connection is lost. the thread ID will change.48.0. $thread_id = mysql_thread_id($link). If the link identifier is not specified. $thread_id).mysql_unbuffered_query Warning This extension is deprecated as of PHP 5. 'mysql_password'). mysql_thread_id example <?php $link = mysql_connect('localhost'. This means only retrieve the thread ID when needed. the last link opened by mysql_connect is assumed. Parameters link_identifier The MySQL connection. and a reconnect with mysql_ping is executed.55.5. if ($thread_id){ printf("current thread id is %d\n". If no connection is found or established. [1] 75 . Retrieves the current thread ID. the MySQLi or PDO_MySQL extension should be used. Examples Example 2. Alternatives to this function include: mysqli_thread_id Description int mysql_thread_id( resource link_identifier = =NULL). If no such link is found. and will be removed in the future. it will try to create one as if mysql_connect was called with no arguments. } ?> The above example will output something similar to: current thread id is 73 See Also mysql_ping mysql_list_processes 2. Return Values The thread ID on success or FALSE on failure. mysql_unbuffered_query Copyright 1997-2012 the PHP Documentation Group. Instead.4. an E_WARNING level error is generated. 'mysql_user'.

DROP. mysql_unbuffered_query returns a resource on success. until all rows are fetched. If the link identifier is not specified. mysql_unbuffered_query sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query does. This saves a considerable amount of memory with SQL queries that produce large result sets. link_identifier The MySQL connection. Data inside the query should be properly escaped. If no such link is found. Parameters query The SQL query to execute. Warning This extension is deprecated as of PHP 5. Alternatives to this function include: See: Buffered and Unbuffered queries Description resource mysql_unbuffered_query( string query. See Also 76 . If no connection is found or established.5. DESCRIBE or EXPLAIN statements. SHOW. resource link_identifier = =NULL).0. the MySQLi or PDO_MySQL extension should be used. UPDATE. the last link opened by mysql_connect is assumed. or FALSE on error. and will be removed in the future. an E_WARNING level error is generated. For other type of SQL statements. 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.mysql_unbuffered_query • mysql_unbuffered_query Send an SQL query to MySQL without fetching and buffering the result rows. DELETE. etc. See also MySQL: choosing an API guide and related FAQ for more information. Return Values For SELECT. using the same link_identifier. mysql_unbuffered_query returns TRUE on success or FALSE on error. Instead. it will try to create one as if mysql_connect was called with no arguments. 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. you must specify the optional parameter link_identifier to identify which connection you want to use. 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.

Changelog mysql_query 2. Changelog Copyright 1997-2012 the PHP Documentation Group. mysql_fieldtable(). mysql_db_name(). mysql_listfields(). mysql_freeresult().5. mysql_fieldlen(). mysql_fieldflags().5. Connecting to a MySQL database via mysql_connect.0 Description This extension has been deprecated. mysql_fieldtype(). and mysql_table_name(). All of the old deprecated functions and aliases now emit E_DEPRECATED errors. [1] The following changes have been made to classes/functions/methods of this extension. 5.5. mysql_tablename(). mysql_listtables(). mysql_fieldname(). mysql_createdb(). mysql_numrows().0 77 . General Changelog for the ext/mysql extension This changelog references the ext/mysql extension. Version 5. mysql_listdbs(). Global ext/mysql changes The following is a list of changes to the entire ext/mysql extension. mysql_dropdb(). mysql_dbname(). mysql_pconnect or an implicit connection via any other mysql_* function will generate an E_DEPRECATED error. Changes to existing functions The following list is a compilation of changelog entries from the ext/mysql functions. These functions are: mysql(). mysql_numfields(). mysql_selectdb().

78 .

82 3.............9..............................1......................3..........................2.............. 129 3...................... Multiple Statements .....20...................... mysqli_get_connection_stats .................... 116 3........................................4.......................... mysqli_error_list ......1............. mysqli_get_client_version ........................ 162 3...............................9.....................................9.......9..............................8........................................3............. 93 3............................ 135 3........................................9............... 163 79 ......23..... 143 3.. 158 3................... mysqli_get_server_info ........................................ 111 3.................................................... mysqli_get_client_info ....9.....................10..............6........... 145 3..................... mysqli::debug.....3.......... 147 3....................4...... 90 3.......... mysqli::get_connection_stats........... 111 3.....................2............... mysqli::dump_debug_info.................. mysqli::autocommit. mysqli::__construct......................... mysqli_affected_rows ... mysqli_character_set_name .............................................. mysqli::$host_info.................... mysqli_get_proto_info ...................1...........9............. API support for transactions ......27..................................9.........2... MySQL Improved Extension (Mysqli) Table of Contents 3............4................. 125 3................... mysqli::$client_info..............5.......3.....2............... mysqli_connect_errno .................. mysqli_connect_error .......... mysqli_error ......................... mysqli_get_charset ..3... 105 3.............. 148 3.... mysqli::$errno... The MySQLi Extension Function Summary ........... mysqli_field_count ............... 108 3......5............................. mysqli::$connect_errno..... mysqli_commit ............................ Notes ................8........................ mysqli_close ............. 151 3..... mysqli::$protocol_version..9...........................................9... mysqli::get_charset.............3.................................. The mysqli class (mysqli) ... 155 3...7..............6................. 99 3......................... mysqli_debug ..... mysqli::character_set_name................................................................ 108 3..18..................................................13.9............Chapter 3.......................9.........3....15................... Connections ...... mysqli::get_warnings........................4....... The mysqli Extension and Persistent Connections ........................................................................................6............................ 159 3.......................... mysqli::$affected_rows..........12........................19.9............. Installing/Configuring ...9......... 144 3........ mysqli_get_warnings ....3................ Runtime Configuration ......... mysqli_change_user .....................7............................ Prepared Statements . 137 3.. 139 3............. 115 3.......4....... Requirements .................. Examples ...... 131 3............................................................................................. mysqli_errno ......................9...9........................8........... Installation ......................................9.....4......................................................................... 82 3............. Executing statements ....21..... Resource Types ........................... mysqli_autocommit .............................. mysqli::$server_version. mysqli::$error.....................9....... mysqli_get_client_version...................................................................................... mysqli_get_client_info ... Quick start guide ..14......................................................................... mysqli::$server_info............................................................3....................17........................... 103 3..........................................................................................24.....................9....................... mysqli::commit....... 86 3.........9..................... mysqli::$connect_error......... 134 3..9....... 134 3............ 86 3................. 106 3.........9..... mysqli_dump_debug_info ................................................... 127 3.................. mysqli::close.. 88 3............................. 161 3..... mysqli_get_server_version .................. mysqli::get_client_info................................................26............................................16.. 122 3....9........................... mysqli::$error_list........ mysqli::change_user............................... Dual procedural and object-oriented interface ..........4....... Predefined Constants ....... 108 3.................7.......3....3....................................5.......11........................ 112 3......... 133 3............... Overview ............ 155 3....................................... mysqli::$client_version......................................1......9....9........... mysqli::$client_version .................. mysqli::$field_count....9.............................. 142 3.... 138 3................ 110 3... mysqli_get_client_stats .................................. Metadata ................ Stored Procedures . mysqli_connect .....3. 150 3.................................................................4............9............... 152 3..........9........................................25.......22...........................9........ mysqli_get_host_info .......

..................10................... 180 3..................39.....................9......60... mysqli::real_query.................. mysqli_stmt::attr_set..... mysqli_stmt_close ...........................12................. mysqli_stmt_attr_set .........28.................. mysqli::$sqlstate........................................ mysqli_warning_count . mysqli_stmt::$field_count........ mysqli_prepare .......9.........10.................9...... 166 3......... 189 3..................9............................... 207 3.......47. 209 3........................... mysqli_stmt::get_result... mysqli::stmt_init......... mysqli_select_db ........................57.. mysqli_stmt::$error_list................49...... 193 3........9... mysqli::more_results...... mysqli_stmt::next_result....... mysqli_stmt_get_warnings ...10. 178 3......10...........58......9.. 195 3.................10................... 186 3.. 214 3.54................9........................7......... mysqli::refresh..9....10........10..............................4....... mysqli_stmt_fetch ........................... mysqli_info ....18..... 216 3..........................................13..10..............9..9. 205 3............................ mysqli::ping..... 238 80 .. mysqli_stmt_num_rows .. 200 3...19................ mysqli_stmt::free_result....9...9...10..9................. 190 3................................... 237 3..... 223 3....29...... mysqli::rpl_query_type....................... mysqli_poll ........ mysqli_ping ..3.. 168 3. mysqli_stmt::$num_rows........... 172 3...5..........51............ mysqli_stmt::data_seek.. mysqli_stmt_next_result ....8.43.... mysqli_stmt_init .........2.....10........ mysqli::use_result..... mysqli_stmt::bind_result..........................10.. 201 3..........42.. mysqli_stmt_errno ................ mysqli_stmt::$error.......................... mysqli::$insert_id.......37.................................55.......................59.. mysqli_insert_id .56...... 204 3...............9...36.................................17....................................9............... mysqli_stmt_attr_get .................38........................ 211 3........... 164 3... 183 3..... mysqli_stmt_bind_result .........................45.................... mysqli_stmt::more_results.. 233 3....... mysqli_next_result .....................9.......... 192 3...............10.............. mysqli_store_result ..... mysqli_real_query ........ mysqli_reap_async_query ...................................... 231 3.................. 237 3. mysqli_sqlstate ............................ mysqli::kill.......................9.............50............. mysqli_query ............................. mysqli_multi_query ..........14...........10... mysqli_stmt_free_result .............................. mysqli::real_connect..9..................................52............................. 219 3... 227 3.... 225 3... mysqli::$info.... mysqli_stmt_field_count ........ mysqli_real_escape_string ........ mysqli_stmt_execute .... mysqli::ssl_set....20............................................... mysqli_stmt::bind_param................. mysqli::poll..........3.................. mysqli::query..........30................ 170 3....................... mysqli_thread_safe ........................6....... mysqli_init ..... 221 3.. 204 3... mysqli::rollback.. 207 3..... mysqli::set_local_infile_default................... mysqli_stmt::$errno.....44.......................................9. mysqli::reap_async_query.................. 175 3.... mysqli::set_local_infile_handler....... mysqli::store_result.. The mysqli_stmt class (mysqli_stmt) . mysqli::thread_safe...... mysqli_stmt::$affected_rows........ mysqli_stmt::fetch.......................48............. mysqli::$thread_id. mysqli_send_query .9..................................................... 234 3.......35...9... mysqli_stmt::close...11. 190 3.............9............................................................ mysqli_rollback ..... mysqli_stmt_affected_rows ............ 228 3......... mysqli_stmt::$insert_id..............9......... 195 3........ mysqli_set_local_infile_handler ...... mysqli_ssl_set ........ 221 3.......16................................................. mysqli_stat ....... mysqli_stmt_data_seek .. 236 3...................40..... mysqli_more_results ......10........................................... mysqli_stmt_error .. mysqli_kill ...................10.......................... mysqli::real_escape_string......................10..... mysqli::send_query...... mysqli_set_charset ... mysqli_set_local_infile_default ...31.... mysqli::options.............. mysqli_options ....... mysqli::select_db.................. mysqli::set_charset.9... mysqli_stmt_get_result .............9...........32................... 169 3. mysqli_stmt::get_warnings.......... mysqli_rpl_query_type ..... 215 3.. 233 3... 166 3.... mysqli_real_connect ........10...... mysqli_stmt_bind_param ................. 202 3............... 197 3....... mysqli_thread_id ........ mysqli_stmt_error_list ...10.................9......................... mysqli::init.....9.................................10............................... mysqli::prepare.....9.... mysqli_refresh .........10.. 173 3. 198 3..................9.46.....1..9...........10.......................9.... mysqli::multi_query.................9. mysqli_use_result ....... 176 3........ mysqli_stmt::attr_get...41............ mysqli_stmt::execute...........10.. 188 3........15..........53.. mysqli::next_result. mysqli::$warning_count.34.... mysqli::stat............ 236 3.........................9....... mysqli_stmt_more_results ...............................9......... 212 3............33........ mysqli_stmt_insert_id .........

.............11.. mysqli_fetch_assoc ................15.........................1....14......15...... 252 3....... mysqli_stmt::store_result..................11............. mysqli_result::fetch_assoc..........10......................................3.............8......... mysqli_embedded_server_end ...15........................... 283 3............ mysqli_stmt_prepare ...................................... mysqli_fetch_fields ....................11........... mysqli_report .4.12.....15.......15...26...... mysqli_bind_param ... 247 3..........15... 284 3.....21....................... 282 3.....................1..19.........10......................15........................... mysqli_result::fetch_field................. mysqli_fetch_lengths .. 293 3............ 282 3....................................... mysqli_result::data_seek.................... mysqli_data_seek .... mysqli_stmt_sqlstate ................................................ mysqli_stmt::prepare................3............................................................................ 285 3......... 285 3.................................................. 281 3............ mysqli_num_fields ...............11.......................11........................... mysqli_result::field_seek............................................................................... mysqli_result::$field_count... 270 3.................15..12............ mysqli_disable_rpl_parse ................... mysqli_result::fetch_row........ mysqli_slave_query ................15.................... mysqli_field_seek ....... 290 3..............................11. mysqli_fetch_object ..15........5.... 268 3...................... mysqli_master_query ......21........ mysqli_result::fetch_array.............. The mysqli_result class (mysqli_result) ....................................... 278 3..................6..... mysqli_driver::embedded_server_start..... mysqli_stmt::result_metadata............................................. 240 3..15...........10..........................15.... mysqli_get_cache_stats ........... mysqli_result::$num_rows....... 281 3....10.....11........ mysqli_field_tell ..................................... 287 3..13............. 279 3............ mysqli_free_result .. mysqli_connect .......................... mysqli_stmt::$param_count. 272 3............15...15....15..............11.........11....................22....11..........2.............................13.........3......................... 284 3............. 249 3....................................14........................ 251 3......12...7.............. mysqli_driver::embedded_server_end..15............ mysqli_warning::__construct ......................................1........ 275 3........... 254 3............. 256 3. mysqli_result::fetch_object........................................ 290 3......... mysqli_stmt_reset .........................10....................................1......... mysqli_num_rows ..... mysqli::disable_reads_from_master................... 280 3..............................14....15................................................7................. 244 3........................15.. 290 3................. 259 3...............................12.......... mysqli_disable_reads_from_master .............. 293 81 .. mysqli_get_metadata ...................10................... mysqli_enable_reads_from_master ......................5............. mysqli_execute .. 246 3.......................... 286 3.....2............ 287 3.............. mysqli_stmt_result_metadata .......... 283 3............................................... mysqli_stmt_param_count . 292 3.............................13.............. mysqli_result::$lengths................................ mysqli_embedded_server_start ....................... mysqli_result::fetch_fields...............................10.......23.............25..20............................... 284 3.......... mysqli_fetch_array ...... 266 3........ mysqli_enable_rpl_parse .............. 257 3....... The mysqli_sql_exception class (mysqli_sql_exception) ........... mysqli_fetch ........... mysqli_fetch_field_direct ....24....... mysqli_warning::next ..................... mysqli_send_long_data ................................... 262 3.......... mysqli_param_count ........................ 244 3................13............11.... mysqli_result::fetch_all........13...... mysqli_stmt_send_long_data .......15................................. Aliases and deprecated Mysqli Functions ................ 286 3.. 273 3......27..................... 276 3......................................... 283 3...........8................. The mysqli_driver class (mysqli_driver) ....................15...........17. mysqli_stmt_store_result ..... 293 3.........4... 292 3........................6...... 291 3.................................. 241 3....... mysqli_client_encoding ..... mysqli_stmt::reset.....11.....................................................................11..................................... mysqli_stmt::send_long_data.....................................9...............11............... mysqli_result::$current_field....2.12....................9................................. mysqli_result::fetch_field_direct.....18............. mysqli_stmt::$sqlstate.... The mysqli_warning class (mysqli_warning) ................................16................... 284 3. mysqli_rpl_probe .......11........................................... mysqli_fetch_field ........................................... mysqli_escape_string ................2.............15......15.......... mysqli_fetch_row .........10............................................... 264 3.10....................... mysqli_set_opt ................11..... mysqli_rpl_parse_enabled .15............................11............... mysqli_fetch_all ......................11......... mysqli_bind_result ......................15........... 286 3. mysqli_result::free......................

.... [1] This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database. and also handle the communication between your application and the database server..... Parts of this documentation included from MySQL manual with permissions of Oracle Corporation.. Software is required to provide the API that your PHP application will use...... More information about the MySQL Database server can be found at http://www.........mysql.. The world database can be found at http://downloads. methods. as it is more modern and leads to better organised code..mysql.... Changelog ..... querying the database and other databaserelated functions..com/doc/..... When writing PHP applications that need to connect to the MySQL server there are several API options available.com/docs/world......... In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions........mysql.. including PHP...1 and above.1.. as it allows your application to connect to a database server. With a procedural API you call functions to carry out tasks... 293 Copyright 1997-2012 the PHP Documentation Group..Examples 3. MySQL provides connectors for a variety of languages... 3. Of the two the latter is usually the preferred interface.2...... APIs can be procedural or object-oriented... [1] All examples in the mysqli documentation use the world database.. What is a Connector? In the MySQL documentation.... [1] The mysqli extension allows you to access the functionality provided by MySQL 4...com/ An overview of software available for using MySQL from PHP can be found at Section 3......16.........2. possibly using other intermediate libraries where necessary.. 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. with the object-oriented API you instantiate classes and then call methods on the resulting objects. the term connector refers to a piece of software that allows your application to connect to the MySQL database server. Overview Copyright 1997-2012 the PHP Documentation Group...... This document discusses what is available and how to select the best solution for your application..........sql.. What is a Driver? 82 .....gz 3. or API.. functions and variables that your application will need to call in order to carry out its desired task.... defines the classes....... What is an API? An Application Programming Interface... This software is known generically as a connector...... “Overview” Documentation for MySQL can be found at http://dev. Examples Copyright 1997-2012 the PHP Documentation Group..

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. 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. PHP's MySQL-related extensions. Sometimes people use the terms connector and driver interchangeably. does not expose an API to the PHP programmer. The PDO MySQL driver extension.3. to allow its facilities to be used programmatically. The driver may also call a library. MySQL Extension (mysql). some extensions which use the PHP extension framework do not expose an API to the PHP programmer. An extension typically exposes an API to the PHP programmer. The terms API and extension should not be taken to mean the same thing. However.Overview A driver is a piece of software designed to communicate with a specific type of database server. this can be confusing.extension. One of the drivers it has available is the PDO MYSQL driver. The PHP code consists of a core. with optional extensions to the core functionality. and the mysql extension. What is PHP's mysqli Extension? 83 . which allows it to interface with the MySQL server. By way of an example.3 or newer.3 or later it is strongly recommended that you use the mysqli extension instead. for example. such as the MySQL Client Library or the MySQL Native Driver.1. This extension can be used with versions of MySQL 4. such as the mysqli extension. but not all of the latest MySQL server features will be available. are implemented using the PHP extension framework.1. The mysql extension source code is located in the PHP extension directory ext/mysql.1. What is an Extension? In the PHP documentation you will come across another term . the PHP Data Objects (PDO) [84] database abstraction layer may use one of several database-specific drivers. but provides an interface to the PDO layer above it. as an extension may not necessarily expose an API to the programmer. Note If you are using MySQL versions 4. see Chapter 2. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4. The following discussion aims to give a brief introduction to the key aspects of each API. For further information on the mysql extension. These libraries implement the low-level protocol used to communicate with the MySQL database server. In the MySQL-related documentation the term “driver” is reserved for software that provides the database-specific part of a connector package.

is a database abstraction layer specifically for PHP applications. 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. or as it is sometimes known. such as a clean. Other PDO drivers available include those for the Firebird and PostgreSQL database servers. at least from the PHP programmer's perspective. PDO is implemented using the PHP extension framework. What is PDO? PHP Data Objects.1. In theory. you could switch the database server you used. The mysqli extension is built using the PHP extension framework. Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl. For example.php. What is the PDO MYSQL driver? The PDO MYSQL driver is not an API as such. MySQL Improved Extension (Mysqli).3 or later it is strongly recommended that you use this extension. its source code is located in the directory ext/mysqli. The PDO MYSQL driver is implemented using the PHP extension framework. It does not expose an API to the PHP programmer. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. simple. PDO does not allow you to use MySQL's support for Multiple Statements.3 and newer. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. portable API. For further information on PDO. The programmer still calls the PDO API. from say Firebird to MySQL. 84 .1. While PDO has its advantages. see Chapter 3. the MySQL improved extension. if you are using the PDO API. Its source code is located in the directory ext/pdo_mysql.Overview The mysqli extension. For further information on the mysqli extension. its source code is located in the directory ext/ pdo. but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.net/book. The PDO MYSQL driver is one of several available PDO drivers. see the http://www.pdo. was developed to take advantage of new features found in MySQL systems versions 4. and only need to make minor changes to your PHP code. The mysqli extension has a number of benefits. As well as the object-oriented interface the extension also provides a procedural interface. 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 If you are using MySQL versions 4. or PDO. The mysqli extension is included with PHP versions 5 and later.

It does not expose an API to the PHP programmer. mysqli and the PDO MYSQL driver each use a low-level library that implements the required protocol. MySQL Functions (PDO_MYSQL) (MySQL (PDO)). otherwise known as libmysql. mysqlnd.1+ Yes functionality 85 . Note The MySQL Native Driver can only be used with MySQL server versions 4. Comparison of Features The following table compares the functionality of the three main methods of connecting to MySQL from PHP: Table 3. the only available library was the MySQL Client Library. The source code is located in ext/mysqlnd.x MySQL development status Recommended by MySQL for new projects API supports Charsets 5. the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd. see Chapter 5. The MySQL Native Driver is implemented using the PHP extension framework. You are strongly encouraged to take advantage of these improvements.1.Overview For further information on the PDO MYSQL driver. as libmysql was originally designed with C applications in mind.0 yes PHP's MySQL Extension Prior to 3.3 and later. the interface presented by libmysql was not optimized for communication with PHP applications. was developed as an alternative to libmysql for PHP applications. In the past.1. The mysql extension. What is PHP's MySQL Native Driver? In order to communicate with the MySQL database server the mysql extension.preferred option Yes 5.0 yes Active development Yes . Comparison of MySQL API options for PHP PHP's mysqli Extension PDO (Using PDO MySQL Driver and MySQL Native Driver) PHP version introduced Included with PHP 5.0 Yes Active development as of Maintenance only PHP 5. However. For this reason the MySQL Native Driver. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql.3 Yes Yes Yes Yes Yes Most Most No No No No No No No API supports server-side Yes Prepared Statements API supports client-side Prepared Statements API supports Stored Procedures API supports Multiple Statements No Yes Yes Supports all MySQL 4.

"database"). The object-oriented interface shows functions grouped by their purpose. Users migrating from the old mysql extension may prefer the procedural interface.1. This quick start gives an overview on the mysqli extension. making it easier to get started. Users can base their choice on personal preference. do not use ' AS _msg FROM DUAL"). In many cases. The documentation is organized using the object-oriented interface.3. "user". $res = mysqli_query($mysqli. users can choose to use the object-oriented interface. the SQL language. $row = mysqli_fetch_assoc($res). "password". It supports the procedural and object-oriented programming paradigm. echo $row['_msg'].Quick start guide 3. The procedural interface is similar to that of the old mysql extension. Example 3.3. $mysql = mysql_connect("localhost". [1] This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL. The object-oriented interface In addition to the classical procedural interface.com". ?> The above example will output: Please. Some mysqli functions take a connection handle as their first argument. Dual procedural and object-oriented interface Copyright 1997-2012 the PHP Documentation Group. and basic knowledge of the MySQL server. "").1. The reference section gives examples for both syntax variants. [1] The mysqli extension features a dual interface. echo $row['_msg']. "root". $mysql).' AS _msg FROM DUAL". Quick start guide Copyright 1997-2012 the PHP Documentation Group. 3. do not use the mysql extension for new developments. whereas matching functions in the old mysql interface take it as an optional last argument. $row = mysql_fetch_assoc($res). "SELECT 'Please. mysql_select_db("test"). Easy migration from the old mysql extension <?php $mysqli = mysqli_connect("example. There are no significant performance differences between the two interfaces. $res = mysql_query("SELECT 'the mysql extension for new developments. Required: A familiarity with the PHP programming language. 86 . Code examples are provided for all major aspects of the API. the function names differ only by prefix.

com". } $res = mysqli_query($mysqli. $mysqli->error. } if ($row = $res->fetch_assoc()) { echo $row['_msg']. "user". Mixing both styles is not recommended for code clarity and coding style reasons. mysqli_connect_error(). "SELECT 'A world full of ' AS _msg FROM DUAL"). "password". Bad coding style <?php $mysqli = new mysqli("example. } $res = $mysqli->query("SELECT 'choices to please everybody. ") " . echo $row['_msg']. "user".3.' AS _msg FROM DUAL").com".' AS _msg FROM DUAL").com". $mysqli->errno . "password". } ?> The above example will output: Possible but bad style. "database").2. $row = mysqli_fetch_assoc($res). The object oriented interface is used for the quickstart because the reference section is organized that way. See also mysqli::__construct 87 . $mysqli->connect_error. $row = $res->fetch_assoc(). $mysqli = new mysqli("example. "password". "SELECT 'Possible but bad style. if (mysqli_connect_errno($mysqli)) { echo "Failed to connect to MySQL: " . "database"). Example 3. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . "database"). Mixing styles It is possible to switch between styles at any time. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . } $res = mysqli_query($mysqli. if (!$res) { echo "Failed to run query: (" . $mysqli->connect_error.Dual procedural and object-oriented interface Example 3. ?> The above example will output: A world full of choices to please everybody. "user". Object-oriented and procedural interface <?php $mysqli = mysqli_connect("example. echo $row['_msg'].

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

If not given or empty. the host name . port and default database can not be found in the connection pool. Depending on the web server deployment model. the mysqli extension implicitly calls mysqli_change_user to reset the state. Persistent connection If a unused persistent connection for a given combination of host. authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. But also. and state reset before reuse. A persistent connection is not. the name persistent may be understood as a promise that the state is persisted. This may be seen as an unwanted side-effect. A common complain about persistent connections is that their state is not reset before reuse. which are a special kind of pooled connections. then the client library will default to a Unix socket connection on localhost. Connection options must be set before a network connection is established.max_persistent. socket.Connections Built-in connection library defaults If the host value is unset or empty. the connect operation has to be performed in three steps: creating a connection handle with mysqli_init. setting the requested options using mysqli_options. and establishing the network connection with mysqli_real_connect. then mysqli opens a new connection. set init commands which are executed upon connect.max_links. and a Unix socket connection is requested. The use of persistent connections can be enabled and disabled using the PHP directive mysqli. Instead it is put into a pool for later reuse.\pipe\MySQL.allow_persistent. password. Reuse saves connection overhead. The total number of connections opened by a script can be limited with mysqli. a PHP process may serve one or multiple requests.sock is attempted. that the web server may spawn many PHP processes. No artifacts from previous usages are visible. Please note. In this case the socket parameter is interpreted as the pipe name. username. If socket is unset or empty. Before a persistent connection is reused. is interpreted by the client library as an attempt to open a Windows named pipe based connection. or for requesting use of a certain charset. socket. port and default database is opened. then the socket (pipe name) defaults to \\. Connection options Connection options are available to. On the contrary. For setting a connection option. By default. a pooled connection may be used by one or more scripts subsequently. The persistent connection appears to the user as if it was just opened. If neither a Unix domain socket based not a Windows named pipe based connection is to be be established and the port parameter value is unset. Connection pooling The mysqli extension supports persistent database connections. 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. 89 . then a connection to the default socket on /tmp/mysql. For example. if a connection to the same server using the same username. The maximum number of persistent connections per PHP process can be restricted with mysqli. password. The mysqlnd library and the MySQL Client Library (libmysql) implement the same logic for determining defaults. the library will default to port 3306. On Windows systems. Therefore. Every PHP process is using its own mysqli connection pool. The default is reset. for example. The mysqli extension supports both interpretations of a persistent connection: state persisted. open and unfinished transactions are not automatically rolled back.

$mysqli->error. Example 3. $mysqli->errno . clients are slow consuming result sets. See also mysqli::__construct mysqli::init mysqli::options mysqli::real_connect mysqli::change_user $mysqli::host_info MySQLi Configuration Options Persistent Database Connections 3. Navigation through buffered results 90 . "user". Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. Navigation is fast because the result sets are held in client memory.com". [1] Statements can be executed with the mysqli_query. users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set. keep in mind that it is often easier to scale by client than it is to scale the server. Example 3. in one call. the safe behavior has been made the default at the expense of maximum performance. It is left to the user to choose between safe behavior and best performance.7. The mysqli_query function is the most common. it is recommended to use buffered result sets. Generally speaking. if any. Connecting to MySQL <?php $mysqli = new mysqli("example. } 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: (" . Therefore.3. mysqli_real_query and mysqli_multi_query functions. Calling mysqli_query is identical to calling mysqli_real_query followed by mysqli_store_result. } ?> 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->connect_error.Executing statements The mysqli_change_user function is an expensive operation. "password". "database").6. Please. Both are valid optimization goals. ") " . ") " . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . For best performance.3. For ease of use. Executing statements Copyright 1997-2012 the PHP Documentation Group. $mysqli->connect_errno . mysqli_query combines statement execution and result set buffering. PHP applications can navigate freely through buffered results. and combines the executing statement with a buffered fetch of its result set.

"user". 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. id = 3 id = 2 id = 1 Result set order. the command COM_QUERY and the text protocol are used for statement execution. echo "Result set order.. Navigation through unbuffered results <?php $mysqli->real_query("SELECT id FROM test ORDER BY id ASC"). } $res = $mysqli->query("SELECT id FROM test ORDER BY id ASC"). mysqli_real_query and mysqli_multi_query functions are used to execute non-prepared statements. $row_no >= 0. (3)")) { echo "Table creation failed: (" . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . With the text protocol. ") " .1. "password". $row['id'] . $row['id'] . $mysqli->error. } ?> The above example will output: Reverse order. for ($row_no = $res->num_rows . At the level of the MySQL Client Server Protocol...\n". $res->data_seek(0). echo "Reverse order. the MySQL server converts 91 . Scrolling through unbuffered results is not possible before all rows have been read..8.. $mysqli->connect_errno . "database"). $mysqli->connect_error. } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1). (2). "\n". unbuffered results can be used. ") " . while ($row = $res->fetch_assoc()) { echo " id = " . Example 3... while ($row = $res->fetch_assoc()) { echo " id = " . echo " id = " .\n". } ?> Result set values data types The mysqli_query. } echo "Result set order.. $res = $mysqli->use_result().com".. "\n".. $row = $res->fetch_assoc(). $mysqli->errno . $row['id'] . $row_no--) { $res->data_seek($row_no).Executing statements <?php $mysqli = new mysqli("example. "\n".\n".

printf("label = %s (%s)\n". Instead. SQL INT columns are returned as integers. If set.10. for example. $mysqli->error. printf("label = %s (%s)\n". ") " . $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE. 'a')")) { echo "Table creation failed: (" . printf("id = %s (%s)\n". "user". $mysqli->real_connect("example. if using the mysqlnd library. ") " . 'a')")) { echo "Table creation failed: (" . $row['id']. printf("id = %s (%s)\n". ") " . "database"). label) VALUES (1. $mysqli->connect_error. $row['label']. "password". $row = $res->fetch_assoc(). This conversion is done regardless of the SQL result set column data type.com". gettype($row['id'])). $mysqli->error. $mysqli->errno . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->errno .com". "password". } $res = $mysqli->query("SELECT id. } $res = $mysqli->query("SELECT id. if the PHP data type value range allows for it. 1). No further client-side casting is done to convert columns back to their native types. Example 3. $row['label']. Example 3. gettype($row['label'])). all values are provided as PHP strings. label FROM test WHERE id = 1"). gettype($row['label'])). $row['id']. ") " . The mysql client libraries receive all column values as strings. label FROM test WHERE id = 1").Executing statements all data of a result sets into strings before sending. $mysqli->connect_error. ?> 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. ?> The above example will output: 92 . } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. $mysqli->connect_errno . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . label) VALUES (1. gettype($row['id'])). } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT.9. "database"). $row = $res->fetch_assoc(). label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. This way. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. $mysqli->connect_errno . Text protocol returns strings by default <?php $mysqli = new mysqli("example. "user". Native data types with mysqlnd and connection option <?php $mysqli = mysqli_init(). the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers.

First stage: prepare <?php $mysqli = new mysqli("example. "database"). "password". } /* Prepared statement. $mysqli->errno . Second stage: bind and execute <?php 93 . Example 3. Prepared Statements Copyright 1997-2012 the PHP Documentation Group. ") " . [1] The MySQL database supports prepared statements. Basic workflow The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is send to the database server. The server performs a syntax check and initializes server internal resources for later use. $mysqli->error. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency. The MySQL server supports using anonymous. positional placeholder with ?. The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources. $mysqli->connect_errno .12.com". Example 3.3. stage 1: prepare */ if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) { echo "Prepare failed: (" . $mysqli->errno . $mysqli->error.11.4. ") " . $mysqli->connect_error. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . } ?> Prepare is followed by execute. } /* Non-prepared statement */ if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) { echo "Table creation failed: (" . ") " . During execute the client binds parameter values and sends them to the server. "user".Prepared Statements 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 3.

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

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

") " . $out_label. } if (!($stmt = $mysqli->prepare("SELECT id. Example 3. $mysqli->errno . printf("label = %s (%s)\n". } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. "user". $mysqli->error. ?> The above example will output: id = 1 (integer) label = a (string) This behavior differs from non-prepared statements. $mysqli->errno .Prepared Statements $stmt->execute(). } $out_id = NULL.16. $mysqli->error. ") " . } ?> The above example will output: id = 1 (integer). $row['id']. label) VALUES (1. printf("id = %s (%s)\n". $stmt->errno . gettype($row['label'])). label = %s (%s)\n". Output variables must be bound after statement execution. $row = $res->fetch_assoc(). Fetching results using bound variables Results from prepared statements can either be retrieved by binding output variables. gettype($out_id). $mysqli->connect_errno . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $stmt->error. If the connection option is used. Output variable binding <?php $mysqli = new mysqli("example. By default. non-prepared statements return all results as strings. or by requesting a mysqli_result object. } while ($stmt->fetch()) { printf("id = %s (%s). ") " . $out_label)) { echo "Binding output parameters failed: (" . $res = $stmt->get_result(). ") " . if (!$stmt->bind_result($out_id. label FROM test"))) { echo "Prepare failed: (" . label = a (string) 96 . One variable must be bound for every column of the statements result set. $mysqli->error. ") " . $mysqli->errno . $mysqli->connect_error. } if (!$stmt->execute()) { echo "Execute failed: (" . gettype($out_label)). This default can be changed using a connection option. $row['label'].com". there are no differences. "database"). "password". $out_label = NULL. 'a')")) { echo "Table creation failed: (" . gettype($row['id'])). $out_id.

$mysqli->error.17. } if (!($stmt = $mysqli->prepare("SELECT id. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. Fetching results using mysqli_result interface Instead of using bound results. results can also be retrieved through the mysqli_result interface. $mysqli->errno . $mysqli->errno . ?> The above example will output: array(1) { [0]=> array(2) { [0]=> int(1) [1]=> string(1) "a" } } Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation. } if (!$stmt->execute()) { echo "Execute failed: (" . "database"). label) VALUES (1. ") " . ") " . $stmt->error. $stmt->errno . Example 3.Prepared Statements Prepared statements return unbuffered result sets by default. $mysqli->error. $mysqli->connect_errno . Example 3. Buffered result set for flexible read out <?php 97 . } var_dump($res->fetch_all()). the data has to be fetched implicitly by mysqli. It is also possible to buffer the results of a prepared statement using mysqli_stmt_store_result. $stmt->errno . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" .18. ") " . } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. The result set takes server resources until all results have been fetched by the client. $mysqli->connect_error. ") " . "password". mysqli_stmt_get_result returns a buffered result set. "user". The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. Using mysqli_result to fetch results <?php $mysqli = new mysqli("example. 'a')")) { echo "Table creation failed: (" . If a client fails to fetch all results or the client closes the statement before having fetched all data. } if (!($res = $stmt->get_result())) { echo "Getting result set failed: (" . Thus it is recommended to consume results timely. label FROM test ORDER BY id ASC"))) { echo "Prepare failed: (" .com". ") " . $stmt->error.

$mysqli->connect_errno . } if (!($res = $stmt->get_result())) { echo "Getting result set failed: (" . $mysqli->error. See the mysqli_stmt_bind_param function for more information. $mysqli->errno . ") " .com". 98 . ") " . to create an appropriate conversion. (3.1). ?> 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" } Escaping and SQL injection Bound variables will be escaped automatically by the server. } $res->close(). A hint must be provided to the server for the type of bound variable. } if (!$stmt->execute()) { echo "Execute failed: (" . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . The automatic escaping of values within the server is sometimes considered a security feature to prevent SQL injection. ") " . Client-side prepared statement emulation The API does not include emulation for client-side prepared statement emulation. 'a'). label) VALUES (1. "database"). $mysqli->connect_error. ") " . "password". if input values are escaped correctly. label FROM test"))) { echo "Prepare failed: (" . } for ($row_no = ($res->num_rows . $mysqli->errno . $stmt->error. } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT. The server inserts their escaped values at the appropriate places into the statement template before execution. $stmt->error. label CHAR(1))") || !$mysqli->query("INSERT INTO test(id. (2. 'b'). "user". $stmt->errno . $stmt->errno . The same degree of security can be achieved with non-prepared statements. 'c')")) { echo "Table creation failed: (" . ") " . $row_no >= 0. $mysqli->error.Prepared Statements $mysqli = new mysqli("example. $row_no--) { $res->data_seek($row_no). var_dump($res->fetch_assoc()). } if (!($stmt = $mysqli->prepare("SELECT id.

5. Table 3. automatic input escaping Yes Supports use of mysqli_result API Yes.3. default of mysqli_query Statement string transferred from 1 client to server Client-server round trips. use output binding API Binary protocol Unbuffered result sets MySQL Client Server protocol data transfer flavor Yes. if any No. The CALL SQL statement is used to execute a stored procedure.non-prepared statement comparison The table below compares server-side prepared and non-prepared statements.2. Stored Procedures Copyright 1997-2012 the PHP Documentation Group. A stored procedure is a subroutine stored in the database catalog. single execution 2 Non-prepared statement 1 1 n n times together with parameter. if any Input parameter binding API Output variable binding API Yes. repeated (n) execution 1+n Statement string transferred from 1 template. Applications can call and execute the stored procedure. use mysqli_stmt_get_result or binding with mysqli_stmt_store_result Yes. SELECT. use mysqli_real_query with mysqli_use_result Text protocol Converted to string or preserved when fetching Yes Result set values SQL data types Preserved when fetching Supports all SQL statements Recent MySQL versions support most but not all See also mysqli::__construct mysqli::query mysqli::prepare mysqli_stmt::prepare mysqli_stmt::execute mysqli_stmt::bind_param mysqli_stmt::bind_result 3. SELECT.Stored Procedures Quick prepared . use mysqli_stmt_get_result Buffered result sets Yes. manual input escaping No Yes Yes. Parameter 99 . n times bound client to server parameter. Comparison of prepared and non-prepared statements Prepared Statement Client-server round trips. [1] The MySQL database supports stored procedures.

} if (!($res = $mysqli->query("SELECT @msg as _p_out"))) { echo "Fetch failed: (" . $mysqli->error.com". ") " . ") " .19. $mysqli->errno . ?> 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. "password". ") " . $mysqli->errno . $mysqli->errno .com". Example 3. ") " . ") " . "user". } var_dump($res->fetch_assoc()). make sure values are escaped correctly. $mysqli->connect_error. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . The mysqli interface has no special notion for the different kinds of parameters. ") " . Please.Stored Procedures Stored procedures can have IN. ") " . $mysqli->error.')) { echo "Stored procedure creation failed: (" . "user". $mysqli->errno . } 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). $mysqli->connect_errno . $mysqli->error. $mysqli->error. END. ") " . } if (!($res = $mysqli->query("SELECT id FROM test"))) { echo "SELECT failed: (" . "database"). $mysqli->connect_error. $mysqli->error. Using session variables <?php $mysqli = new mysqli("example. Example 3. $mysqli->errno . INOUT and OUT parameters. } if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) { echo "CALL failed: (" . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . } 100 . "password". } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) { echo "Table creation failed: (" . depending on the MySQL version. $mysqli->error. ") " . Calling a stored procedure <?php $mysqli = new mysqli("example. $mysqli->errno .")) { echo "Stored procedure creation failed: (" . $mysqli->errno . $mysqli->connect_errno .20. "database"). $mysqli->error. } if (!$mysqli->query("CALL p(1)")) { echo "CALL failed: (" . IN parameter Input parameters are provided with the CALL statement. END. } 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 TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1). ?> 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. However. Fetching results from stored procedures <?php $mysqli = new mysqli("example. Both functions allow fetching any number of result sets returned by a statement.com". $mysqli->errno . } else { if ($mysqli->errno) { echo "Store failed: (" . (2). ") " . The mysqli_query function combines statement execution and fetching the first result set into a buffered result set. However. Failing to fetch all result sets returned by a stored procedure causes an error. there are additional stored procedure result sets hidden from the user which cause mysqli_query to fail returning the user expected result sets. please note the possible performance impact of a custom solution based on catalog inspection. Example 3. $mysqli->error. ") " . $mysqli->connect_error.Stored Procedures $row = $res->fetch_assoc(). Result sets returned from a stored procedure are fetched using mysqli_real_query or mysqli_multi_query. $mysqli->errno . Handling result sets Stored procedures can return result sets. $mysqli->error. such as CALL. var_dump($res->fetch_all()). $mysqli->errno .21. SELECT id + 1 FROM test echo "Stored procedure creation failed: (" . $mysqli->error. if any. ?> The above example will output: 101 . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . ") " . $mysqli->error. $res->free(). } do { if ($res = $mysqli->store_result()) { printf("---\n"). "user". } if (!$mysqli->multi_query("CALL p()")) { echo "CALL failed: (" . $mysqli->errno . ") " . "database"). echo $row['_p_out']. "password". } } } while ($mysqli->more_results() && $mysqli->next_result()). Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query. (3)")) { echo "Table creation failed: (" . } if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test. ") " . $mysqli->connect_errno .

(3)")) { echo "Table creation failed: (" . Stored Procedures and Prepared Statements <?php $mysqli = new mysqli("example. that not every MYSQL server version may support preparing the CALL SQL statement. 102 .Stored Procedures --array(3) { [0]=> array(1) { [0]=> string(1) } [1]=> array(1) { [0]=> string(1) } [2]=> array(1) { [0]=> string(1) } } --array(3) { [0]=> array(1) { [0]=> string(1) } [1]=> array(1) { [0]=> string(1) } [2]=> array(1) { [0]=> string(1) } } "1" "2" "3" "2" "3" "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. Please note. } if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test. ") " . $mysqli->error. E echo "Stored procedure creation failed: (" . "password". $mysqli->errno . } 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: (" . $mysqli->errno .com". "user". $mysqli->connect_errno . Example 3. $mysqli->error. ") " . $mysqli->connect_error. $mysqli->errno . if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->error. "database"). ") " . SELECT id + 1 FROM test. The prepared statement and non-prepared statement interfaces are similar.22. ") " . (2).

Sending multiple statements at once reduces client-server round trips but requires special handling. Stored Procedures and Prepared Statements using bind API <?php if (!($stmt = $mysqli->prepare("CALL p()"))) { echo "Prepare failed: (" . $stmt->errno . } while ($stmt->fetch()) { echo "id = $id_out\n". } do { $id_out = NULL. ") " . [1] MySQL optionally allows having multiple statements in one statement string. ") " . $stmt->errno .6. Multiple statements or multi queries must be executed with mysqli_multi_query. if (!$stmt->bind_result($id_out)) { echo "Bind failed: (" . $stmt->error.Multiple Statements } if (!$stmt->execute()) { echo "Execute failed: (" . $mysqli->errno . Multiple Statements Copyright 1997-2012 the PHP Documentation Group. 103 . ") " . } else { if ($stmt->errno) { echo "Store failed: (" .3. ") " . mysqli_free_result($res). Then. The individual statements of the statement string are separated by semicolon. $stmt->errno . ?> Of course. } do { if ($res = $stmt->get_result()) { printf("---\n"). $stmt->errno . ?> See also mysqli::query mysqli::multi_query mysqli_result::next-result mysqli_result::more-results 3. use of the bind API for fetching is supported as well. $stmt->error.23. $mysqli->error. Example 3. $stmt->error. ") " . } } while ($stmt->more_results() && $stmt->next_result()). all result sets returned by the executed statements must be fetched. } } } while ($stmt->more_results() && $stmt->next_result()). } if (!$stmt->execute()) { echo "Execute failed: (" . var_dump(mysqli_fetch_all($res)). $stmt->error.

SQL Injection <?php $mysqli = new mysqli("example. $mysqli->connect_errno . ") " . ". $sql. SELECT SLEEP(999). $mysqli->error. DROP TABLE mysql. ") " . } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) { echo "Table creation failed: (" .user").25. } $sql = "SELECT COUNT(*) AS _num FROM test. $mysqli->connect_error. "user". $res->free(). $mysqli->error. } } while ($mysqli->more_results() && $mysqli->next_result()).= "INSERT INTO test(id) VALUES (1). injected and malicious SQL statement. ". DROP DATABASE mysql or . the server will not execute the second. "database"). 104 . "database"). if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $res = $mysqli->query("SELECT 1. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as .com". ") " . If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used.24. ". Multiple Statements <?php $mysqli = new mysqli("example. "password". ?> 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 The API functions mysqli_query and mysqli_real_query do not set a connection flag necessary for activating multi queries in the server. Example 3. } do { if ($res = $mysqli->store_result()) { var_dump($res->fetch_all(MYSQLI_ASSOC)).com". $mysqli->errno .Multiple Statements The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement. "user". if (!$mysqli->multi_query($sql)) { echo "Multi query failed: (" . "password". Example 3. $sql.= "SELECT COUNT(*) AS _num FROM test. $mysqli->errno .

Example 3. $mysqli->connect_error.3. check the manual that corresponds to your MySQL server version for the right syntax to use near 'DROP TABLE mysql. [1] The MySQL server supports transactions depending on the storage engine used. such as the replication and load balancing plugin. "database"). Commit and rollback 105 .API support for transactions if (!$res) { echo "Error executing query: (" . It is recommended to use API calls for enabling and disabling the auto commit mode and for committing and rolling back transactions. $mysqli->errno . Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode. Since MySQL 5. InnoDB has full ACID transaction support. $mysqli->errno . if transactions are controlled with API calls.26. Setting auto commit mode with SQL and through the API <?php $mysqli = new mysqli("example.com". The replication plugin offers transaction aware load balancing.user' at line 1 Prepared statements Use of the multiple statement with prepared statements is not supported. $mysqli->error. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->error. } ?> Optional feature packages. ") " . ") " .5. $mysqli->connect_errno . committing or rolling back a transaction. "user". Transactions can either be controlled using SQL or API calls. API support for transactions Copyright 1997-2012 the PHP Documentation Group. See also mysqli::query mysqli::multi_query mysqli_result::next-result mysqli_result::more-results 3.7. can easily monitor API calls.27. the default storage engine is InnoDB. /* Won't be monitored and recognized by the replication and the load balancing plugin */ if (!$mysqli->query('SET AUTOCOMMIT = 0')) { echo "Query failed: (" . } /* Recommended: using API to control transactional settings */ $mysqli->autocommit(false). Example 3. ") " . "password". } ?> The above example will output: Error executing query: (1064) You have an error in your SQL syntax.

3. ") " . "password".28. } $res = $mysqli->query("SELECT 1 AS _one. $mysqli->connect_error. The metadata describes the columns found in the result set. "password". $mysqli->autocommit(false). Differences between MySQL server versions are not aligned. $mysqli->rollback().Metadata <?php $mysqli = new mysqli("example. $mysqli->query("INSERT INTO test(id) VALUES (2)"). $mysqli->commit(). "database"). "user". var_dump($res->fetch_fields()). $mysqli->connect_errno .com". Accessing result set meta data <?php $mysqli = new mysqli("example. Metadata Copyright 1997-2012 the PHP Documentation Group. [1] A MySQL result set contains metadata. ?> Please note. "user". $mysqli->query("INSERT INTO test(id) VALUES (1)").com". that the MySQL server cannot roll back all statements. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . The extension performs no or negligible changes to the information it receives. "database"). Some statements cause am implicit commit. See also mysqli::autocommit mysqli_result::commit mysqli_result::rollback 3. Example 3. All metadata send by MySQL is accessible through the mysqli interface. 'Hello' AS _two FROM DUAL"). ?> 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) "" 106 . Meta data is access through the mysqli_result interface.8.

$stmt->execute().Metadata ["catalog"]=> string(3) "def" ["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. var_dump($res->fetch_fields()).29. Prepared statements metadata <?php $stmt = $mysqli->prepare("SELECT 1 AS _one. A suitable mysqli_result handle is returned by mysqli_stmt_result_metadata. 'Hello' AS _two FROM DUAL"). ?> See also 107 . $res = $stmt->result_metadata(). Example 3.

Although these binary versions are typically built with support for MySQL extensions enabled. Unless your Unix distribution comes with a binary package of PHP with the mysqli extension available. For previous versions. you will need to build PHP from source code. Table 3.0.2. mysqli compile time support matrix PHP Version Default Configure Configure Options: mysqlnd Options: libmysql Not Available --with-mysqli=/ path/to/ mysql_config --with-mysqli=/ mysqlnd is now path/to/ supported mysql_config Changelog 5.3. Installing/Configuring Copyright 1997-2012 the PHP Documentation Group.3. Check the package manager than comes with your chosen distribution for availability. Refer to What is PHP's MySQL Native Driver? [85] for a brief overview of the advantages of MySQL Native Driver.7 or newer.1. [1] 3. please see the MySQL extension documentation. 5. 3.4. Note The mysqli extension is designed to work with MySQL version 4.0.4.2. or 5. the extension libraries themselves may need to be installed using an additional package.4. The MySQL Native Driver is the recommended option.0.1. Building PHP from source allows you to specify the MySQL extensions you want to use. The MySQL Native Driver was included in PHP version 5.x.1.x libmysql --withmysqli=mysqlnd 108 . 5.Installing/Configuring mysqli::query mysqli_result::fetch_fields 3. you must compile PHP with support for the mysqli extension.1.2. 3.0. as it results in improved performance and gives access to features not available when using the MySQL Client Library. as well as your choice of client library for each extension.4. Installation Copyright 1997-2012 the PHP Documentation Group.3.0. [1] In order to have these functions available. Requirements Copyright 1997-2012 the PHP Documentation Group. The /path/to/mysql_config represents the location of the mysql_config program that comes with MySQL Server.x libmysql 5. [1] The mysqli extension was introduced with PHP version 5.13 or newer.x. Installation on Linux Copyright 1997-2012 the PHP Documentation Group. [1] The common Unix distributions include binary versions of PHP that can be installed.

x mysqlnd --with-mysqli=/ mysqlnd is now the path/to/ default mysql_config Note that it is possible to freely mix MySQL extensions and client libraries. Copying libmysql./configure --with-mysql=/usr/bin/mysql_config --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd [other options] \ 3. [1] On Windows. PHP 5.0. PHP is most commonly installed using the binary installer. the PHP directive extension_dir should be set to the directory where the PHP extensions are located. As with enabling any PHP extension (such as php_mysqli. Also. so that it can be successfully loaded.dll to the Windows system directory (typically c:\Windows\system) also works. while configuring the mysqli extension to use the MySQL Native Driver. 5. and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli.dll DLL must be enabled inside of php. An example extension_dir value for PHP 5 is c:\php\ext.2. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. However.2. if you want to use the MySQL Client Library with mysqli.4. this is because php_mysqli. In order to do this you need to find the php.ini.ini file (typically located in c:\php). However.4. [1] Once PHP has been installed.1.1.dll'". The MySQL Client Library is included as a file named libmysql. Installation on Windows Systems Copyright 1997-2012 the PHP Documentation Group.4. in the section marked [PHP_MYSQLI]. 5./php_mysqli.2 Copyright 1997-2012 the PHP Documentation Group.dll.dll in the Windows PHP distribution.dll and/or libmysql. The mysqli extension is not enabled by default. See also the Manual Windows Installation Instructions. This file needs to be available in the Windows system's PATH environment variable. this practice is strongly discouraged. it is possible to enable the MySQL extension to use the MySQL Client Library (libmysql). all permutations of extension and client library are possible. and the mysqli and PDO MYSQL extensions to use the MySQL Native Driver: . For example. 3. you need to make sure PHP can access the client library file. as the system directory is by default in the system's PATH.2. 109 .dll).2. The following example builds the MySQL extension to use the MySQL Client Library. some configuration is required to enable mysqli and specify the client library you want it to use.Installation PHP Version Default Configure Configure Options: mysqlnd Options: libmysql --with-mysqli Changelog 5.dll cannot be found by the system. Note If when starting the web server an error similar to the following occurs: "Unable to load dynamic library '. so the php_mysqli.

2. Available since PHP 5.5.0. Available since PHP 5.allow_persistent integer mysqli.allow_persistent mysqli.max_links mysqli.0.default_pw mysqli.default_user mysqli. Available since PHP 5. 110 .max_persistent mysqli.cache_size Default "1" "1" "-1" "-1" "3306" NULL NULL NULL NULL "0" "2000" Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_ALL PHP_INI_SYSTEM PHP_INI_SYSTEM Changelog Available since PHP 5. Available since PHP 5.0.0. for PHP versions 5.3.2.0.reconnect mysqli.0. Available since PHP 5.allow_local_infile mysqli.3. from PHP's perspective.ini. Available since PHP 5.3. Here's a short explanation of the configuration directives.4.0. Available since PHP 5. Available since PHP 5.2. This means you don't need to worry about configuring access to libmysql.0. see the chapter on configuration changes.dll. [1] On Windows. Set to 0 for unlimited.allow_local_infile Allow accessing.0+ Copyright 1997-2012 the PHP Documentation Group.3.default_port mysqli.2. local files with LOAD DATA integer statements mysqli. Table 3. PHP 5. MySQLi Configuration Options Name mysqli.Runtime Configuration 3.max_persistent integer Enable the ability to create persistent connections using mysqli_connect.0. Available since PHP 5.0. the mysqli extension is enabled and uses the MySQL Native Driver by default.3.3. Maximum of persistent connections that can be made.3 and newer.default_socket mysqli. 3.default_host mysqli.0. [1] The behaviour of these functions is affected by settings in php.0.0.4.4. Runtime Configuration Copyright 1997-2012 the PHP Documentation Group.0. Available since PHP 4.0. mysqli. For further details and definitions of the preceding PHP_INI_* constants.4.

increasing the burden on the programmer. The default password to use when connecting to the database server if no other password is specified. [1] This extension has no resource types defined. The default user name to use when connecting to the database server if no other name is specified.default_pw string mysqli.4. The default server host to use when connecting to the database server if no other host is specified. If no default is specified. Support was already present in PDO MYSQL and ext/mysql.cache_size integer Users cannot set MYSQL_OPT_READ_TIMEOUT through an API call or runtime configuration setting. This reduces the overhead of creating fresh connections every time one is required.default_port integer The maximum number of MySQL connections per process.default_socket string mysqli. Available only with mysqlnd. The default TCP port number to use when connecting to the database server if no other port is specified. The problem with persistent connections is that they can be left in unpredictable states by clients. Doesn't apply in safe mode.3 for the mysqli extension. For example. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process. The cleanup carried out by mysqli includes: 111 . To open a persistent connection you must prepend p: to the hostname when connecting. 3. The persistent connection of the mysqli extension however provides built-in cleanup handling code. Automatically reconnect if the connection was lost. the mysql-tcp entry in /etc/services or the compiletime MYSQL_PORT constant. Note that if it were possible there would be differences between how libmysql and streams would interpret the value of MYSQL_OPT_READ_TIMEOUT.max_links integer mysqli.default_host string mysqli. Any cleanup would need to be done by the new client process before it could make good use of the persistent connection. Resource Types Copyright 1997-2012 the PHP Documentation Group. mysqli does not provide a separate function for opening persistent connections.4. in that order. rather than being created and destroyed multiple times. The default socket name to use when connecting to a local database server if no other socket name is specified.reconnect integer mysqli. Doesn't apply in safe mode.default_user string mysqli. Unlike the mysql extension.5. 3. [1] Persistent connection support was introduced in PHP 5. the port will be obtained from the MYSQL_TCP_PORT environment variable. a table lock might be activated before a client terminates unexpectedly. The mysqli Extension and Persistent Connections Copyright 1997-2012 the PHP Documentation Group.Resource Types mysqli. Doesn't apply in safe mode. mysqli. A new client process reusing this persistent connection will get the connection “as is”. as unused connections are cached and ready to be reused. Win32 will only use the MYSQL_PORT constant.

Predefined Constants • 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.6. It is possible to switch off the automatic cleanup code. This option should not be set by application programs. 3. MYSQLI_READ_DEFAULT_GROUP Read options from the named group from my. [1] The constants below are defined by this extension. as it is called automatically. it is set internally in the MySQL client library Use compression protocol MYSQLI_CLIENT_SSL MYSQLI_CLIENT_COMPRESS MYSQLI_CLIENT_INTERACTIVE Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. Use SSL (encrypted protocol). the disadvantage is that the code could potentially be a little slower. The advantage is that the programmer no longer needs to worry about adding cleanup code. The automatic cleanup feature has advantages and disadvantages though.cnf MYSQLI_OPT_CONNECT_TIMEOUTConnect timeout in seconds MYSQLI_OPT_LOCAL_INFILE MYSQLI_INIT_COMMAND Enables command LOAD LOCAL INFILE Command to execute when connecting to MySQL server.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE MYSQLI_READ_DEFAULT_FILE Read options from the named option file instead of from my. The client's 112 . as the code to perform the cleanup needs to run each time a connection is returned from the connection pool. However. Predefined Constants Copyright 1997-2012 the PHP Documentation Group. The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user(). Note The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library. Will automatically be re-executed when reconnecting. before the client process uses them. by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined. and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

col_name syntax. MYSQLI_CLIENT_IGNORE_SPACEAllow spaces after function names.0.3 and up) Field is defined as BIT (MySQL 5. MYSQLI_CLIENT_MULTI_QUERIES Allows multiple semicolon-delimited queries in a single mysqli_query call. Field is part of an index. MYSQLI_CLIENT_NO_SCHEMA Don't allow the db_name.Predefined Constants session wait_timeout variable will be set to the value of the session interactive_timeout variable. MYSQLI_STORE_RESULT MYSQLI_USE_RESULT MYSQLI_ASSOC For using buffered resultsets For using unbuffered resultsets Columns are returned into the array having the fieldname as the array index.tbl_name. Columns are returned into the array having an enumerated index. Columns are returned into the array having both a numerical index and the fieldname as the associative index.0. Field is defined as BLOB Field is defined as UNSIGNED Field is defined as ZEROFILL MYSQLI_NUM MYSQLI_BOTH MYSQLI_NOT_NULL_FLAG MYSQLI_PRI_KEY_FLAG MYSQLI_UNIQUE_KEY_FLAG MYSQLI_MULTIPLE_KEY_FLAG MYSQLI_BLOB_FLAG MYSQLI_UNSIGNED_FLAG MYSQLI_ZEROFILL_FLAG MYSQLI_AUTO_INCREMENT_FLAGField is defined as AUTO_INCREMENT MYSQLI_TIMESTAMP_FLAG 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 Field is defined as 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. Makes all functions names reserved words. Indicates that a field is defined as NOT NULL Field is part of a primary index Field is part of a unique index.3 and up) Field is defined as TINYINT Field is defined as SMALLINT Field is defined as INT 113 .

0.1.3.0 and MySQL 5.5. Available since PHP 5. For CHAR. MYSQLI_CURSOR_TYPE_FOR_UPDATE MYSQLI_CURSOR_TYPE_NO_CURSOR MYSQLI_CURSOR_TYPE_READ_ONLY MYSQLI_CURSOR_TYPE_SCROLLABLE 114 .0. see MYSQLI_TYPE_STRING Field is defined as GEOMETRY More data available for bind variable No more data available for bind variable Data truncation occurred. Field is defined as ENUM.Predefined Constants MYSQLI_TYPE_FLOAT MYSQLI_TYPE_DOUBLE MYSQLI_TYPE_NULL MYSQLI_TYPE_TIMESTAMP MYSQLI_TYPE_LONGLONG MYSQLI_TYPE_INT24 MYSQLI_TYPE_DATE MYSQLI_TYPE_TIME MYSQLI_TYPE_DATETIME MYSQLI_TYPE_YEAR MYSQLI_TYPE_NEWDATE MYSQLI_TYPE_INTERVAL MYSQLI_TYPE_ENUM MYSQLI_TYPE_SET MYSQLI_TYPE_TINY_BLOB MYSQLI_TYPE_MEDIUM_BLOB MYSQLI_TYPE_LONG_BLOB MYSQLI_TYPE_BLOB MYSQLI_TYPE_VAR_STRING MYSQLI_TYPE_STRING MYSQLI_TYPE_CHAR MYSQLI_TYPE_GEOMETRY MYSQLI_NEED_DATA MYSQLI_NO_DATA MYSQLI_DATA_TRUNCATED MYSQLI_ENUM_FLAG Field is defined as FLOAT Field is defined as DOUBLE Field is defined as DEFAULT NULL Field is defined as TIMESTAMP Field is defined as BIGINT Field is defined as MEDIUMINT Field is defined as DATE Field is defined as TIME Field is defined as DATETIME Field is defined as YEAR Field is defined as DATE Field is defined as INTERVAL Field is defined as ENUM Field is defined as SET Field is defined as TINYBLOB Field is defined as MEDIUMBLOB Field is defined as LONGBLOB Field is defined as BLOB Field is defined as VARCHAR Field is defined as CHAR or BINARY Field is defined as TINYINT. Available since PHP 5.

and restarts the slave. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5. [1] Some implementation notes: 1. Set all options on (report all). MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED MYSQLI_SERVER_QUERY_NO_INDEX_USED MYSQLI_REFRESH_GRANT MYSQLI_REFRESH_LOG MYSQLI_REFRESH_TABLES Refreshes the grant tables. For example. Like executing the RESET MASTER SQL statement. libmysql may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. On a slave replication server: resets the master server information. like executing the FLUSH LOGS SQL statement. Generally speaking. MYSQLI_DEBUG_TRACE_ENABLEDIs set to 1 if mysqli_debug functionality is enabled. Throw a mysqli_sql_exception for errors instead of warnings. On a master replication server: removes the binary log files listed in the binary log index. and truncates the index file. if using mysqlnd. less than 50 bytes. Note there are different internal implementations within libmysql and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. mysqlnd will allocate significantly less memory.3. Flushes the logs. Flushes the host cache. Memory allocation is much lower. if there is a POINT column in a result set. like executing the FLUSH HOSTS SQL statement.Notes MYSQLI_STMT_ATTR_CURSOR_TYPE MYSQLI_STMT_ATTR_PREFETCH_ROWS MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH MYSQLI_SET_CHARSET_NAME MYSQLI_REPORT_INDEX MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT MYSQLI_REPORT_ALL MYSQLI_REPORT_OFF Report if no index or bad index was used in a query. 2. Reset the status variables. Turns reporting off. Flushes the thread cache. Notes Copyright 1997-2012 the PHP Documentation Group.7. 115 . Report errors from mysqli function calls. Flushes the table cache. like executing the FLUSH STATUS SQL statement. MYSQLI_REFRESH_HOSTS MYSQLI_REFRESH_STATUS MYSQLI_REFRESH_THREADS MYSQLI_REFRESH_SLAVE MYSQLI_REFRESH_MASTER 3. like executing the FLUSH TABLES SQL statement. Like executing the RESET SLAVE SQL statement.

The MySQLi Extension Function Summary 3.8. Summary of mysqli methods mysqli Class OOP Interface Properties $mysqli::affected_rows mysqli_affected_rowsN/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 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 Procedural Interface Alias (Do not use) Description $mysqli::client_info $mysqli::client_version $mysqli::connect_errno $mysqli::connect_error mysqli_get_client_info N/A mysqli_get_client_version N/A mysqli_connect_errnoN/A mysqli_connect_errorN/A $mysqli::errno mysqli_errno N/A $mysqli::error mysqli_error N/A $mysqli::field_count mysqli_field_count N/A $mysqli::host_info mysqli_get_host_infoN/A $mysqli::protocol_version mysqli_get_proto_info N/A $mysqli::server_info $mysqli::server_version mysqli_get_server_info N/A mysqli_get_server_version N/A $mysqli::info mysqli_info N/A $mysqli::insert_id mysqli_insert_id N/A 116 .5. [1] Table 3. The MySQLi Extension Function Summary Copyright 1997-2012 the PHP Documentation Group.

Returns client Zval cache statistics. mysqli_character_set_name mysqli_client_encoding Returns the default mysqli::client_encoding character set for the database connection mysqli::close mysqli_close N/A 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.e. Available only with mysqlnd.The MySQLi Extension Function Summary mysqli Class OOP Interface $mysqli::sqlstate Procedural Interface mysqli_sqlstate Alias (Do not use) N/A Description 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 autocommitting database modifications Changes the user of the specified database connection $mysqli::warning_count mysqli_warning_countN/A Methods mysqli::autocommit mysqli_autocommit N/A mysqli::change_user mysqli_change_user N/A mysqli::character_set_name. Returns the MySQL client version as a string Returns client perprocess statistics. NOT DOCUMENTED mysqli::commit mysqli_commit N/A N/A mysqli::__construct mysqli_connect mysqli::debug mysqli_debug N/A mysqli::dump_debug_info mysqli_dump_debug_info N/A mysqli::get_charset mysqli_get_charset N/A mysqli::get_connection_stats mysqli_get_connection_stats N/A mysqli::get_client_info mysqli_get_client_info N/A mysqli::get_client_stats mysqli_get_client_stats N/A mysqli::get_cache_stats mysqli_get_cache_stats N/A mysqli::get_server_info mysqli_get_server_info N/A 117 . class) method] Performs debugging operations Dump debugging information into the log Returns a character set object Returns client connection statistics. Available only with mysqlnd.

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 mysqli::get_warningsmysqli_get_warnings N/A mysqli::kill mysqli_kill N/A mysqli::more_resultsmysqli_more_results N/A mysqli::multi_query mysqli_multi_query mysqli::next_result mysqli_next_result mysqli::options mysqli::ping mysqli_options mysqli_ping N/A N/A mysqli_set_opt N/A mysqli::prepare mysqli::query mysqli_prepare mysqli_query N/A N/A mysqli::real_connectmysqli_real_connect N/A mysqli::real_escape_string.The MySQLi Extension Function Summary mysqli Class OOP Interface mysqli::init Procedural Interface mysqli_init Alias (Do not use) N/A Description NOT DOCUMENTED Initializes MySQLi and returns a resource for use with mysqli_real_connect. or resets the replication server information Rolls back current transaction Selects the default database for database queries mysqli::rollback mysqli::select_db mysqli_rollback mysqli_select_db N/A N/A 118 . mysqli_real_escape_string mysqli_escape_stringEscapes special mysqli::escape_string characters in a string for use in an SQL statement. [Not called on an object. as it returns a $mysqli object. taking into account the current charset of the connection mysqli::real_query mysqli::refresh mysqli_real_query mysqli_refresh N/A N/A Execute an SQL query Flushes tables or caches.] Asks the server to kill a MySQL thread Check if there are any more query results from a multi query Performs a query on the database Prepare next result from multi_query Set options Pings a server connection.

The MySQLi Extension Function Summary mysqli Class OOP Interface Procedural Interface Alias (Do not use) N/A Description 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::set_charset mysqli_set_charset mysqli::set_local_infile_default mysqli_set_local_infile_default N/A mysqli::set_local_infile_handler mysqli_set_local_infile_handler N/A mysqli::ssl_set mysqli_ssl_set N/A mysqli::stat mysqli::stmt_init mysqli_stat mysqli_stmt_init N/A N/A mysqli::store_resultmysqli_store_result N/A mysqli::thread_id mysqli_thread_id N/A N/A N/A mysqli::thread_safe mysqli_thread_safe mysqli::use_result mysqli_use_result Table 3. deleted. Summary of mysqli_stmt methods MySQL_STMT OOP Interface Properties $mysqli_stmt::affected_rows mysqli_stmt_affected_rows N/A Returns the total number of rows changed.6. or inserted by the last executed statement Returns the error code for the most recent statement call Returns a string description for last statement error Returns the number of field in the given statement .not documented Procedural Interface Alias (Do not use) Description $mysqli_stmt::errno mysqli_stmt_errno N/A $mysqli_stmt::error mysqli_stmt_error N/A $mysqli_stmt::field_count mysqli_stmt_field_count N/A 119 .

NOT DOCUMENTED mysqli_stmt_insert_id N/A $mysqli_stmt::num_rows mysqli_stmt_num_rowsN/A $mysqli_stmt::param_count ysqli_stmt_param_count m mysqli_param_count $mysqli_stmt::sqlstate mysqli_stmt_sqlstateN/A Methods mysqli_stmt::attr_get mysqli_stmt_attr_getN/A mysqli_stmt::attr_set mysqli_stmt_attr_setN/A mysqli_stmt::bind_param mysqli_stmt_bind_param mysqli_bind_param mysqli_stmt::bind_result mysqli_stmt_bind_result mysqli_bind_result mysqli_stmt::close mysqli_stmt_close N/A mysqli_stmt::data_seek mysqli_stmt_data_seek N/A mysqli_stmt::executemysqli_stmt_execute mysqli_execute mysqli_stmt::fetch mysqli_stmt_fetch mysqli_fetch mysqli_stmt::free_result mysqli_stmt_free_result N/A mysqli_stmt::get_result mysqli_stmt_get_result N/A mysqli_stmt::get_warnings mysqli_stmt_get_warnings N/A 120 .The MySQLi Extension Function Summary MySQL_STMT OOP Interface $mysqli_stmt::insert_id Procedural Interface Alias (Do not use) Description 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. Available only with mysqlnd.

The MySQLi Extension Function Summary

MySQL_STMT OOP Interface Procedural Interface Alias (Do not use) Description NOT DOCUMENTED Available only with mysqlnd. NOT DOCUMENTED Available only with mysqlnd. See also property $mysqli_stmt::num_rows Prepare an SQL statement for execution Resets a prepared statement $mysqli_stmt::more_results() mysqli_stmt_more_results() /A N

$mysqli_stmt::next_result()mysqli_stmt_next_result() N/A

mysqli_stmt::num_rows mysqli_stmt_num_rowsN/A mysqli_stmt::preparemysqli_stmt_prepare N/A mysqli_stmt::reset mysqli_stmt_reset N/A

mysqli_stmt::result_metadata mysqli_stmt_result_metadata mysqli_get_metadata Returns result set metadata from a prepared statement mysqli_stmt::send_long_data mysqli_stmt_send_long_data mysqli_send_long_data Send data in blocks mysqli_stmt::store_result mysqli_stmt_store_result N/A Transfers a result set from a prepared statement

Table 3.7. Summary of mysqli_result methods mysqli_result OOP Interface Properties $mysqli_result::current_fieldysqli_field_tell m $mysqli_result::field_countmysqli_num_fields $mysqli_result::lengths 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 arbitrary row in the result Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd. Procedural Interface Alias (Do not use) Description

mysqli_fetch_lengthsN/A

$mysqli_result::num_rows mysqli_num_rows Methods mysqli_result::data_seek mysqli_data_seek

N/A

N/A

mysqli_result::fetch_all mysqli_fetch_all

N/A

121

The mysqli class (mysqli)

mysqli_result OOP Interface Procedural Interface Alias (Do not use) N/A Description Fetch a result row as an associative, a numeric array, or both Fetch a result row as an associative array Fetch meta-data for a single field Returns the next field in the result set Returns an array of objects representing the fields in a result set Returns the current row of a result set as an object Get a result row as an enumerated array Set result pointer to a specified field offset Frees the memory associated with a result mysqli_result::fetch_array mysqli_fetch_array

mysqli_result::fetch_assoc mysqli_fetch_assoc

N/A

mysqli_result::fetch_field_direct mysqli_fetch_field_direct N/A mysqli_result::fetch_field mysqli_fetch_field N/A

mysqli_result::fetch_fields mysqli_fetch_fields N/A

mysqli_result::fetch_object mysqli_fetch_object N/A

mysqli_result::fetch_row mysqli_fetch_row mysqli_result::field_seek mysqli_field_seek mysqli_result::free, mysqli_free_result mysqli_result::close, mysqli_result::free_result Table 3.8. Summary of mysqli_driver methods MySQL_Driver OOP Interface Properties N/A Methods Procedural Interface

N/A N/A N/A

Alias (Do not use)

Description

mysqli_driver::embedded_server_end mysqli_embedded_server_end N/A mysqli_driver::embedded_server_start mysqli_embedded_server_start N/A Note

NOT DOCUMENTED NOT DOCUMENTED

Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

3.9. The mysqli class (mysqli)
Copyright 1997-2012 the PHP Documentation Group. [1] Represents a connection between PHP and a MySQL database.
mysqli {

122

The mysqli class (mysqli)

mysqli Properties int mysqli->affected_rows ; string mysqli->client_info ; int mysqli->client_version ; string mysqli->connect_errno ; string mysqli->connect_error ; int mysqli->errno ; array mysqli->error_list ; string mysqli->error ; int mysqli->field_count ; int mysqli->client_version ; string mysqli->host_info ; string mysqli->protocol_version ; string mysqli->server_info ; int mysqli->server_version ; string mysqli->info ; mixed mysqli->insert_id ; string mysqli->sqlstate ; int mysqli->thread_id ; int mysqli->warning_count ; Methods mysqli::__construct( string host = =ini_get("mysqli.default_host"), string username

123

The mysqli class (mysqli)

= =ini_get("mysqli.default_user"), string passwd = =ini_get("mysqli.default_pw"), string dbname = ="", int port = =ini_get("mysqli.default_port"), string socket = =ini_get("mysqli.default_socket")); bool mysqli::autocommit( bool mode); bool mysqli::change_user( string user, string password, string database); string mysqli::character_set_name(); bool mysqli::close(); bool mysqli::commit(); bool mysqli::debug( string message); bool mysqli::dump_debug_info(); object mysqli::get_charset(); string mysqli::get_client_info(); bool mysqli::get_connection_stats(); mysqli_warning mysqli::get_warnings(); mysqli mysqli::init(); bool mysqli::kill( int processid); bool mysqli::more_results(); bool mysqli::multi_query( string query); bool mysqli::next_result(); bool mysqli::options( int option, mixed value); bool mysqli::ping(); public int mysqli::poll( array read, array error, array reject, int sec, int usec); mysqli_stmt mysqli::prepare( string query); mixed mysqli::query(

124

mysqli::$affected_rows, mysqli_affected_rows

string query, int resultmode = =MYSQLI_STORE_RESULT); bool mysqli::real_connect( string host, string username, string passwd, string dbname, int port, string socket, int flags); string mysqli::escape_string( string escapestr); bool mysqli::real_query( string query); public mysqli_result mysqli::reap_async_query(); public bool mysqli::refresh( int options); bool mysqli::rollback(); int mysqli::rpl_query_type( string query); bool mysqli::select_db( string dbname); bool mysqli::send_query( string query); bool mysqli::set_charset( string charset); bool mysqli::set_local_infile_handler( mysqli link, callable read_func); bool mysqli::ssl_set( string key, string cert, string ca, string capath, string cipher); string mysqli::stat(); mysqli_stmt mysqli::stmt_init(); mysqli_result mysqli::store_result(); mysqli_result mysqli::use_result(); }

3.9.1. mysqli::$affected_rows, mysqli_affected_rows
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::$affected_rows

125

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 ;

Procedural style
int mysqli_affected_rows( mysqli link);

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. For SELECT statements mysqli_affected_rows works like mysqli_num_rows. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

Return Values An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error. Note If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string. Examples Example 3.30. $mysqli->affected_rows 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(); } /* Insert rows */ $mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage"); printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows); $mysqli->query("ALTER TABLE Language ADD Status int default 0"); /* update rows */ $mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50"); printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows); /* delete rows */ $mysqli->query("DELETE FROM Language WHERE Percentage < 50"); printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows); /* select all rows */

126

mysqli::autocommit, mysqli_autocommit

$result = $mysqli->query("SELECT CountryCode FROM Language"); printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows); $result->close(); /* Delete table Language */ $mysqli->query("DROP TABLE Language"); /* close connection */ $mysqli->close(); ?>

Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); if (!$link) { printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error()); exit(); } /* Insert rows */ mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage"); printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link)); mysqli_query($link, "ALTER TABLE Language ADD Status int default 0"); /* update rows */ mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50"); printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link)); /* delete rows */ mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50"); printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link)); /* select all rows */ $result = mysqli_query($link, "SELECT CountryCode FROM Language"); printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link)); mysqli_free_result($result); /* Delete table Language */ mysqli_query($link, "DROP TABLE Language"); /* close connection */ mysqli_close($link); ?>

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

3.9.2. mysqli::autocommit, mysqli_autocommit
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::autocommit mysqli_autocommit

127

mysqli::autocommit, mysqli_autocommit

Turns on or off auto-committing database modifications Description Object oriented style
bool mysqli::autocommit( bool mode);

Procedural style
bool mysqli_autocommit( mysqli link, bool mode);

Turns on or off auto-commit mode on queries for the database connection. To determine the current state of autocommit use the SQL command SELECT @@autocommit. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Whether to turn on auto-commit or not.

mode Return Values

Returns TRUE on success or FALSE on failure. Notes Note This function doesn't work with non transactional table types (like MyISAM or ISAM). Examples Example 3.31. mysqli::autocommit example Object oriented style
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* turn autocommit on */ $mysqli->autocommit(TRUE); if ($result = $mysqli->query("SELECT @@autocommit")) { $row = $result->fetch_row(); printf("Autocommit is %s\n", $row[0]); $result->free(); } /* close connection */ $mysqli->close(); ?>

128

mysqli::change_user, mysqli_change_user

Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); if (!$link) { printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error()); exit(); } /* turn autocommit on */ mysqli_autocommit($link, TRUE); if ($result = mysqli_query($link, "SELECT @@autocommit")) { $row = mysqli_fetch_row($result); printf("Autocommit is %s\n", $row[0]); mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?>

The above examples will output:
Autocommit is 1

See Also mysqli_commit mysqli_rollback

3.9.3. mysqli::change_user, mysqli_change_user
Copyright 1997-2012 the PHP Documentation Group. [1] • 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 link, string user, string password, string database);

129

mysqli::change_user, mysqli_change_user

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 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 3.32. mysqli::change_user example Object oriented style
<?php /* connect database test */ $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();

user password database

130

mysqli_character_set_name Copyright 1997-2012 the PHP Documentation Group. if ($result = mysqli_query($link.9. if ($row[0] === NULL) { printf("Value of variable a is NULL\n").4. $row[0]). "test"). "my_user". /* check connection */ if (!$link) { printf("Connect failed: %s\n". /* reset all and select a new database */ mysqli_change_user($link. mysqli_connect_error()). "my_password". "SET @a:=1"). "SELECT DATABASE()")) { $row = mysqli_fetch_row($result). } /* Set Variable a */ mysqli_query($link. } if ($result = mysqli_query($link. mysqli_character_set_name if ($row[0] === NULL) { printf("Value of variable a is NULL\n"). ?> The above examples will output: Default database: world Value of variable a is NULL See Also mysqli_connect mysqli_select_db 3. mysqli_free_result($result). "world"). mysqli::character_set_name. printf("Default database: %s\n". "SELECT @a")) { $row = mysqli_fetch_row($result). exit().mysqli::character_set_name. [1] • mysqli::character_set_name mysqli_character_set_name 131 . "my_password". } /* close connection */ $mysqli->close(). } /* close connection */ mysqli_close($link). ?> Procedural style <?php /* connect database test */ $link = mysqli_connect("localhost". "my_user". } mysqli_free_result($result). } $result->close().

mysqli_connect_error()). "my_user". exit(). } /* Print current character set */ $charset = mysqli_character_set_name($link). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli::character_set_name example Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". Parameters link Return Values The default character set for the current connection Examples Example 3. "world"). printf ("Current character set is %s\n". "my_user". mysqli_character_set_name Returns the default character set for the database connection Description Object oriented style string mysqli::character_set_name(). /* close connection */ mysqli_close($link). 132 . ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". printf ("Current character set is %s\n". "world"). $charset). Procedural style string mysqli_character_set_name( mysqli link). mysqli_connect_error()). exit(). /* check connection */ if (!$link) { printf("Connect failed: %s\n". "my_password". Returns the current character set for the database connection.$charset). } /* Print current character set */ $charset = $mysqli->character_set_name().33. $mysqli->close().mysqli::character_set_name. "my_password".

Return Values A string that represents the MySQL client library version Examples Example 3.9. Returns a string that represents the MySQL client library version. 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". ?> See Also mysqli_get_client_version 133 . mysqli::$client_info.5.34. mysqli_get_client_info()).mysqli::$client_info. [1] • mysqli::$client_info mysqli_get_client_info Get MySQL client info Description Object oriented style string mysqli->client_info . mysqli_get_client_info Copyright 1997-2012 the PHP Documentation Group. mysqli_get_client_info ?> The above examples will output: Current character set is latin1_swedish_ci See Also mysqli_set_charset mysqli_client_encoding mysqli_real_escape_string 3. Procedural style string mysqli_get_client_info( mysqli link).

For example. [1] • mysqli::$client_version mysqli_get_client_version Returns the MySQL client version as a string Description Object oriented style int mysqli->client_version .mysqli::$client_version. 4. Return Values A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version.7.1. 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".6. mysqli::close.35. ?> See Also mysqli_get_client_info mysqli_get_server_info mysqli_get_server_version 3. Examples Example 3. Returns client version number as an integer. [1] • mysqli::close mysqli_close 134 .0 is returned as 40100. mysqli_get_client_version Copyright 1997-2012 the PHP Documentation Group. Procedural style int mysqli_get_client_version( mysqli link). mysqli_get_client_version mysqli_get_server_info mysqli_get_server_version 3. mysqli_get_client_version()). mysqli::$client_version. This is useful to quickly determine the version of the client library to know if some capability exists. mysqli_close Copyright 1997-2012 the PHP Documentation Group.9.9.

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

/* Insert some values */ $mysqli->query("INSERT INTO Language VALUES ('DEU'. } /* set autocommit to off */ mysqli_autocommit($link. "INSERT INTO Language VALUES ('DEU'. mysqli_query($link. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".2)"). 9. "CREATE TABLE Language LIKE CountryLanguage"). 'Swabian'. ?> See Also mysqli_autocommit 136 . exit(). } $mysqli->query("CREATE TABLE Language LIKE CountryLanguage"). 11. "my_password". 'F'.36. /* Insert some values */ mysqli_query($link. 11. mysqli_commit link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure. mysqli::commit example Object oriented style <?php $mysqli = new mysqli("localhost". 'Swabian'. Examples Example 3.4)"). /* check connection */ if (!$link) { printf("Connect failed: %s\n". mysqli_connect_error()). "world"). /* close connection */ $mysqli->close(). "test"). 'F'. /* drop table */ $mysqli->query("DROP TABLE Language"). ?> Procedural style <?php $link = mysqli_connect("localhost". /* commit transaction */ $mysqli->commit(). /* close connection */ mysqli_close($link). /* commit transaction */ mysqli_commit($link).mysqli::commit. 'Bavarian'. "my_user". 9. mysqli_connect_error()). "my_user". "my_password". /* set autocommit to off */ $mysqli->autocommit(FALSE). 'F'.2)"). mysqli_query($link. FALSE). $mysqli->query("INSERT INTO Language VALUES ('DEU'. 'Bavarian'. 'F'. exit(). "INSERT INTO Language VALUES ('DEU'.4)").

$mysqli->connect_errno).37. mysqli::$connect_errno.txt. Note Client error message numbers are listed in the MySQL errmsg. [1] • mysqli::$connect_errno mysqli_connect_errno Returns the error code from last connect call Description Object oriented style string mysqli->connect_errno . 'my_password'. 'fake_user'. 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'. 'my_password'. if (!$link) { die('Connect Error: ' . zero means no error occurred. mysqli_connect_errno mysqli_rollback 3. Procedural style int mysqli_connect_errno(). if it failed. Returns the last error code number from the last call to mysqli_connect. 'fake_user'.9. if ($mysqli->connect_errno) { die('Connect Error: ' . mysqli_connect_errno()). } 137 .9. Examples Example 3. 'my_db'). $mysqli->connect_errno example Object oriented style <?php $mysqli = @new mysqli('localhost'.mysqli::$connect_errno.h header file. mysqli_connect_errno Copyright 1997-2012 the PHP Documentation Group.h. server error message numbers are listed in mysqld_error. Return Values An error code value for the last call to mysqli_connect. 'my_db').

10. Procedural style string mysqli_connect_error(). mysqli::$connect_error.2. 'my_password'. if ($mysqli->connect_error) { die('Connect Error: ' . NULL is returned if no error occurred.mysqli::$connect_error. Returns the last error message string from the last call to mysqli_connect.9 and 5. Return Values A string that describes the error. } ?> 138 . mysqli_connect_error ?> The above examples will output: Connect Error: 1045 See Also mysqli_connect mysqli_connect_error mysqli_errno mysqli_error mysqli_sqlstate 3.9. 'my_db'). $mysqli->connect_error example Object oriented style <?php $mysqli = @new mysqli('localhost'. [1] • mysqli::$connect_error mysqli_connect_error Returns a string description of the last connect error Description Object oriented style string mysqli->connect_error . $mysqli->connect_error). Examples Example 3.0.3.38. mysqli_connect_error Copyright 1997-2012 the PHP Documentation Group. // Works as of PHP 5. 'fake_user'.

mysqli::__construct. mysqli::__construct. string username = =ini_get("mysqli. mysqli_connect_error()).default_host"). if (!$link) { die('Connect Error: ' .2.0. 'my_password'. Use the mysqli_connect_error function if compatibility with earlier PHP versions is required. } ?> The above examples will output: Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES) Notes Warning The mysqli->connect_error property only works properly as of PHP versions 5. See Also mysqli_connect mysqli_connect_errno mysqli_errno mysqli_error mysqli_sqlstate 3.default_user").9.3. 139 . 'my_db').default_pw"). string dbname = ="". mysqli_connect Procedural style <?php $link = @mysqli_connect('localhost'.9 and 5. 'fake_user'.11. [1] • mysqli::__construct mysqli_connect Open a new connection to the MySQL server Description Object oriented style mysqli::__construct( string host = =ini_get("mysqli. string passwd = =ini_get("mysqli. mysqli_connect Copyright 1997-2012 the PHP Documentation Group.

default_socket")). username passwd The MySQL user name.mysqli::__construct. Parameters host Can be either a host name or an IP address. string passwd = =ini_get("mysqli. Changelog dbname port socket 140 . string dbname = ="". int port = =ini_get("mysqli. mysqli_connect int port = =ini_get("mysqli. string username = =ini_get("mysqli. Return Values Returns an object which represents the connection to a MySQL Server. How the connection is made to the MySQL database is determined by the host parameter. Procedural style mysqli mysqli_connect( string host = =ini_get("mysqli.default_port"). If not provided or NULL . Specifies the socket or named pipe that should be used. the MySQL server will attempt to authenticate the user against those user records which have no password only. the local host is assumed. string socket = =ini_get("mysqli.default_host"). Passing the NULL value or the string "localhost" to this parameter.default_pw"). Specifies the port number to attempt to connect to the MySQL server. pipes will be used instead of the TCP/IP protocol. Opens a connection to the MySQL Server running on. If provided will specify the default database to be used when performing queries. Prepending host by p: opens a persistent connection. This allows one username to be used with different permissions (depending on if a password as provided or not). Note Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server.default_port").default_socket")). When possible. string socket = =ini_get("mysqli. mysqli_change_user is automatically called on connections opened from the connection pool.default_user").

$db->host_info . 'my_db'). "\n". ?> Procedural style <?php $link = mysqli_connect('localhost'.3.. echo 'Success.2. $pass. * BUT $connect_error was broken until PHP 5. ') ' . "\n". 'my_user'. ' .. /* * This is the "official" OO way to do it. } } } $db = new foo_mysqli('localhost'. $pass. $db). $mysqli->connect_errno . ?> Object oriented style when extending mysqli class <?php class foo_mysqli extends mysqli { public function __construct($host. ') ' . mysqli_connect_errno() . ' .. ') ' . 'my_password'. mysqli_connect Version 5. 141 . mysqli::__construct example Object oriented style Description Added the ability of persistent connections. $db) { parent::__construct($host.. 'my_password'. mysqli_connect_error()). mysqli_connect_error()). if (mysqli_connect_error()) { die('Connect Error (' .0.9 and 5. */ if (mysqli_connect_error()) { die('Connect Error (' . $user. mysqli_close($link). 'my_password'.mysqli::__construct. "\n". 'my_db').9 and 5. } echo 'Success. 'my_user'. mysqli_connect_error()).3. } /* * Use this instead of $connect_error if you need to ensure * compatibility with PHP versions prior to 5. */ if ($mysqli->connect_error) { die('Connect Error (' . ' . ') ' . $user. 'my_db'). } echo 'Success. if (!$link) { die('Connect Error (' . $mysqli->connect_error). 'my_user'. mysqli_get_host_info($link) .0 Examples Example 3. $mysqli->host_info . mysqli_connect_errno() . $mysqli->close().39. mysqli_connect_errno() .0.. $db->close()..3. <?php $mysqli = new mysqli('localhost'.2.

mysqli::debug.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect.12.. Note Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E.mysqli::debug. MySQL host info: localhost via TCP/IP Notes Note MySQLnd always assumes the server default charset. such as the connection timeout. Libmysql uses the default charset set in the my. On Windows. See Also mysqli_real_connect mysqli_options mysqli_connect_errno mysqli_connect_error mysqli_close 3. This charset is sent during connection hand-shake/authentication. if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. To check if the connection failed then use either the mysqli_connect_error function or the mysqli->connect_error property as in the preceding examples. Note If it is necessary to set options. Note Calling the constructor with no parameters is the same as calling mysqli_init. but after mysqli_init. mysqli_debug ?> The above examples will output: Success.9. mysqli_debug Copyright 1997-2012 the PHP Documentation Group.. which mysqlnd will use. Note OO syntax only: If a connection fails an object is still returned. mysqli_real_connect must be used instead. [1] • mysqli::debug mysqli_debug 142 .

Generating a Trace File <?php /* Create a trace file in '/tmp/client. Notes Note To use the mysqli_debug function you must compile the MySQL client library to support debugging./tmp/client. mysqli::dump_debug_info. mysqli_dump_debug_info Performs debugging operations Description Object oriented style bool mysqli::debug( string message). Examples Example 3. ?> A string representing the debugging operation to perform See Also mysqli_dump_debug_info mysqli_report 3.trace"). Parameters message Return Values Returns TRUE . [1] • mysqli::dump_debug_info mysqli_dump_debug_info Dump debugging information into the log Description 143 .mysqli::dump_debug_info.9.40.13.trace' on the local (client) machine: */ mysqli_debug("d:t:o. mysqli_dump_debug_info Copyright 1997-2012 the PHP Documentation Group. Performs debugging operations using the Fred Fish debugging library. Procedural style bool mysqli_debug( string message).

Client error message numbers are listed in the MySQL errmsg.h header file. server error message numbers are listed in mysqld_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 bool mysqli_dump_debug_info( mysqli link). Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure. [1] • mysqli::$errno mysqli_errno Returns the error code for the most recent function call Description Object oriented style int mysqli->errno . mysqli_errno Object oriented style bool mysqli::dump_debug_info(). Procedural style int mysqli_errno( mysqli link). See Also mysqli_debug 3.h.9. mysqli::$errno.14. Returns the last error code for the most recent MySQLi function call that can succeed or fail.mysqli::$errno. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values 144 . 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. mysqli_errno Copyright 1997-2012 the PHP Documentation Group.txt.

$mysqli->errno). mysqli_connect_error()). Examples Example 3. $mysqli->errno example Object oriented style <?php $mysqli = new mysqli("localhost". $mysqli->connect_error). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "world"). "my_user".mysqli::$error_list. /* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n". } if (!mysqli_query($link. ?> The above examples will output: Errorcode: 1193 See Also mysqli_connect_errno mysqli_connect_error mysqli_error mysqli_sqlstate 3. mysqli_error_list Copyright 1997-2012 the PHP Documentation Group. mysqli::$error_list. exit(). [1] • mysqli::$error_list 145 . mysqli_errno($link)). "world"). if it failed. } /* close connection */ $mysqli->close(). "my_user". "SET a=1")) { printf("Errorcode: %d\n". "my_password". "my_password". zero means no error occurred. } /* close connection */ mysqli_close($link). ?> Procedural style <?php $link = mysqli_connect("localhost".41.15. mysqli_error_list An error code value for the last call.9. } if (!$mysqli->query("SET a=1")) { printf("Errorcode: %d\n". exit().

"nobody". Parameters link Return Values A list of errors.42. ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style <?php $link = mysqli_connect("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } if (!mysqli_query($link. and sqlstate. Procedural style array mysqli_error_list( mysqli link). Examples Example 3. $mysqli->error_list example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_connect_error()). } 146 . each as an associative array containing the errno. Returns a array of errors for the most recent MySQLi function call that can succeed or fail. ""). exit(). "my_password". } /* close connection */ $mysqli->close(). "world"). } if (!$mysqli->query("SET a=1")) { print_r($mysqli->error_list). exit(). "my_user". "SET a=1")) { print_r(mysqli_error_list($link)). error. mysqli_connect_error()).mysqli::$error_list. mysqli_error_list mysqli_error_list Returns a list of errors from the last command executed Description Object oriented style array mysqli->error_list .

An empty string if no error occurred. mysqli_error /* close connection */ mysqli_close($link).mysqli::$error. Procedural style string mysqli_error( mysqli link). Parameters link Return Values A string that describes the error. mysqli_error Copyright 1997-2012 the PHP Documentation Group. mysqli::$error.9.16. [1] • mysqli::$error mysqli_error Returns a string description of the last error Description Object oriented style string mysqli->error . Examples Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 147 . Returns the last error message for the most recent MySQLi function call that can succeed or fail. ?> The above examples will output: Array ( [0] => Array ( [errno] => 1193 [sqlstate] => HY000 [error] => Unknown system variable 'a' ) ) See Also mysqli_connect_errno mysqli_connect_error mysqli_error mysqli_sqlstate 3.

/* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n". mysqli_field_count Copyright 1997-2012 the PHP Documentation Group.17. mysqli::$field_count. } /* close connection */ $mysqli->close(). [1] • mysqli::$field_count mysqli_field_count Returns the number of columns for the most recent query 148 . mysqli_field_count Example 3. } /* close connection */ mysqli_close($link). exit().mysqli::$field_count. mysqli_error($link)). exit(). } if (!mysqli_query($link. } if (!$mysqli->query("SET a=1")) { printf("Errormessage: %s\n". $mysqli->error example Object oriented style <?php $mysqli = new mysqli("localhost". ?> Procedural style <?php $link = mysqli_connect("localhost".43. "SET a=1")) { printf("Errormessage: %s\n". $mysqli->connect_error). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "world"). $mysqli->error). "my_password". "world"). mysqli_connect_error()). "my_user". ?> The above examples will output: Errormessage: Unknown system variable 'a' See Also mysqli_connect_errno mysqli_connect_error mysqli_errno mysqli_sqlstate 3. "my_password".9. "my_user".

'Hartmut'). "DROP TABLE IF EXISTS friends"). mysqli_query($link. Returns the number of columns for the most recent query on the connection represented by the link parameter. mysqli_field_count Description Object oriented style int mysqli->field_count . $mysqli->query( "DROP TABLE IF EXISTS friends"). 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. name varchar(20))"). (2. 'Ulf')"). $mysqli->query( "CREATE TABLE friends (id int. (2. "CREATE TABLE friends (id int. "test"). "my_password". $mysqli->field_count example Object oriented style <?php $mysqli = new mysqli("localhost". /* process resultset */ $row = $result->fetch_row(). Procedural style int mysqli_field_count( mysqli link).'Hartmut'). name varchar(20))"). "my_user". "SELECT * FROM friends"). Examples Example 3. if (mysqli_field_count($link)) { /* this was a select/show or describe query */ 149 . mysqli_query($link.44. $mysqli->query( "INSERT INTO friends VALUES (1. "my_password". /* free resultset */ $result->close(). mysqli_real_query($link. } /* close connection */ $mysqli->close(). "test"). mysqli_query($link. "my_user". ?> Procedural style <?php $link = mysqli_connect("localhost". Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values An integer representing the number of fields in a result set. 'Ulf')"). "INSERT INTO friends VALUES (1.mysqli::$field_count. $mysqli->real_query("SELECT * FROM friends"). if ($mysqli->field_count) { /* this was a select/show or describe query */ $result = $mysqli->store_result().

18. mysqli_get_charset $result = mysqli_store_result($link).mysqli::get_charset. /* free resultset */ mysqli_free_result($result). /* process resultset */ $row = mysqli_fetch_row($result). mysqli::get_charset. [1] • mysqli::get_charset mysqli_get_charset Returns a character set object Description Object oriented style object mysqli::get_charset(). } /* close connection */ mysqli_close($link). mysqli_get_charset Copyright 1997-2012 the PHP Documentation Group. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values The function returns a character set object with the following properties: charset collation dir 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 (?) min_length max_length number state Examples 150 . Procedural style object mysqli_get_charset( mysqli link). ?> 3.9. Returns a character set object providing several properties of the current active character set.

mysqli::get_client_info.9. mysqli_get_client_info Copyright 1997-2012 the PHP Documentation Group. "localhost"."". ?> The above examples will output: object(stdClass)#2 (7) { ["charset"]=> string(6) "latin1" ["collation"]=> string(17) "latin1_swedish_ci" ["dir"]=> string(0) "" ["min_length"]=> int(1) ["max_length"]=> int(1) ["number"]=> int(8) ["state"]=> int(801) } See Also mysqli_character_set_name mysqli_set_charset 3. mysqli::get_client_info. ?> Procedural style <?php $db = mysqli_init(). mysqli::get_charset example Object oriented style <?php $db = mysqli_init()."test"). var_dump($db->get_charset()).19."test")."root". [1] • mysqli::get_client_info mysqli_get_client_info Get MySQL client info Description Object oriented style 151 ."". $db->real_connect("localhost".45. mysqli_get_client_info Example 3."root". mysqli_real_connect($db. var_dump($db->get_charset()).

mysqli_get_client_stats string mysqli::get_client_info(). FALSE otherwise. ?> 152 .20. ?> See Also mysqli_get_client_version mysqli_get_server_info mysqli_get_server_version 3. Procedural style string mysqli_get_client_info( mysqli link). Parameters Return Values Returns an array with client stats if success. mysqli_get_client_info()).47. Returns client per-process statistics. A mysqli_get_client_stats example <?php $link = mysqli_connect(). mysqli_get_client_stats Copyright 1997-2012 the PHP Documentation Group. Available only with mysqlnd. [1] • mysqli_get_client_stats Returns client per-process statistics Description array mysqli_get_client_stats(). Returns a string that represents the MySQL client library version. Examples Example 3.46. 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". print_r(mysqli_get_client_stats()).9. Return Values A string that represents the MySQL client library version Examples Example 3.

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 [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 153 .

mysqli_get_client_stats [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 ) See Also Stats description 154 .

mysqli::$client_version 3. [1] • mysqli::get_connection_stats mysqli_get_connection_stats Returns statistics about the client connection Description Object oriented style 155 .mysqli_get_client_version. mysqli_get_client_version()). [1] • mysqli_get_client_version mysqli::$client_version Returns the MySQL client version as a string Description Object oriented style int mysqli->client_version .48. 4.1. 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 3.9. For example. mysqli_get_connection_stats Copyright 1997-2012 the PHP Documentation Group. Procedural style int mysqli_get_client_version( mysqli link).22. This is useful to quickly determine the version of the client library to know if some capability exits.9.0 is returned as 40100. Returns client version number as an integer. mysqli::get_connection_stats. Examples Example 3. mysqli::$client_version Copyright 1997-2012 the PHP Documentation Group.21. Return Values A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version.

print_r(mysqli_get_connection_stats($link)). Procedural style array mysqli_get_connection_stats( mysqli link).49. A mysqli_get_connection_stats example <?php $link = mysqli_connect(). Returns statistics about the client connection. Examples Example 3.mysqli::get_connection_stats. mysqli_get_connection_stats bool mysqli::get_connection_stats(). FALSE otherwise. Parameters link Return Values Returns an array with connection stats if success. ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 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 156 . Available only with mysqlnd.

mysqli::get_connection_stats. mysqli_get_connection_stats [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 157 .

9. [1] • mysqli::$host_info mysqli_get_host_info Returns a string representing the type of connection used Description Object oriented style string mysqli->host_info . Procedural style string mysqli_get_host_info( mysqli link). mysqli::$host_info. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values A character string representing the server hostname and the connection type. Returns a string describing the connection represented by the link parameter (including the server host name). 158 . mysqli_get_host_info Copyright 1997-2012 the PHP Documentation Group.mysqli::$host_info. mysqli_get_host_info [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 3.23.

mysqli::$protocol_version. "world"). /* close connection */ $mysqli->close(). mysqli_get_proto_info Copyright 1997-2012 the PHP Documentation Group.9.mysqli::$protocol_version. } /* print host information */ printf("Host info: %s\n". $mysqli->host_info example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_connect_error()). } /* print host information */ printf("Host info: %s\n". "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".24. ?> Procedural style <?php $link = mysqli_connect("localhost". mysqli_get_host_info($link)). "my_user". exit(). mysqli_connect_error()). /* close connection */ mysqli_close($link). mysqli_get_proto_info Examples Example 3. ?> The above examples will output: Host info: Localhost via UNIX socket See Also mysqli_get_proto_info 3. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $mysqli->host_info).50. exit(). [1] • mysqli::$protocol_version mysqli_get_proto_info Returns the version of the MySQL protocol used Description Object oriented style 159 . "my_password". "my_password". "my_user".

"my_user". Examples Example 3. } /* print protocol version */ printf("Protocol version: %d\n". ?> The above examples will output: Protocol version: 10 160 . exit(). } /* print protocol version */ printf("Protocol version: %d\n". Parameters link Return Values Returns an integer representing the protocol version. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".mysqli::$protocol_version. "my_password"). mysqli_get_proto_info($link)). /* close connection */ $mysqli->close(). mysqli_connect_error()). mysqli_connect_error()). $mysqli->protocol_version). "my_password"). ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style <?php $link = mysqli_connect("localhost". Procedural style int mysqli_get_proto_info( mysqli link). $mysqli->protocol_version example Object oriented style <?php $mysqli = new mysqli("localhost". exit(). mysqli_get_proto_info string mysqli->protocol_version .51. /* close connection */ mysqli_close($link). Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user".

[1] • mysqli::$server_info mysqli_get_server_info Returns the version of the MySQL server Description Object oriented style string mysqli->server_info . /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Parameters link Return Values A character string representing the server version. Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.9. "my_password"). Examples Example 3. exit(). mysqli_get_server_info See Also mysqli_get_host_info 3. $mysqli->server_info).25. ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style 161 .mysqli::$server_info. } /* print server version */ printf("Server version: %s\n". $mysqli->server_info example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli::$server_info. "my_user". /* close connection */ $mysqli->close(). mysqli_get_server_info Copyright 1997-2012 the PHP Documentation Group. Procedural style string mysqli_get_server_info( mysqli link).52. mysqli_connect_error()).

"my_user".mysqli::$server_version. mysqli::$server_version. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_get_server_info($link)). mysqli_connect_error()). mysqli_get_server_version Copyright 1997-2012 the PHP Documentation Group. exit(). [1] • 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 . Parameters link Return Values An integer representing the server version. The mysqli_get_server_version function returns the version of the server connected to (represented by the link parameter) as an integer.26.1. mysqli_get_server_version <?php $link = mysqli_connect("localhost".9. } /* print server version */ printf("Server version: %s\n". "my_password"). Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 162 . Procedural style int mysqli_get_server_version( mysqli link).2-alpha-debug See Also mysqli_get_client_info mysqli_get_client_version mysqli_get_server_version 3. ?> The above examples will output: Server version: 4. /* close connection */ mysqli_close($link).

"my_password").27. } /* print server version */ printf("Server version: %d\n". mysqli_connect_error()). [1] • mysqli::get_warnings mysqli_get_warnings 163 . "my_password").9. mysqli_get_warnings The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i. ?> The above examples will output: Server version: 40102 See Also mysqli_get_client_info mysqli_get_client_version mysqli_get_server_info 3. /* close connection */ $mysqli->close(). mysqli_connect_error()). exit(). mysqli_get_warnings Copyright 1997-2012 the PHP Documentation Group. /* close connection */ mysqli_close($link).mysqli::get_warnings. ?> Procedural style <?php $link = mysqli_connect("localhost". version 4. Examples Example 3. $mysqli->server_version).53. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".0 is 40100). exit().e. "my_user". $mysqli->server_version example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_get_server_version($link)). mysqli::get_warnings. } /* print server version */ printf("Server version: %d\n".1.

..... In these situations. mysqli_info Get result of SHOW WARNINGS Description Object oriented style mysqli_warning mysqli::get_warnings(). Procedural style mysqli_warning mysqli_get_warnings( mysqli link). The nature of this string is provided below: Table 3. Procedural style string mysqli_info( mysqli link).9..(..). Warning This function is currently not documented..) LOAD DATA INFILE ..(. Possible mysqli_info return values Query type INSERT INTO. UPDATE .28...9. 3.mysqli::$info. only its argument list is available. The mysqli_info function returns a string providing information about the last query executed. mysqli::$info.. ALTER TABLE ..VALUES (. mysqli_info will return an empty string.... mysqli_info Copyright 1997-2012 the PHP Documentation Group. INSERT INTO. Parameters 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 164 .SELECT. Note Queries which do not fall into one of the preceding formats are not supported...). [1] • mysqli::$info mysqli_info Retrieves information about the most recently executed query Description Object oriented style string mysqli->info .

"my_user".. /* INSERT INTO . "world"). } mysqli_query($link. ?> The above examples will output: Records: 150 Duplicates: 0 Warnings: 0 See Also mysqli_affected_rows mysqli_warning_count mysqli_num_rows 165 .mysqli::$info. mysqli_info link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values A character string representing additional information about the most recently executed query. "CREATE TEMPORARY TABLE t1 LIKE City"). /* close connection */ $mysqli->close(). SELECT */ mysqli_query($link. $mysqli->info example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_connect_error()). $mysqli->info). printf("%s\n". "my_user".. } $mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City"). /* close connection */ mysqli_close($link). mysqli_info($link)). SELECT */ $mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150"). mysqli_connect_error()). "my_password". /* INSERT INTO . /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Examples Example 3. "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". ?> Procedural style <?php $link = mysqli_connect("localhost". "my_password". "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150"). exit(). printf("%s\n". exit().54.

mysqli_insert_id Copyright 1997-2012 the PHP Documentation Group. Procedural style mysqli mysqli_init().30. Procedural style 166 . mysqli_init Copyright 1997-2012 the PHP Documentation Group. mysqli_init 3.9.9. See Also mysqli_options mysqli_close mysqli_real_connect mysqli_connect 3. Allocates or initializes a MYSQL object suitable for mysqli_options and mysqli_real_connect. Return Values Returns an object. Examples See mysqli_real_connect. mysqli::$insert_id. [1] • mysqli::$insert_id mysqli_insert_id Returns the auto generated id used in the last query Description Object oriented style mixed mysqli->insert_id . [1] • mysqli::init mysqli_init Initializes MySQLi and returns a resource for use with mysqli_real_connect() Description Object oriented style mysqli mysqli::init().mysqli::init. Note Any subsequent calls to any mysqli function (except mysqli_options) will fail until mysqli_real_connect was called.29. mysqli::init.

mysqli_connect_error()). /* close connection */ $mysqli->close(). Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values The value of the AUTO_INCREMENT field that was updated by the previous query. 617000)". $mysqli->insert_id). mysqli_insert_id mixed mysqli_insert_id( mysqli link). exit(). mysqli_connect_error()). printf ("New Record has id %d. } $mysqli->query("CREATE TABLE myCity LIKE City"). exit().mysqli::$insert_id. ?> Procedural style <?php $link = mysqli_connect("localhost". mysqli_insert_id will return a string. "my_password". If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute. this function will return zero. 167 . The mysqli_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. /* drop table */ $mysqli->query("DROP TABLE myCity"). "my_password". $query = "INSERT INTO myCity VALUES (NULL. "world"). 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. "world"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". 'DEU'. "my_user".55. "my_user". Examples Example 3. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.\n". Note If the number is greater than maximal int value. $mysqli->insert_id example Object oriented style <?php $mysqli = new mysqli("localhost". 'Stuttgart'. $mysqli->query($query). 'Stuttgart'.

mysqli::kill, mysqli_kill

} mysqli_query($link, "CREATE TABLE myCity LIKE City"); $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)"; mysqli_query($link, $query); printf ("New Record has id %d.\n", mysqli_insert_id($link)); /* drop table */ mysqli_query($link, "DROP TABLE myCity"); /* close connection */ mysqli_close($link); ?>

The above examples will output:
New Record has id 1.

3.9.31. mysqli::kill, mysqli_kill
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::kill mysqli_kill Asks the server to kill a MySQL thread Description Object oriented style
bool mysqli::kill( int processid);

Procedural style
bool mysqli_kill( mysqli link, int processid);

This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id function. To stop a running query you should use the SQL command KILL QUERY processid. Parameters link Return Values Returns TRUE on success or FALSE on failure. Examples Example 3.56. mysqli::kill example Object oriented style Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

168

mysqli::more_results, mysqli_more_results

<?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(); } /* determine our thread id */ $thread_id = $mysqli->thread_id; /* Kill connection */ $mysqli->kill($thread_id); /* This should produce an error */ if (!$mysqli->query("CREATE TABLE myCity LIKE City")) { printf("Error: %s\n", $mysqli->error); exit; } /* close connection */ $mysqli->close(); ?>

Procedural style
<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* determine our thread id */ $thread_id = mysqli_thread_id($link); /* Kill connection */ mysqli_kill($link, $thread_id); /* This should produce an error */ if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n", mysqli_error($link)); exit; } /* close connection */ mysqli_close($link); ?>

The above examples will output:
Error: MySQL server has gone away

See Also mysqli_thread_id

3.9.32. mysqli::more_results, mysqli_more_results
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::more_results

169

mysqli::multi_query, mysqli_multi_query

mysqli_more_results Check if there are any more query results from a multi query Description Object oriented style
bool mysqli::more_results();

Procedural style
bool mysqli_more_results( mysqli link);

Indicates if one or more result sets are available from a previous call to mysqli_multi_query. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

Return Values Returns TRUE on success or FALSE on failure. Examples See mysqli_multi_query. See Also mysqli_multi_query mysqli_next_result mysqli_store_result mysqli_use_result

3.9.33. mysqli::multi_query, mysqli_multi_query
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::multi_query mysqli_multi_query Performs a query on the database Description Object oriented style
bool mysqli::multi_query( string query);

Procedural style
bool mysqli_multi_query( mysqli link,

170

mysqli::multi_query, mysqli_multi_query

string query);

Executes one or multiple queries which are concatenated by a semicolon. To retrieve the resultset from the first query you can use mysqli_use_result or mysqli_store_result. All subsequent query results can be processed using mysqli_more_results and mysqli_next_result. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query, as a string. Data inside the query should be properly escaped. Return Values Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result first. Examples Example 3.57. mysqli::multi_query 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(); } $query = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* 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", $row[0]); } $result->free(); } /* print divider */ if ($mysqli->more_results()) { printf("-----------------\n"); } } while ($mysqli->next_result()); } /* close connection */ $mysqli->close(); ?>

query

Procedural style

171

mysqli::next_result, mysqli_next_result

<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if (mysqli_multi_query($link, $query)) { do { /* store first result set */ if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } /* print divider */ if (mysqli_more_results($link)) { printf("-----------------\n"); } } while (mysqli_next_result($link)); } /* close connection */ mysqli_close($link); ?>

The above examples will output something similar to:
my_user@localhost ----------------Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer

See Also mysqli_query mysqli_use_result mysqli_store_result mysqli_next_result mysqli_more_results

3.9.34. mysqli::next_result, mysqli_next_result
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::next_result mysqli_next_result Prepare next result from multi_query Description

172

mysqli::options, mysqli_options

Object oriented style
bool mysqli::next_result();

Procedural style
bool mysqli_next_result( mysqli link);

Prepares next result set from a previous call to mysqli_multi_query which can be retrieved by mysqli_store_result or mysqli_use_result. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init

Return Values Returns TRUE on success or FALSE on failure. Examples See mysqli_multi_query. See Also mysqli_multi_query mysqli_more_results mysqli_store_result mysqli_use_result

3.9.35. mysqli::options, mysqli_options
Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli::options mysqli_options Set options Description Object oriented style
bool mysqli::options( int option, mixed value);

Procedural style
bool mysqli_options( mysqli link, int option, mixed value);

Used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options.

173

mysqli::options, mysqli_options

mysqli_options should be called after mysqli_init and before mysqli_real_connect. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The option that you want to set. It can be one of the following values: Table 3.10. Valid options Name Description

option

MYSQLI_OPT_CONNECT_TIMEOUT connection timeout in seconds (supported on Windows with TCP/ IP since PHP 5.3.1) MYSQLI_OPT_LOCAL_INFILE MYSQLI_INIT_COMMAND MYSQLI_READ_DEFAULT_FILE MYSQLI_READ_DEFAULT_GROUP 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.cnf or the file specified with MYSQL_READ_DEFAULT_FILE . RSA public key file used with the SHA-256 based authentication.

MYSQLI_SERVER_PUBLIC_KEY

value Return Values

The value for the option.

Returns TRUE on success or FALSE on failure. Changelog Version 5.5.0 Description The MYSQLI_SERVER_PUBLIC_KEY option was added.

Examples See mysqli_real_connect. Notes Note MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use. Libmysql uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init.

174

This function can be used by clients that remain idle for a long while. mysqli::ping example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_ping Copyright 1997-2012 the PHP Documentation Group.9. 175 . and global option mysqli.58.reconnect is enabled an automatic reconnection is attempted.36. [1] • mysqli::ping mysqli_ping Pings a server connection. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure. Checks whether the connection to the server is working. mysqli::ping. Procedural style bool mysqli_ping( mysqli link). "my_user". mysqli_ping See Also mysqli_init mysqli_real_connect 3. "my_password". exit(). or tries to reconnect if the connection has gone down Description Object oriented style bool mysqli::ping().mysqli::ping. "world"). If it has gone down. to check whether the server has closed the connection and reconnect if necessary. $mysqli->error). } /* check if server is alive */ if ($mysqli->ping()) { printf ("Our connection is ok!\n"). } else { printf ("Error: %s\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). Examples Example 3.

Procedural style int mysqli_poll( array read. int sec. "my_user". "world"). int sec.9. ?> Procedural style <?php $link = mysqli_connect("localhost". 176 .mysqli::poll. array error. exit(). } else { printf ("Error: %s\n". } /* close connection */ mysqli_close($link). [1] • mysqli::poll mysqli_poll Poll connections Description Object oriented style public int mysqli::poll( array read. array reject. mysqli_error($link)). } /* check if server is alive */ if (mysqli_ping($link)) { printf ("Our connection is ok!\n"). mysqli::poll. mysqli_connect_error()). array error. array reject. "my_password". mysqli_poll } /* close connection */ $mysqli->close(). ?> The above examples will output: Our connection is ok! 3. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". int usec).37. mysqli_poll Copyright 1997-2012 the PHP Documentation Group.

must be non-negative.59. Warning This function is currently not documented. MYSQLI_ASYNC). ?> Number of seconds to wait. $errors. must be non-negative. Number of microseconds to wait. $reject. foreach ($all_links as $link) { $links[] = $errors[] = $reject[] = $link. } } while ($processed < count($all_links)). FALSE otherwise. if (is_object($result)) mysqli_free_result($result). $all_links = array($link1). The above example will output: Array ( [0] => test ) 177 . do { $links = $errors = $reject = array(). The method can be used as static. $processed = 0. mysqli_error($link))). $link1->query("SELECT 'test'". } else die(sprintf("MySQLi Error: %s". Available only with mysqlnd. $processed++. A mysqli_poll example <?php $link1 = mysqli_connect(). Examples Example 3. } if (!mysqli_poll($links. only its argument list is available. Poll connections. } foreach ($links as $link) { if ($result = $link->reap_async_query()) { print_r($result->fetch_row()). 1)) { continue.mysqli::poll. mysqli_poll int usec). Parameters read error reject sec usec Return Values Returns number of ready connections upon success.

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. The query must consist of a single SQL statement. and returns a statement handle to be used for further operations on the statement. string query). as a string. they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row). For example. mysqli_prepare See Also mysqli_query mysqli_reap_async_query 3. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query.38. [1] • mysqli::prepare mysqli_prepare Prepare an SQL statement for execution Description Object oriented style mysqli_stmt mysqli::prepare( string query). Prepares the SQL query. mysqli::prepare. Note The markers are legal only in certain places in SQL statements. query 178 . Note You should not add a terminating semicolon or \g to the statement. Procedural style mysqli_stmt mysqli_prepare( mysqli link.9. mysqli_prepare Copyright 1997-2012 the PHP Documentation Group. or in a comparison with a column in a WHERE clause to specify a comparison value.mysqli::prepare. This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

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

[1] • mysqli::query mysqli_query Performs a query on the database Description Object oriented style mixed mysqli::query( string query. mysqli_query $city = "Amersfoort".39. "SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt. $district). mysqli_query Copyright 1997-2012 the PHP Documentation Group. $city. } /* close connection */ mysqli_close($link). 180 . int resultmode = =MYSQLI_STORE_RESULT). "s". /* execute query */ mysqli_stmt_execute($stmt). Procedural style mixed mysqli_query( mysqli link. /* close statement */ mysqli_stmt_close($stmt).9. int resultmode = =MYSQLI_STORE_RESULT).mysqli::query. $district). /* bind result variables */ mysqli_stmt_bind_result($stmt. $city). ?> 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 3. mysqli::query. printf("%s is in district %s\n". /* create a prepared statement */ if ($stmt = mysqli_prepare($link. /* fetch value */ mysqli_stmt_fetch($stmt). string query.

0 Examples Example 3. Return Values Returns FALSE on failure. Changelog Version 5. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query string. The behavior is as follows: • mysqlnd on Linux returns an error code of 1153.3. The error message means “got a packet bigger than max_allowed_packet bytes”. mysqli::query example Object oriented style Description Added the ability of async queries. resultmode Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. • mysqlnd on Windows returns an error code 2006. mysqli_poll is then used to get results from such queries. Note In the case where you pass a statement to mysqli_query that is longer than max_allowed_packet of the server. mysqli_query Performs a query against the database. For successful SELECT. query 181 . For other successful queries mysqli_query will return TRUE . This error message means “server has gone away”. MYSQLI_STORE_RESULT is used.61. 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). SHOW. This error message means “server has gone away”. DESCRIBE or EXPLAIN queries mysqli_query will return a mysqli_result object.mysqli::query. By default. the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). using this function is identical to calling mysqli_real_query followed either by mysqli_use_result or mysqli_store_result. Functionally. it is possible to perform query asynchronously. • libmysql on all platforms returns an error code 2006. Data inside the query should be properly escaped.

mysqli::query. /* free result set */ mysqli_free_result($result). /* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n". that we can't execute any functions which interact with the server until result set was closed. "SELECT Name FROM City LIMIT 10")) { printf("Select returned %d rows. ?> 182 . } mysqli_close($link). "world"). "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) { printf("Table myCity successfully created.\n".\n"). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $result->num_rows). "SET @a:='this will not work'")) { printf("Error: %s\n".\n". } mysqli_free_result($result). "my_password". $mysqli->connect_error). exit(). "my_password". "SELECT * FROM City". that we can't execute any functions which interact with the server until result set was closed. } $result->close(). $mysqli->error). mysqli_error($link)). MYSQLI_USE_RESULT)) { /* Note. mysqli_connect_error()). ?> Procedural style <?php $link = mysqli_connect("localhost". All calls will return an 'out of sync' error */ if (!mysqli_query($link. "my_user". mysqli_num_rows($result)). } /* Create table doesn't return a resultset */ if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) { printf("Table myCity successfully created. } /* Select queries return a resultset */ if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) { printf("Select returned %d rows. /* free result set */ $result->close(). exit(). } /* Create table doesn't return a resultset */ if (mysqli_query($link. mysqli_query <?php $mysqli = new mysqli("localhost". MYSQLI_USE_RESULT)) { /* Note.\n"). } /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ if ($result = mysqli_query($link. } $mysqli->close(). All calls will return an 'out of sync' error */ if (!$mysqli->query("SET @a:='this will not work'")) { printf("Error: %s\n". "world"). "my_user". } /* 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("SELECT * FROM City".

Parameters 183 . Error: Commands out of sync. [1] • mysqli::real_connect mysqli_real_connect Opens a connection to a mysql server Description Object oriented style bool mysqli::real_connect( string host. int port. Procedural style bool mysqli_real_connect( mysqli link. Select returned 10 rows. string passwd. int flags). string passwd. string dbname.40. string socket. string username. string socket. mysqli::real_connect. string dbname. • With the mysqli_options function you can set various options for connection. This function differs from mysqli_connect: • mysqli_real_connect needs a valid object which has to be created by function mysqli_init. string host. You can't run this command now See Also mysqli_real_query mysqli_multi_query mysqli_free_result 3.mysqli::real_connect. mysqli_real_connect The above examples will output: Table myCity successfully created.9. mysqli_real_connect Copyright 1997-2012 the PHP Documentation Group. Establish a connection to a MySQL database engine. int port. string username. int flags). • There is a flags parameter.

This allows one username to be used with different permissions (depending on if a password as provided or not). When possible. The MySQL user name. Supported flags Name MYSQLI_CLIENT_COMPRESS MYSQLI_CLIENT_FOUND_ROWS Description Use compression protocol return number of matched rows. the local host is assumed. pipes will be used instead of the TCP/IP protocol. Passing the NULL value or the string "localhost" to this parameter. host username passwd dbname port socket flags With the parameter flags you can set different connection options: Table 3. Note Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. If provided or NULL . Specifies the port number to attempt to connect to the MySQL server. Specifies the socket or named pipe that should be used. mysqli_real_connect link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Can be either a host name or an IP address. not the number of affected rows MYSQLI_CLIENT_IGNORE_SPACE Allow spaces after function names. If provided will specify the default database to be used when performing queries. If you want to execute multiple queries use the mysqli_multi_query function. Return Values 184 .11. MYSQLI_CLIENT_INTERACTIVE Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection Use SSL (encryption) MYSQLI_CLIENT_SSL Note For security reasons the MULTI_STATEMENT flag is not supported in PHP. the MySQL server will attempt to authenticate the user against those user records which have no password only.mysqli::real_connect. How the connection is made to the MySQL database is determined by the host parameter. Makes all function names reserved words.

' . 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'). ?> Procedural style <?php $link = mysqli_init(). 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'). $db) { parent::init(). } if (!$mysqli->options(MYSQLI_INIT_COMMAND. ' . ') ' . mysqli_connect_errno() . 'my_user'. $pass. } if (!mysqli_options($link. 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed'). 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed').62.. 'my_user'. $db->host_info . if (!$mysqli) { die('mysqli_init failed'). } } } $db = new foo_mysqli('localhost'. if (!$link) { die('mysqli_init failed'). "\n". $mysqli->close(). } if (!$mysqli->real_connect('localhost'. $db)) { die('Connect Error (' . 185 . if (!parent::options(MYSQLI_INIT_COMMAND. mysqli_connect_errno() . "\n". } if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT. $user. 'my_db')) { die('Connect Error (' . Examples Example 3.. 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed'). $user. MYSQLI_INIT_COMMAND. } if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT. mysqli_connect_error()). mysqli::real_connect example Object oriented style <?php $mysqli = mysqli_init(). mysqli_connect_error()). echo 'Success. 'my_password'. } echo 'Success.. } if (!parent::real_connect($host. 'my_password'. 'my_db'). $db->close(). ') ' . $mysqli->host_info .mysqli::real_connect. $pass. ?> Object oriented style when extending mysqli class <?php class foo_mysqli extends mysqli { public function __construct($host. mysqli_real_connect Returns TRUE on success or FALSE on failure..

9. [1] • mysqli::real_escape_string mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement.. Libmysql uses the default charset set in the my.. mysqli_connect_errno() .. but after mysqli_init. mysqli_close($link). ' . which mysqlnd will use. ') ' . string mysqli::real_escape_string( string escapestr). mysqli_connect_error()). 'my_user'. mysqli_get_host_info($link) . MySQL host info: localhost via TCP/IP Notes Note MySQLnd always assumes the server default charset. mysqli_real_escape_string Copyright 1997-2012 the PHP Documentation Group. 'localhost'. This charset is sent during connection hand-shake/authentication. mysqli_real_escape_string } if (!mysqli_options($link. 186 . } echo 'Success. 'my_password'.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect.41. 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed').. ?> The above examples will output: Success. 'my_db')) { die('Connect Error (' . } if (!mysqli_real_connect($link. taking into account the current charset of the connection Description Object oriented style string mysqli::escape_string( string escapestr). mysqli::real_escape_string. "\n".mysqli::real_escape_string. MYSQLI_OPT_CONNECT_TIMEOUT. See Also mysqli_connect mysqli_init mysqli_options mysqli_ssl_set mysqli_close 3.

$city = "'s Hertogenbosch". } $mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"). string escapestr). $mysqli->affected_rows). or with the API function mysqli_set_charset for it to affect mysqli_real_escape_string. Characters encoded are NUL (ASCII 0).63. /* this query will fail. Security: the default character set The character set must be set either at the server level.\n". mysqli::real_escape_string example Object oriented style <?php $mysqli = new mysqli("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". cause we didn't escape $city */ if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n". '. "world"). and Control-Z. $mysqli->sqlstate). This function is used to create a legal SQL string that you can use in an SQL statement. ". \. } $mysqli->close(). The given string is encoded to an escaped SQL string. Examples Example 3. mysqli_real_escape_string Procedural style string mysqli_real_escape_string( mysqli link. ?> escapestr Procedural style 187 .mysqli::real_escape_string. "my_password". \r. taking into account the current character set of the connection. exit(). See the concepts section on character sets for more information. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The string to be escaped. \n. /* this query with escaped $city will work */ if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted. Return Values Returns an escaped string. "my_user". mysqli_connect_error()). } $city = $mysqli->real_escape_string($city).

188 .42. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "CREATE TEMPORARY TABLE myCity LIKE City"). Notes Note For those accustomed to using mysql_real_escape_string. [1] • mysqli::real_query mysqli_real_query Execute an SQL query Description Object oriented style bool mysqli::real_query( string query). exit(). /* this query with escaped $city will work */ if (mysqli_query($link. note that the arguments of mysqli_real_escape_string differ from what mysql_real_escape_string expects. mysqli_sqlstate($link)). mysqli_affected_rows($link)). The link identifier comes first in mysqli_real_escape_string. /* this query will fail. mysqli_real_query <?php $link = mysqli_connect("localhost". } mysqli_close($link). $city). mysqli_connect_error()). $city = "'s Hertogenbosch". whereas the string to be escaped comes first in mysql_real_escape_string. } $city = mysqli_real_escape_string($link. } mysqli_query($link. ?> The above examples will output: Error: 42000 1 Row inserted. cause we didn't escape $city */ if (!mysqli_query($link. "world"). mysqli_real_query Copyright 1997-2012 the PHP Documentation Group. "INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted. "INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n". "my_user".9. "my_password".\n". See Also mysqli_set_charset mysqli_character_set_name 3. mysqli::real_query.mysqli::real_query.

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result or mysqli_use_result functions. string query). In order to determine if a given query should return a result set or not. see mysqli_field_count. Warning This function is currently not documented. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The query. Data inside the query should be properly escaped. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 189 . Available only with mysqlnd.9. [1] • mysqli::reap_async_query mysqli_reap_async_query Get result from async query Description Object oriented style public mysqli_result mysqli::reap_async_query(). See Also mysqli_query mysqli_store_result mysqli_use_result query 3. mysqli_reap_async_query Procedural style bool mysqli_real_query( mysqli link. as a string. Get result from async query. Return Values Returns TRUE on success or FALSE on failure. mysqli::reap_async_query. mysqli_reap_async_query Copyright 1997-2012 the PHP Documentation Group.43. only its argument list is available.mysqli::reap_async_query. Procedural style mysqli_result mysqli_reap_async_query( mysql link).

int options). mysqli_rollback Copyright 1997-2012 the PHP Documentation Group. Flushes tables or caches.mysqli::refresh. using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation. See Also mysqli_poll 3.45. mysqli_refresh Copyright 1997-2012 the PHP Documentation Group. mysqli::rollback. mysqli_refresh Return Values Returns mysqli_result in success. See also the official MySQL Refresh documentation.44. or resets the replication server information. Procedural style int mysqli_refresh( resource link. FALSE otherwise. [1] • mysqli::refresh mysqli_refresh Refreshes Description Object oriented style public bool mysqli::refresh( int options).9. otherwise FALSE See Also mysqli_poll options 3. Return Values TRUE if the refresh was a success. [1] • mysqli::rollback mysqli_rollback Rolls back current transaction 190 .9. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The options to refresh. mysqli::refresh.

/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Rollbacks the current transaction for the database.\n". Parameters link Return Values Returns TRUE on success or FALSE on failure. ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 191 . $row[0]).mysqli::rollback. } /* Drop table myCity */ $mysqli->query("DROP TABLE myCity").\n". mysqli_rollback Description Object oriented style bool mysqli::rollback(). Examples Example 3. } /* Rollback */ $mysqli->rollback(). Procedural style bool mysqli_rollback( mysqli link). $mysqli->close(). "my_user". $mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50"). } /* disable autocommit */ $mysqli->autocommit(FALSE). /* delete all rows */ $mysqli->query("DELETE FROM myCity"). $mysqli->query("CREATE TABLE myCity LIKE City"). mysqli::rollback example Object oriented style <?php $mysqli = new mysqli("localhost". exit(). "world"). $row[0]). $mysqli->query("ALTER TABLE myCity Type=InnoDB"). if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(). /* Free result */ $result->close(). "my_password". mysqli_connect_error()). if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(). printf("%d rows in table myCity. /* Free result */ $result->close().64. /* commit insert */ $mysqli->commit(). printf("%d rows in table myCity (after rollback).

46. mysqli_query($link.mysqli::rpl_query_type. ?> The above examples will output: 0 rows in table myCity. $row[0]). "my_password". "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result). mysqli_connect_error()). "DELETE FROM myCity"). if ($result = mysqli_query($link. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". if ($result = mysqli_query($link. printf("%d rows in table myCity (after rollback). /* delete all rows */ mysqli_query($link. $row[0]). mysqli_close($link). mysqli_rpl_query_type Procedural style <?php $link = mysqli_connect("localhost". "INSERT INTO myCity SELECT * FROM City LIMIT 50"). mysqli_rpl_query_type Copyright 1997-2012 the PHP Documentation Group. } /* disable autocommit */ mysqli_autocommit($link.\n". "my_user". mysqli_query($link. /* commit insert */ mysqli_commit($link). "ALTER TABLE myCity Type=InnoDB"). mysqli::rpl_query_type. } /* Drop table myCity */ mysqli_query($link. "CREATE TABLE myCity LIKE City"). "SELECT COUNT(*) FROM myCity")) { $row = mysqli_fetch_row($result). See Also mysqli_commit mysqli_autocommit 3.\n". /* Free result */ mysqli_free_result($result). } /* Rollback */ mysqli_rollback($link). /* Free result */ mysqli_free_result($result). [1] • mysqli::rpl_query_type mysqli_rpl_query_type Returns RPL query type Description 192 . "world").9. FALSE). mysqli_query($link. 50 rows in table myCity (after rollback). printf("%d rows in table myCity. "DROP TABLE myCity"). exit().

only its argument list is available. Note This function should only be used to change the default database for the connection. 3. MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. string query). You can select the default database with 4th parameter in mysqli_connect. SELECT is slave. Procedural style bool mysqli_select_db( mysqli link. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The database name. string dbname).0. Returns MYSQLI_RPL_MASTER .47. Selects the default database to be used when performing queries against the database connection. REPAIR and similar are admin.3.9. Warning This function is currently not documented. mysqli_select_db Object oriented style int mysqli::rpl_query_type( string query). and FLUSH. dbname 193 . mysqli_select_db Copyright 1997-2012 the PHP Documentation Group.mysqli::select_db. [1] • mysqli::select_db mysqli_select_db Selects the default database for database queries Description Object oriented style bool mysqli::select_db( string dbname). INSERT. Warning This function has been DEPRECATED and REMOVED as of PHP 5. Procedural style int mysqli_rpl_query_type( mysqli link. UPDATE and similar are master queries. mysqli::select_db.

"test"). } /* return name of current default database */ if ($result = $mysqli->query("SELECT DATABASE()")) { $row = $result->fetch_row().\n". mysqli_free_result($result). } /* change db to world db */ $mysqli->select_db("world"). printf("Default database is %s. $result->close(). Examples Example 3. "my_user". mysqli_connect_error()). ?> 194 .mysqli::select_db. "SELECT DATABASE()")) { $row = mysqli_fetch_row($result). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". $row[0]). "my_password". $result->close(). /* return name of current default database */ if ($result = mysqli_query($link.\n". "my_user".\n". } $mysqli->close(). exit(). "SELECT DATABASE()")) { $row = mysqli_fetch_row($result). "my_password". mysqli_select_db Return Values Returns TRUE on success or FALSE on failure. printf("Default database is %s. exit(). mysqli::select_db example Object oriented style <?php $mysqli = new mysqli("localhost". } mysqli_close($link). "test").65. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "world"). mysqli_free_result($result). } /* change db to world db */ mysqli_select_db($link. /* return name of current default database */ if ($result = $mysqli->query("SELECT DATABASE()")) { $row = $result->fetch_row(). mysqli_connect_error()). $row[0]). $row[0]).\n". } /* return name of current default database */ if ($result = mysqli_query($link. $row[0]). printf("Default database is %s. ?> Procedural style <?php $link = mysqli_connect("localhost". printf("Default database is %s.

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

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

9. [1] • 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).mysqli::set_local_infile_default. mysqli_set_local_infile_default if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler. } else { printf("Current character set: %s\n". mysqli_set_local_infile_default Copyright 1997-2012 the PHP Documentation Group.50. ?> 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 3. mysqli_character_set_name($link)). Examples See mysqli_set_local_infile_handler examples See Also Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 197 . } mysqli_close($link). mysqli_error($link)). exit(). } /* change character set to utf8 */ if (!mysqli_set_charset($link. mysqli::set_local_infile_default. "utf8")) { printf("Error loading character set utf8: %s\n". Parameters link Return Values No value is returned.

callable read_func). mysqli::set_local_infile_handler.9. Return Values Returns TRUE on success or FALSE on failure.51.mysqli::set_local_infile_handler. The returned data needs to match the format specified in the LOAD DATA Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init A callback function or object method taking the following parameters: stream 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 read_func &buffer buflen &errormsg The callback function should return the number of characters stored in the buffer or a negative value if an error occurred. [1] • 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. mysqli_set_local_infile_handler Copyright 1997-2012 the PHP Documentation Group. 198 . 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. Procedural style bool mysqli_set_local_infile_handler( mysqli link. mysqli_set_local_infile_handler mysqli_set_local_infile_handler 3. callable read_func).

return strlen($buffer). "LOAD DATA LOCAL INFILE 'input."test"). $row). &$errmsg) { $buffer = fgets($stream). "localhost"."". $row). function callme($stream. } echo "Input:\n". $buffer)).mysqli::set_local_infile_handler. echo $buffer. $res = mysqli_query($db." delimiter with [TAB] $buffer = strtoupper(str_replace(". } echo "Input:\n". function callme($stream. while ($row = $res->fetch_assoc()) { echo join(". while ($row = mysqli_fetch_assoc($res)) { echo join(". &$buffer. "callme")."."test"). } ?> Procedural style <?php $db = mysqli_init(). mysqli_set_local_infile_handler Examples Example 3.txt' INTO TABLE t1"). $db->set_local_infile_handler("callme").". $db->query("LOAD DATA LOCAL INFILE 'input. mysqli_set_local_infile_handler($db. &$errmsg) { $buffer = fgets($stream). echo "\nResult:\n"." delimiter with [TAB] $buffer = strtoupper(str_replace(".67. } ?> The above examples will output: Input: 23. $db->real_connect("localhost". "SELECT * FROM t1")."". "\t".foo 42. $db->set_local_infile_default().". return strlen($buffer). &$buffer. echo $buffer.bar Output: 23. "\t".FOO 199 . mysqli::set_local_infile_handler example Object oriented style <?php $db = mysqli_init(). $res = $db->query("SELECT * FROM t1"). // convert to upper case and replace ".txt' INTO TABLE t1")."\n"."root". $buffer))."root". $buflen. // convert to upper case and replace ". mysqli_set_local_infile_default($db)."."\n". $buflen. echo "\nResult:\n". mysqli_query($db. mysqli_real_connect($db.

[1] • mysqli::$sqlstate mysqli_sqlstate Returns the SQLSTATE error from previous MySQL operation Description Object oriented style string mysqli->sqlstate . "my_password".68. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".html.mysql.BAR See Also mysqli_set_local_infile_default 3.52. Parameters link Return Values Returns a string containing the SQLSTATE error code for the last error. Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 200 . see http://dev. Returns a string containing the SQLSTATE error code for the last error. Examples Example 3.com/doc/mysql/en/error-handling. The value HY000 (general error) is used for unmapped errors. For a list of possible values. mysqli_connect_error()). $mysqli->sqlstate example Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_sqlstate 42. mysqli_sqlstate Copyright 1997-2012 the PHP Documentation Group.9. "my_user". Procedural style string mysqli_sqlstate( mysqli link). The values are specified by ANSI SQL and ODBC. The error code consists of five characters. mysqli::$sqlstate. '00000' means no error. '00000' means no error. Note Note that not all MySQL errors are yet mapped to SQLSTATE's. "world").mysqli::$sqlstate. The error code consists of five characters.

exit(). $mysqli->sqlstate). mysqli_ssl_set Copyright 1997-2012 the PHP Documentation Group. "my_password". mysqli::ssl_set. Procedural style 201 .53. mysqli_ssl_set exit(). string capath.SQLSTATE %s. } /* Table City already exists.mysqli::ssl_set. Name VARCHAR(30))")) { printf("Error . string cert. mysqli_connect_error()). ?> The above examples will output: Error . /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". See Also mysqli_errno mysqli_error 3. string ca. so we should get an error */ if (!$mysqli->query("CREATE TABLE City (ID INT. mysqli_sqlstate($link)). [1] • mysqli::ssl_set mysqli_ssl_set Used for establishing secure connections using SSL Description Object oriented style bool mysqli::ssl_set( string key. "world"). so we should get an error */ if (!mysqli_query($link. } $mysqli->close().SQLSTATE %s. } /* Table City already exists. Name VARCHAR(30))")) { printf("Error . "my_user".\n". } mysqli_close($link).\n".9. string cipher).SQLSTATE 42S01. "CREATE TABLE City (ID INT. ?> Procedural style <?php $link = mysqli_connect("localhost".

A list of allowable ciphers to use for SSL encryption. string cipher). mysqli::stat.9.mysqli::stat. It must be called before mysqli_real_connect. string cert. See Also mysqli_options mysqli_real_connect 3. Parameters link Procedural style only: A link identifier returned by mysqli_connect or mysqli_init The path name to the key file. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5. This function does nothing unless OpenSSL support is enabled. string capath. The path name to the certificate file. [1] • mysqli::stat mysqli_stat Gets the current system status Description Object oriented style string mysqli::stat().3. Procedural style 202 . Note that MySQL Native Driver does not support SSL before PHP 5. If SSL setup is incorrect mysqli_real_connect will return an error when you attempt to connect.3 onwards. string key.54.3. string ca. so calling this function when using MySQL Native Driver will result in an error. mysqli_stat bool mysqli_ssl_set( mysqli link. Used for establishing secure connections using SSL. The path name to the certificate authority file. key cert ca capath cipher Any unused SSL parameters may be given as NULL Return Values This function always returns TRUE value. The pathname to a directory that contains trusted SSL CA certificates in PEM format. mysqli_stat Copyright 1997-2012 the PHP Documentation Group.

$mysqli->close(). mysqli_connect_error()). and open tables. FALSE if an error occurred. questions. exit(). "world"). ?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style <?php $link = mysqli_connect("localhost". mysqli_stat returns a string containing information similar to that provided by the 'mysqladmin status' command. $mysqli->stat()). Examples Example 3. "world").mysqli::stat. "my_user". "my_password". mysqli_connect_error()).69. Parameters link Return Values A string describing the server status. mysqli_stat($link)). "my_password". reloads. exit().632 Memory in use: 8496K Max memory used: 8560K See Also mysqli_get_server_info 203 . } printf("System status: %s\n". This includes uptime in seconds and the number of running threads. mysqli_close($link). mysqli_stat string mysqli_stat( mysqli link). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". } printf ("System status: %s\n". ?> 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. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli::stat example Object oriented style <?php $mysqli = new mysqli("localhost".

See Also mysqli_stmt_prepare Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 3. Note Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare was called.9. Procedural style mysqli_stmt mysqli_stmt_init( mysqli link). Parameters link Return Values Returns an object.mysqli::stmt_init. [1] • mysqli::store_result mysqli_store_result Transfers a result set from the last query Description Object oriented style mysqli_result mysqli::store_result(). Allocates and initializes a statement object suitable for mysqli_stmt_prepare.56.9. mysqli::stmt_init. [1] • 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(). Procedural style mysqli_result mysqli_store_result( 204 . mysqli::store_result.55. mysqli_stmt_init Copyright 1997-2012 the PHP Documentation Group. mysqli_stmt_init 3. mysqli_store_result Copyright 1997-2012 the PHP Documentation Group.

when transferring large result sets using the mysqli_store_result this becomes particularly important. 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. 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. 205 .mysqli::$thread_id. the statement should have produced a non-empty result set. mysqli::$thread_id. See Also mysqli_real_query mysqli_use_result Procedural style only: A link identifier returned by mysqli_connect or mysqli_init 3. You can check if you have got an error by checking if mysqli_error doesn't return an empty string. This function also returns FALSE if the reading of the result set failed. If mysqli_field_count returns a non-zero value. Note mysqli_store_result returns FALSE in case the query didn't return a result set (if the query was. mysqli_thread_id mysqli link). 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). Parameters link Return Values Returns a buffered result object or FALSE if an error occurred. for example an INSERT statement). or if mysqli_field_count returns a non zero value.9. [1] • mysqli::$thread_id mysqli_thread_id Returns the thread ID for the current connection Description Object oriented style int mysqli->thread_id .57. Examples See mysqli_multi_query. if mysqli_errno returns a non zero value. mysqli_thread_id Copyright 1997-2012 the PHP Documentation Group.

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

mysqli_use_result Copyright 1997-2012 the PHP Documentation Group.59. } /* close connection */ mysqli_close($link). [1] • mysqli::use_result mysqli_use_result Initiate a result set retrieval Description Object oriented style 207 . "CREATE TABLE myCity LIKE City")) { printf("Error: %s\n". mysqli::thread_safe. /* This should produce an error */ if (!mysqli_query($link.9. exit. /* Kill connection */ mysqli_kill($link. 3. Return Values TRUE if the client library is thread-safe. $thread_id). mysqli_error($link)).9.58. [1] • mysqli::thread_safe mysqli_thread_safe Returns whether thread safety is given or not Description Procedural style bool mysqli_thread_safe(). mysqli_thread_safe Copyright 1997-2012 the PHP Documentation Group. ?> The above examples will output: Error: MySQL server has gone away See Also mysqli_kill 3. Tells whether the client library is compiled as thread-safe.mysqli::thread_safe. otherwise FALSE . mysqli::use_result. mysqli_thread_safe } /* determine our thread id */ $thread_id = mysqli_thread_id($link).

} $query = "SELECT CURRENT_USER(). 5".". To use this functionality. Return Values Returns an unbuffered result object or FALSE if an error occurred. mysqli_use_result mysqli_result mysqli::use_result(). mysqli_connect_error()). and one or the other must be called to prevent the next query on that database connection from failing. Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query function on the database connection. /* 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()) { printf("-----------------\n").= "SELECT Name FROM City ORDER BY ID LIMIT 20. since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched. "my_password". ?> 208 . Either this or the mysqli_store_result function must be called before the results of a query can be retrieved. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "world"). "my_user".mysqli::use_result. mysqli::use_result example Object oriented style <?php $mysqli = new mysqli("localhost". 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 . } } while ($mysqli->next_result()). } $result->close(). Procedural style mysqli_result mysqli_use_result( mysqli link). } /* close connection */ $mysqli->close().71. the result set must be stored using mysqli_store_result. One should not use mysqli_use_result if a lot of processing on the client side is performed. exit(). Examples Example 3. $row[0]).

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

?> Procedural style only: A link identifier returned by mysqli_connect or mysqli_init Procedural style <?php 210 . if ($mysqli->warning_count) { if ($result = $mysqli->query("SHOW WARNINGS")) { $row = $result->fetch_row(). /* a remarkable city in Wales */ $query = "INSERT INTO myCity (CountryCode. printf("%s (%d): %s\n". Returns the number of warnings from the last query in the connection. $mysqli->query($query). $row[0]. "my_password". mysqli_connect_error()). } } /* close connection */ $mysqli->close(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } $mysqli->query("CREATE TABLE myCity LIKE City").mysqli::$warning_count. $row[1]. $result->close(). "world"). Note For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count]. exit(). $row[2]). Name) VALUES('GBR'. mysqli_warning_count Description Object oriented style int mysqli->warning_count . Procedural style int mysqli_warning_count( mysqli link).72. 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')". "my_user". Parameters link Return Values Number of warnings or zero if there are no warnings. Examples Example 3. $mysqli->warning_count example Object oriented style <?php $mysqli = new mysqli("localhost".

mysqli_query($link.The mysqli_stmt class (mysqli_stmt) $link = mysqli_connect("localhost". The mysqli_stmt class (mysqli_stmt) Copyright 1997-2012 the PHP Documentation Group. "my_password". 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')". int mysqli_stmt->errno . $row[2]).10. } mysqli_query($link. ?> The above examples will output: Warning (1264): Data truncated for column 'Name' at row 1 See Also mysqli_errno mysqli_error mysqli_sqlstate 3. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". [1] Represents a prepared statement. "SHOW WARNINGS")) { $row = mysqli_fetch_row($result). if (mysqli_warning_count($link)) { if ($result = mysqli_query($link. } } /* close connection */ mysqli_close($link). string mysqli_stmt->error . Name) VALUES('GBR'. $row[1]. printf("%s (%d): %s\n". mysqli_connect_error()). int mysqli_stmt->field_count . mysqli_free_result($result). exit(). "my_user". $query). int 211 . mysqli_stmt { mysqli_stmt Properties int mysqli_stmt->affected_rows . /* a remarkable long city name in Wales */ $query = "INSERT INTO myCity (CountryCode. "CREATE TABLE myCity LIKE City"). $row[0]. array mysqli_stmt->error_list . "world").

} 3. bool mysqli_stmt::reset(). bool mysqli_stmt::bind_result( mixed var1. bool mysqli_stmt::bind_param( string types. string data). int mysqli_stmt->num_rows . int mode). object mysqli_stmt::get_warnings( mysqli_stmt stmt). [1] • mysqli_stmt::$affected_rows mysqli_stmt_affected_rows 212 . void mysqli_stmt::free_result().. int mysqli_stmt->param_count . bool mysqli_stmt::close(). mixed var1. mixed . bool mysqli_stmt::send_long_data( int param_nr. bool mysqli_stmt::attr_set( int attr... Methods int mysqli_stmt::attr_get( int attr). string mysqli_stmt->sqlstate . void mysqli_stmt::data_seek( int offset).1.. mysqli_result mysqli_stmt::result_metadata().).). mysqli_stmt_affected_rows mysqli_stmt->insert_id . mysqli_result mysqli_stmt::get_result(). bool mysqli_stmt::execute(). bool mysqli_stmt::fetch(). mixed mysqli_stmt::prepare( string query). bool mysqli_stmt::store_result().mysqli_stmt::$affected_rows.10. mysqli_stmt_affected_rows Copyright 1997-2012 the PHP Documentation Group. mixed . mysqli_stmt::$affected_rows.

} /* create temp table */ $mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country"). } Procedural style only: A statement identifier returned by mysqli_stmt_init. mysqli_stmt_affected_rows Returns the total number of rows changed. /* execute statement */ $stmt->execute(). or inserted by the last executed statement Description Object oriented style int mysqli_stmt->affected_rows . $query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?". UPDATE. mysqli_connect_error()). no rows matched the WHERE clause in the query or that no query has yet been executed. $stmt->bind_param("s". 213 . /* prepare statement */ if ($stmt = $mysqli->prepare($query)) { /* Bind variable for placeholder */ $code = 'A%'. Zero indicates that no records where updated for an UPDATE/DELETE statement. "world"). deleted. use mysqli_stmt_num_rows instead. or DELETE query. $code).73. exit(). "my_user". /* close statement */ $stmt->close(). In order to get the number of rows from a SELECT query. the number of affected rows will be returned as a string value. -1 indicates that the query has returned an error. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". This function only works with queries which update a table. Note If the number of affected rows is greater than maximal PHP int value. Procedural style int mysqli_stmt_affected_rows( mysqli_stmt stmt). $stmt->affected_rows). Examples Example 3. NULL indicates an invalid argument was supplied to the function. printf("rows inserted: %d\n". Parameters stmt Return Values An integer greater than zero indicates the number of rows affected or retrieved. "my_password". Returns the number of rows affected by INSERT. Object oriented style <?php $mysqli = new mysqli("localhost".mysqli_stmt::$affected_rows.

/* close statement */ mysqli_stmt_close($stmt). mysqli_stmt_affected_rows($stmt)). ?> Example 3. mysqli_stmt::attr_get. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } /* close connection */ mysqli_close($link). mysqli_stmt_bind_param($stmt. "world"). /* prepare statement */ if ($stmt = mysqli_prepare($link. } /* create temp table */ mysqli_query($link. ?> The above examples will output: rows inserted: 17 See Also mysqli_stmt_num_rows mysqli_prepare 3.mysqli_stmt::attr_get. "CREATE TEMPORARY TABLE myCountry LIKE Country"). "my_password". $query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?". $query)) { /* Bind variable for placeholder */ $code = 'A%'. Procedural style <?php $link = mysqli_connect("localhost". exit(). mysqli_connect_error()). "s".2. 214 . [1] • 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). /* execute statement */ mysqli_stmt_execute($stmt). mysqli_stmt_attr_get /* close connection */ $mysqli->close().10. $code).74. "my_user". printf("rows inserted: %d\n". mysqli_stmt_attr_get Copyright 1997-2012 the PHP Documentation Group.

otherwise returns the value of the attribute. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. int mode). The attribute that you want to set. [1] • 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. The attribute that you want to get.12.mysqli_stmt::attr_set. int attr). It can have one of the following values: Table 3. Procedural style bool mysqli_stmt_attr_set( mysqli_stmt stmt. Used to modify the behavior of a prepared statement. mysqli_stmt::attr_set. 3. Attribute values Character Description attr MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH If set to 1. Gets the current value of a statement attribute. mysqli_stmt_attr_set Procedural style int mysqli_stmt_attr_get( mysqli_stmt stmt. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. attr Return Values Returns FALSE if the attribute is not found. This function may be called multiple times to set several attributes.3. causes mysqli_stmt_store_result 215 . int mode).10. int attr. mysqli_stmt_attr_set Copyright 1997-2012 the PHP Documentation Group.

. a cursor is opened for the statement when you invoke mysqli_stmt_execute. mixed var1. mode The value to assign to the attribute. mode can be in the range from 1 to the maximum value of unsigned long..4. MYSQLI_STMT_ATTR_PREFETCH_ROWSof rows to fetch from Number server at a time when using a cursor. If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY. 3. mysqli_stmt_store_result is unnecessary. mysqli_stmt_free_result closes any open cursor. mixed . it closes the cursor before opening a new one.10.. Procedural style bool mysqli_stmt_bind_param( mysqli_stmt stmt. If there is already an open cursor from a previous mysqli_stmt_execute call. mixed . The default is 1. mysqli_stmt::bind_param.mysqli_stmt::bind_param. [1] • 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.. mysqli_stmt_reset also closes any open cursor before preparing the statement for reexecution. If you open a cursor for a prepared statement. mixed var1. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY. MYSQLI_STMT_ATTR_CURSOR_TYPE of cursor to open Type for statement when mysqli_stmt_execute is invoked. mysqli_stmt_bind_param Copyright 1997-2012 the PHP Documentation Group. mysqli_stmt_bind_param Character Description to update the metadata MYSQL_FIELD->max_length value. string types. 216 .).).

?. Note Care must be taken when using mysqli_stmt_bind_param in conjunction with call_user_func_array. 'world'). whereas call_user_func_array can accept as a parameter a list of variables that can represent references or values. $percent).13.mysqli_stmt::bind_param. ?. $stmt->bind_param('sssd'. Object oriented style <?php $mysqli = new mysqli('localhost'. 'my_password'. $code. A string that contains one or more characters which specify the types for the corresponding bind variables: Table 3. exit().75. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". 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 types var1 The number of variables and length of string types must match the parameters in the statement. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. 217 . 'my_user'. you have to specify b in types and use mysqli_stmt_send_long_data to send the data in packets. $code = 'DEU'. } $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?. mysqli_connect_error()). Examples Example 3. mysqli_stmt_bind_param Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare. Note that mysqli_stmt_bind_param requires parameters to be passed by reference. allowed packet size (max_allowed_packet). Return Values Returns TRUE on success or FALSE on failure. $official. Note If data size of a variable exceeds max. $language. ?)").

?.\n". printf("%d Row deleted. $percent). /* close statement and connection */ mysqli_stmt_close($stmt).\n". mysqli_stmt_bind_param($stmt. mysqli_stmt_affected_rows($stmt)).2. $language = 'Bavarian'. ?> Example 3. $percent = 11. 'sssd'. /* close connection */ $mysqli->close(). "INSERT INTO CountryLanguage VALUES (?. "DELETE FROM CountryLanguage WHERE Language='Bavarian'"). /* execute prepared statement */ mysqli_stmt_execute($stmt). $code = 'DEU'. $mysqli->affected_rows). $code. mysqli_affected_rows($link)). ?)"). printf("%d Row inserted. mysqli_connect_error()). 'my_password'.mysqli_stmt::bind_param. ?. 1 Row deleted. $official = "F". $stmt->affected_rows). 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 218 . mysqli_stmt_bind_param $language = 'Bavarian'. /* check connection */ if (!$link) { printf("Connect failed: %s\n". /* close statement and connection */ $stmt->close(). /* close connection */ mysqli_close($link).\n". $official. printf("%d Row deleted. Procedural style <?php $link = mysqli_connect('localhost'.76. /* Clean up table CountryLanguage */ $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'"). printf("%d Row inserted. } $stmt = mysqli_prepare($link. 'my_user'.\n". exit(). ?> The above examples will output: 1 Row inserted. /* Clean up table CountryLanguage */ mysqli_query($link. $percent = 11. 'world'). /* execute prepared statement */ $stmt->execute(). $official = "F". $language.2.

Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. Examples Example 3. The variable to be bound.. When mysqli_stmt_fetch is called to fetch data.). . if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mixed var1.. The new binding takes effect the next time mysqli_stmt_fetch is called.77.10.. A column can be bound or rebound at any time. the MySQL client/server protocol places the data for the bound columns into the specified variables var1. mysqli_stmt_bind_result 3. mysqli_stmt_bind_result Copyright 1997-2012 the PHP Documentation Group. var1 Return Values Returns TRUE on success or FALSE on failure.). Binds columns in the result set to variables.. Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_connect_error()). even after a result set has been partially retrieved. Depending on column types bound variables can silently change to the corresponding PHP type. Procedural style bool mysqli_stmt_bind_result( mysqli_stmt stmt. "world"). "my_user"..mysqli_stmt::bind_result. mixed . mixed . "my_password". [1] • 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..5. 219 . Note Note that all columns must be bound after mysqli_stmt_execute and prior to calling mysqli_stmt_fetch.. mysqli_stmt::bind_result.

exit(). mysqli_connect_error()). Name FROM Country ORDER BY Name LIMIT 5")) { mysqli_stmt_execute($stmt). /* bind variables to prepared statement */ $stmt->bind_result($col1. "my_password". $col2). /* check connection */ if (!$link) { printf("Connect failed: %s\n". mysqli_stmt_bind_result exit(). $col2). /* bind variables to prepared statement */ mysqli_stmt_bind_result($stmt. } /* prepare statement */ if ($stmt = $mysqli->prepare("SELECT Code. $col1. } /* close connection */ $mysqli->close(). Procedural style <?php $link = mysqli_connect("localhost". "SELECT Code. $col1. ?> 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 220 . $col2). /* fetch values */ while ($stmt->fetch()) { printf("%s %s\n". ?> Example 3. /* fetch values */ while (mysqli_stmt_fetch($stmt)) { printf("%s %s\n".78. } /* prepare statement */ if ($stmt = mysqli_prepare($link. } /* close statement */ mysqli_stmt_close($stmt). } /* close connection */ mysqli_close($link).mysqli_stmt::bind_result. $col2). "my_user". $col1. } /* close statement */ $stmt->close(). Name FROM Country ORDER BY Name LIMIT 5")) { $stmt->execute(). "world").

7. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init.6. [1] • 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( 221 . mysqli_stmt_close also deallocates the statement handle.mysqli_stmt::close. Return Values Returns TRUE on success or FALSE on failure.10. mysqli_stmt_close Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli_stmt::close mysqli_stmt_close Closes a prepared statement Description Object oriented style bool mysqli_stmt::close(). mysqli_stmt_close mysqli_stmt_prepare mysqli_stmt_init mysqli_stmt_errno mysqli_stmt_error 3. mysqli_stmt::close. this function cancels them so that the next query can be executed. See Also mysqli_prepare 3. Procedural style bool mysqli_stmt_close( mysqli_stmt stmt). Closes a prepared statement. mysqli_stmt_data_seek Copyright 1997-2012 the PHP Documentation Group.10. mysqli_stmt::data_seek. If the current statement has pending or unread results.

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

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

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

mysqli_stmt_error_list mysqli_stmt_close($stmt). See Also mysqli_stmt_error mysqli_stmt_sqlstate 3.mysqli_stmt::$error_list. error. [1] • mysqli_stmt::$error_list mysqli_stmt_error_list Returns a list of errors from the last statement executed Description Object oriented style array mysqli_stmt->error_list . Parameters stmt Return Values A list of errors. "my_user". 225 . "world").83. mysqli_stmt_error_list Copyright 1997-2012 the PHP Documentation Group. Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". "my_password".10. and sqlstate. ?> The above examples will output: Error: 1146. Returns an array of errors for the most recently invoked statement function that can succeed or fail. Examples Example 3. mysqli_stmt::$error_list.9. } /* close connection */ mysqli_close($link). /* check connection */ Procedural style only: A statement identifier returned by mysqli_stmt_init. Procedural style array mysqli_stmt_error_list( mysqli_stmt stmt). each as an associative array containing the errno.

mysqli_stmt::$error_list. if ($stmt = mysqli_prepare($link. $query)) { /* drop table */ mysqli_query($link. } /* close connection */ $mysqli->close(). /* close statement */ $stmt->close(). mysqli_connect_error()). print_r($stmt->error_list). "world"). "DROP TABLE myCountry"). $query = "SELECT Name. mysqli_connect_error()). Code FROM myCountry ORDER BY Name". exit(). if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry"). /* close statement */ mysqli_stmt_close($stmt). "CREATE TABLE myCountry LIKE Country"). /* execute query */ mysqli_stmt_execute($stmt). } mysqli_query($link. } /* close connection */ mysqli_close($link). $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"). ?> The above examples will output: Array ( [0] => Array ( [errno] => 1146 [sqlstate] => 42S02 [error] => Table 'world.myCountry' doesn't exist ) ) 226 . ?> Example 3. $query = "SELECT Name. "my_user". "INSERT INTO myCountry SELECT * FROM Country"). print_r(mysql_stmt_error_list($stmt)). /* execute query */ $stmt->execute().84. Code FROM myCountry ORDER BY Name". echo "Error:\n". exit(). mysqli_stmt_error_list if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_query($link. Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". "my_password". echo "Error:\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } $mysqli->query("CREATE TABLE myCountry LIKE Country").

Returns a containing the error message for the most recently invoked statement function that can succeed or fail. $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"). Code FROM myCountry ORDER BY Name". Procedural style only: A statement identifier returned by mysqli_stmt_init.10. mysqli_connect_error()). mysqli_stmt_error Copyright 1997-2012 the PHP Documentation Group.10. Examples Example 3. "my_password". } $mysqli->query("CREATE TABLE myCountry LIKE Country"). "my_user". [1] • mysqli_stmt::$error mysqli_stmt_error Returns a string description for last statement error Description Object oriented style string mysqli_stmt->error . /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_stmt::$error. Parameters stmt Return Values A string that describes the error. "world"). Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost". Procedural style string mysqli_stmt_error( mysqli_stmt stmt). An empty string if no error occurred.mysqli_stmt::$error. $query = "SELECT Name. mysqli_stmt_error See Also mysqli_stmt_error mysqli_stmt_errno mysqli_stmt_sqlstate 3. exit().85. 227 . if ($stmt = $mysqli->prepare($query)) { /* drop table */ $mysqli->query("DROP TABLE myCountry").

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

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

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

Data has been fetched Error occurred No more rows/data exists or data truncation occurred Examples Example 3.10. Procedural style bool mysqli_stmt_fetch( mysqli_stmt stmt). Return Values Value TRUE FALSE NULL Description Success.89. mysqli_stmt::fetch.14. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result. mysqli_stmt_fetch Copyright 1997-2012 the PHP Documentation Group. Note Data are transferred unbuffered without calling mysqli_stmt_store_result which can decrease performance (but reduces memory cost). Return Values Table 3. mysqli_stmt_fetch mysqli_prepare mysqli_stmt_bind_param 3.12.mysqli_stmt::fetch. [1] • mysqli_stmt::fetch mysqli_stmt_fetch Fetch results from a prepared statement into the bound variables Description Object oriented style bool mysqli_stmt::fetch(). Note Note that all columns must be bound by the application before calling mysqli_stmt_fetch. Object oriented style <?php 231 .

$code). "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". exit(). if ($stmt = $mysqli->prepare($query)) { /* execute statement */ $stmt->execute(). if ($stmt = mysqli_prepare($link. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* bind result variables */ mysqli_stmt_bind_result($stmt. } $query = "SELECT Name. Procedural style <?php $link = mysqli_connect("localhost". /* fetch values */ while (mysqli_stmt_fetch($stmt)) { printf ("%s (%s)\n". } $query = "SELECT Name. $name. mysqli_connect_error()).90.5". $code). $code). "my_password". mysqli_stmt_fetch $mysqli = new mysqli("localhost". exit(). mysqli_connect_error()). } /* close connection */ mysqli_close($link). "world"). ?> The above examples will output: Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) See Also 232 . CountryCode FROM City ORDER by ID DESC LIMIT 150. $name. $name. } /* close statement */ mysqli_stmt_close($stmt). /* fetch values */ while ($stmt->fetch()) { printf ("%s (%s)\n". } /* close statement */ $stmt->close().5". $code). $query)) { /* execute statement */ mysqli_stmt_execute($stmt). CountryCode FROM City ORDER by ID DESC LIMIT 150. "world").mysqli_stmt::fetch. /* bind result variables */ $stmt->bind_result($name. } /* close connection */ $mysqli->close(). ?> Example 3. "my_password". "my_user".

10. mysqli_stmt_free_result Copyright 1997-2012 the PHP Documentation Group. 233 . 3.mysqli_stmt::$field_count. Frees the result memory associated with the statement. mysqli_stmt::$field_count.14.10. Procedural style int mysqli_stmt_field_count( mysqli_stmt stmt). only its argument list is available. which was allocated by mysqli_stmt_store_result. [1] • 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. Procedural style void mysqli_stmt_free_result( mysqli_stmt stmt).13. mysqli_stmt_field_count mysqli_prepare mysqli_stmt_errno mysqli_stmt_error mysqli_stmt_bind_result 3. Warning This function is currently not documented. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. [1] • mysqli_stmt::$field_count mysqli_stmt_field_count Returns the number of field in the given statement Description Object oriented style int mysqli_stmt->field_count . mysqli_stmt_field_count Copyright 1997-2012 the PHP Documentation Group.

0. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. Call to return a result set from a prepared statement query. "password".1". mysqli_stmt::get_result. mysqli_stmt_get_result Copyright 1997-2012 the PHP Documentation Group.mysqli_stmt::get_result.0. mysqli_stmt_get_result Return Values No value is returned. $stmt = $mysqli->stmt_init(). [1] • mysqli_stmt::get_result mysqli_stmt_get_result Gets a result set from a prepared statement Description Object oriented style mysqli_result mysqli_stmt::get_result(). See Also mysqli_stmt_store_result 3. Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1". } $query = "SELECT Name.91. "user". "world").15. Return Values Returns a resultset or FALSE on failure.10. Procedural style mysqli_result mysqli_stmt_get_result( mysqli_stmt stmt). Object oriented style <?php $mysqli = new mysqli("127. if(!$stmt->prepare($query)) { 234 . Examples Example 3. if($mysqli->connect_error) { die("$mysqli->connect_errno: $mysqli->connect_error"). Population. MySQL Native Driver Only Available only with mysqlnd.

?> 235 . } $query = "SELECT Name. $result = mysqli_stmt_get_result($stmt).'Asia'. mysqli_stmt_get_result print "Failed to prepare statement\n". $stmt = mysqli_stmt_init($link). } else { mysqli_stmt_bind_param($stmt.92. while ($row = mysqli_fetch_array($result. exit(). MYSQLI_NUM)) { foreach ($row as $r) { print "$r ". "user". } } } mysqli_stmt_close($stmt). } print "\n".mysqli_stmt::get_result. Population. $continent).0.'North America'). if (!$link) { $error = mysqli_connect_error(). foreach($continent_array as $continent) { $stmt->execute(). $continent). while ($row = $result->fetch_array(MYSQLI_NUM)) { foreach ($row as $r) { print "$r ". $query)) { print "Failed to prepare statement\n".0. } } } $stmt->close(). print "$errno: $error\n".'North America'). $continent_array = array('Europe'. "world"). Procedural style <?php $link = mysqli_connect("127.'Africa'. $mysqli->close(). if(!mysqli_stmt_prepare($stmt.'Asia'.'Africa'. $continent_array = array('Europe'. $result = $stmt->get_result().1". } print "\n". $errno = mysqli_connect_errno(). ?> Example 3. Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1". "s". foreach($continent_array as $continent) { mysqli_stmt_execute($stmt). } else { $stmt->bind_param("s". "password". mysqli_close($link).

3. mysqli_stmt_insert_id Copyright 1997-2012 the PHP Documentation Group. [1] • 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 . Warning This function is currently not documented. [1] • 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). mysqli_stmt::$insert_id.10. only its argument list is available.10.mysqli_stmt::get_warnings. 236 . 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 3.17. mysqli_stmt_get_warnings Copyright 1997-2012 the PHP Documentation Group.16. Procedural style object mysqli_stmt_get_warnings( mysqli_stmt stmt). mysqli_stmt::get_warnings.

mysqli_stmt::more_results. otherwise FALSE . See Also mysqli_stmt::next_result mysqli::multi_query 3.10. mysqli_stmt::more_results. Procedural style: bool mysqli_stmt_more_results( mysql_stmt stmt). [1] • mysqli_stmt::more_results mysqli_stmt_more_results Check if there are more query results from a multiple query Description Object oriented style (method): public bool mysqli_stmt::more_results(). only its argument list is available. Checks if there are more query results from a multiple query. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init.10. [1] • mysqli_stmt::next_result mysqli_stmt_next_result Reads the next result from a multiple query Description Object oriented style (method): 237 . 3. mysqli_stmt_more_results Procedural style mixed mysqli_stmt_insert_id( mysqli_stmt stmt).18. mysqli_stmt_next_result Copyright 1997-2012 the PHP Documentation Group. mysqli_stmt::next_result.19. Warning This function is currently not documented. Return Values Returns TRUE if more results exist. mysqli_stmt_more_results Copyright 1997-2012 the PHP Documentation Group.

Returns the number of rows in the result set. mysqli_stmt::$num_rows. Reads the next result from a multiple query. Procedural style: bool mysqli_stmt_next_result( mysql_stmt stmt). mysqli_stmt_num_rows public bool mysqli_stmt::next_result(). Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. Errors/Exceptions Emits an E_STRICT level error if a result set does not exist. before calling mysqli_stmt::next_result.mysqli_stmt::$num_rows.20. 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. Procedural style int mysqli_stmt_num_rows( mysqli_stmt stmt). 238 . mysqli_stmt_num_rows may be called immediately. See Also mysqli_stmt::more_results mysqli::multi_query 3.10. Return Values Returns TRUE on success or FALSE on failure. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. If you use mysqli_stmt_store_result. [1] • 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 . mysqli_stmt_num_rows Copyright 1997-2012 the PHP Documentation Group. and suggests using mysqli_stmt::more_results in these cases.

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

/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf("Statement has %d markers. exit(). /* close statement */ $stmt->close(). Procedural style int mysqli_stmt_param_count( mysqli_stmt stmt). } if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) { $marker = $stmt->param_count.95. Returns the number of parameter markers present in the prepared statement. } /* close connection */ $mysqli->close(). "my_user". Return Values Returns an integer representing the number of parameters. mysqli_stmt_param_count Copyright 1997-2012 the PHP Documentation Group.10. mysqli_stmt::$param_count. Object oriented style <?php $mysqli = new mysqli("localhost".\n". mysqli_stmt_param_count See Also mysqli_stmt_affected_rows mysqli_prepare mysqli_stmt_store_result 3.mysqli_stmt::$param_count. [1] • 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 . "world").21. "my_password". mysqli_connect_error()). Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. $marker). Examples Example 3. ?> 240 .

/* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf("Statement has %d markers. exit(). 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. mysqli_stmt_prepare Copyright 1997-2012 the PHP Documentation Group. Prepares the SQL query pointed to by the null-terminated string query. mysqli_stmt_prepare Example 3. Procedural style bool mysqli_stmt_prepare( mysqli_stmt stmt. mysqli_stmt::prepare. } /* close connection */ mysqli_close($link). 241 .mysqli_stmt::prepare. "world"). mysqli_connect_error()).10. Procedural style <?php $link = mysqli_connect("localhost". /* close statement */ mysqli_stmt_close($stmt).22.96. See Also mysqli_prepare 3. } if ($stmt = mysqli_prepare($link. string query).\n". "my_user". [1] • mysqli_stmt::prepare mysqli_stmt_prepare Prepare an SQL statement for execution Description Object oriented style mixed mysqli_stmt::prepare( string query). $marker). "SELECT Name FROM Country WHERE Name=? OR Code=?")) { $marker = mysqli_stmt_param_count($stmt). ?> The above examples will output: Statement has 2 markers. "my_password".

The latter restriction is necessary because it would be impossible to determine the parameter type. • libmysql on all platforms returns an error code 2006. • mysqlnd on Windows returns an error code 2006. and not in Data Definition Language (DDL) statements. The error message means “got a packet bigger than max_allowed_packet bytes”. or to specify both operands of a binary operator such as the = equal sign. Examples query 242 . Note The markers are legal only in certain places in SQL statements. Return Values Returns TRUE on success or FALSE on failure. mysqli_stmt_prepare Note In the case where you pass a statement to mysqli_stmt_prepare that is longer than max_allowed_packet of the server. as a string. they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row). Note You should not add a terminating semicolon or \g to the statement. they are not allowed for identifiers (such as table or column names). The query.mysqli_stmt::prepare. or in a comparison with a column in a WHERE clause to specify a comparison value. in the select list that names the columns to be returned by a SELECT statement). This error message means “server has gone away”. parameters are legal only in Data Manipulation Language (DML) statements. In general. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. This error message means “server has gone away”. You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions. It must consist of a single SQL statement. However. The behavior is as follows: • mysqlnd on Linux returns an error code of 1153. For example. the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql).

printf("%s is in district %s\n". $district). $district). /* bind result variables */ $stmt->bind_result($district). exit(). /* fetch value */ mysqli_stmt_fetch($stmt). /* create a prepared statement */ $stmt = $mysqli->stmt_init().97. /* close statement */ mysqli_stmt_close($stmt). exit(). "world"). "my_user". /* execute query */ mysqli_stmt_execute($stmt). mysqli_connect_error()). $city). } $city = "Amersfoort". if (mysqli_stmt_prepare($stmt. $district). Procedural style <?php $link = mysqli_connect("localhost". $city. if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ $stmt->bind_param("s". mysqli_connect_error()). "world"). $city. "my_user". "my_password". /* bind result variables */ mysqli_stmt_bind_result($stmt.98. } /* close connection */ mysqli_close($link). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* create a prepared statement */ $stmt = mysqli_stmt_init($link). /* execute query */ $stmt->execute(). $city). } $city = "Amersfoort". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf("%s is in district %s\n". "s". /* fetch value */ $stmt->fetch(). ?> Example 3. mysqli_stmt_prepare Example 3. ?> The above examples will output: 243 .mysqli_stmt::prepare. 'SELECT District FROM City WHERE Name=?')) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt. /* close statement */ $stmt->close(). "my_password". } /* close connection */ $mysqli->close(). Object oriented style <?php $mysqli = new mysqli("localhost".

[1] 244 .10. mysqli_stmt_result_metadata Copyright 1997-2012 the PHP Documentation Group. data sent using mysqli_stmt_send_long_data.mysqli_stmt::reset.23. 3. mysqli_stmt::result_metadata. It does not clear bindings or stored result sets.10. Parameters stmt Return Values Returns TRUE on success or FALSE on failure. It resets the statement on the server. See Also mysqli_prepare Procedural style only: A statement identifier returned by mysqli_stmt_init. mysqli_stmt_reset Copyright 1997-2012 the PHP Documentation Group. mysqli_stmt::reset.24. To prepare a statement with another query use function mysqli_stmt_prepare. mysqli_stmt_reset 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 3. unbuffered result sets and current errors. Resets a prepared statement on client and server to state after prepare. Procedural style bool mysqli_stmt_reset( mysqli_stmt stmt). Stored result sets will be cleared when executing the prepared statement (or closing it). [1] • mysqli_stmt::reset mysqli_stmt_reset Resets a prepared statement Description Object oriented style bool mysqli_stmt::reset().

mysqli_stmt::result_metadata. such as: • mysqli_num_fields • mysqli_fetch_field • mysqli_fetch_field_direct • mysqli_fetch_fields • mysqli_field_count • mysqli_field_seek • mysqli_field_tell • mysqli_free_result The result set structure should be freed when you are done with it. Note This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata. Parameters stmt Procedural style only: A statement identifier returned by mysqli_stmt_init. If a statement passed to mysqli_prepare is one that produces a result set. It does not contain any row results. Return Values Returns a result object or FALSE if an error occurred. Procedural style mysqli_result mysqli_stmt_result_metadata( mysqli_stmt stmt). mysqli_stmt_result_metadata • 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(). which you can do by passing it to mysqli_free_result Note The result set returned by mysqli_stmt_result_metadata contains only metadata. 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. 245 . The rows are obtained by using the statement handle with mysqli_stmt_fetch.

"my_user". /* close resultset */ mysqli_free_result($result).'Hartmut'). $stmt = $mysqli->prepare("SELECT id. Procedural style <?php $link = mysqli_connect("localhost". (2. ?> See Also mysqli_prepare mysqli_free_result 3. /* get resultset for metadata */ $result = mysqli_stmt_result_metadata($stmt). name varchar(20))"). $stmt->execute(). name FROM friends"). "test"). "DROP TABLE IF EXISTS friends"). printf("Fieldname: %s\n". "my_password".100. ?> Example 3.99. name FROM friends"). mysqli_stmt_execute($stmt). /* close resultset */ $result->close(). 'Ulf')").10. name varchar(20))").25. $mysqli->query("DROP TABLE IF EXISTS friends"). mysqli_stmt_send_long_data Copyright 1997-2012 the PHP Documentation Group. "my_password". /* get resultset for metadata */ $result = $stmt->result_metadata().mysqli_stmt::send_long_data. mysqli_query($link. "CREATE TABLE friends (id int. 'Ulf')"). mysqli_query($link. mysqli_stmt::send_long_data. "test"). "my_user". $field->name). $field->name). /* retrieve field information from metadata result set */ $field = $result->fetch_field(). "SELECT id. printf("Fieldname: %s\n". [1] • mysqli_stmt::send_long_data mysqli_stmt_send_long_data Send data in blocks Description 246 . /* close connection */ $mysqli->close(). /* retrieve field information from metadata result set */ $field = mysqli_fetch_field($result). "INSERT INTO friends VALUES (1. $mysqli->query("CREATE TABLE friends (id int. /* close connection */ mysqli_close($link). $stmt = mysqli_prepare($link. $mysqli->query("INSERT INTO friends VALUES (1. Object oriented style <?php $mysqli = new mysqli("localhost". mysqli_query($link.'Hartmut'). (2. mysqli_stmt_send_long_data Examples Example 3.

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

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

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

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

"world"). int 251 .15. ?> The above examples will output: Number of rows: 20.4. } /* close connection */ mysqli_close($link). as mysqli_result now implements Traversable. The mysqli_result class (mysqli_result) Copyright 1997-2012 the PHP Documentation Group. "my_user". Changelog Table 3. /* store result */ mysqli_stmt_store_result($stmt). CountryCode FROM City ORDER BY Name LIMIT 20". mysqli_connect_error()). [1] Represents the result set obtained from a query against the database. printf("Number of rows: %d.\n". if ($stmt = mysqli_prepare($link. Changelog Version 5. $query)) { /* execute query */ mysqli_stmt_execute($stmt). mysqli_stmt_num_rows($stmt)). mysqli_result { mysqli_result Traversable Properties int mysqli_result->current_field .The mysqli_result class (mysqli_result) $link = mysqli_connect("localhost". See Also mysqli_prepare mysqli_stmt_result_metadata mysqli_stmt_fetch 3. exit(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* close statement */ mysqli_stmt_close($stmt).11. } $query = "SELECT Name.0 Description Iterator support was added. "my_password". /* free result */ mysqli_stmt_free_result($stmt).

mixed mysqli_result::fetch_row(). object mysqli_result::fetch_object( string class_name. array params). mysqli_field_tell mysqli_result->field_count .1. } 3. mysqli_result::$current_field. mysqli_field_tell Copyright 1997-2012 the PHP Documentation Group.11. object mysqli_result::fetch_field_direct( int fieldnr). bool mysqli_result::field_seek( int fieldnr). array mysqli_result->lengths . Procedural style int mysqli_field_tell( 252 . mixed mysqli_result::fetch_array( int resulttype = =MYSQLI_BOTH). Methods bool mysqli_result::data_seek( int offset).mysqli_result::$current_field. void mysqli_result::free(). array mysqli_result::fetch_fields(). int mysqli_result->num_rows . array mysqli_result::fetch_assoc(). [1] • mysqli_result::$current_field mysqli_field_tell Get current field offset of a result pointer Description Object oriented style int mysqli_result->current_field . mixed mysqli_result::fetch_all( int resulttype = =MYSQLI_NUM). object mysqli_result::fetch_field().

exit(). Returns the position of the field cursor used for the last mysqli_fetch_field call. exit().106. $finfo->type). $finfo->max_length). 253 . printf("Name: %s\n".mysqli_result::$current_field. "my_user". "world"). Object oriented style <?php $mysqli = new mysqli("localhost". $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { /* get fieldpointer offset */ $currentfield = mysqli_field_tell($result).107. Len: %d\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf("Column %d:\n". $finfo->name). "my_user". ?> Example 3. mysqli_connect_error()). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Return Values Returns current offset of field cursor. "world"). if ($result = $mysqli->query($query)) { /* Get field information for all columns */ while ($finfo = $result->fetch_field()) { /* get fieldpointer offset */ $currentfield = $result->current_field. Parameters result Procedural style only: A result set identifier returned by mysqli_query. } $query = "SELECT Name. mysqli_connect_error()). SurfaceArea from Country ORDER BY Code LIMIT 5". $currentfield). $finfo->flags). "my_password". } /* close connection */ $mysqli->close(). } $query = "SELECT Name. mysqli_field_tell mysqli_result result). if ($result = mysqli_query($link. "my_password". $currentfield). Procedural style <?php $link = mysqli_connect("localhost". printf("Type: %d\n\n". printf("Flags: %d\n". printf("max. $finfo->table). printf("Table: %s\n". mysqli_store_result or mysqli_use_result. SurfaceArea from Country ORDER BY Code LIMIT 5". This value can be used as an argument to mysqli_field_seek. printf("Column %d:\n". } $result->close(). Examples Example 3.

2. } /* close connection */ mysqli_close($link). %d\n\n". $finfo->type). $finfo->name). Procedural style bool mysqli_data_seek( mysqli_result result. ?> The above examples will output: Column 1: Name: Table: max. mysqli_data_seek Copyright 1997-2012 the PHP Documentation Group. 254 .11. mysqli_data_seek printf("Name: printf("Table: printf("max. int offset). $finfo->max_length). %s\n". [1] • mysqli_result::data_seek mysqli_data_seek Adjusts the result pointer to an arbitrary row in the result Description Object oriented style bool mysqli_result::data_seek( int offset). Len: Flags: Type: Column 2: Name: Table: max. mysqli_result::data_seek. Len: Flags: Type: Name Country 11 1 254 SurfaceArea Country 10 32769 4 See Also mysqli_fetch_field mysqli_field_seek 3. %d\n". } mysqli_free_result($result). %d\n".mysqli_result::data_seek. Len: printf("Flags: printf("Type: %s\n". $finfo->flags). $finfo->table). The mysqli_data_seek function seeks to an arbitrary result pointer specified by the offset in the result set.

1). mysqli_connect_error()). 399). Notes Note This function can only be used with buffered results attained from the use of the mysqli_store_result or mysqli_query functions. if ($result = mysqli_query($link. } /* close connection */ $mysqli->close().108. $row[0]. 400 */ mysqli_data_seek($result. printf ("City: %s Countrycode: %s\n". CountryCode FROM City ORDER BY Name".. $row[1]). /* free result set*/ $result->close(). mysqli_data_seek Parameters result Procedural style only: A result set identifier returned by mysqli_query. exit(). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". } $query = "SELECT Name. CountryCode FROM City ORDER BY Name". Examples Example 3. Must be between zero and the total number of rows minus one (0. "my_password". exit().mysqli_num_rows . $query)) { /* seek to row no. The field offset. offset Return Values Returns TRUE on success or FALSE on failure. /* fetch row */ $row = $result->fetch_row(). "my_password". 255 . Procedural style <?php /* Open a connection */ $link = mysqli_connect("localhost". mysqli_connect_error()). Object oriented style <?php /* Open a connection */ $mysqli = new mysqli("localhost".mysqli_result::data_seek. ?> Example 3. "world").109. "world"). 400 */ $result->data_seek(399). "my_user". } $query = "SELECT Name. mysqli_store_result or mysqli_use_result. /* check connection */ if (!$link) { printf("Connect failed: %s\n". "my_user". if ($result = $mysqli->query( $query)) { /* seek to row no.

a numeric array. $row[1]).mysqli_result::fetch_all. [1] • mysqli_result::fetch_all mysqli_fetch_all Fetches all result rows as an associative array. $row[0]. } /* close connection */ mysqli_close($link). ?> 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 3. /* free result set*/ mysqli_free_result($result). mysqli_fetch_all Copyright 1997-2012 the PHP Documentation Group. int resulttype = =MYSQLI_NUM). or both Description Object oriented style mixed mysqli_result::fetch_all( int resulttype = =MYSQLI_NUM). mysqli_result::fetch_all.11. or both. a numeric array. 256 .3. Parameters result Procedural style only: A result set identifier returned by mysqli_query. printf ("City: %s Countrycode: %s\n". mysqli_fetch_all /* fetch row */ $row = mysqli_fetch_row($result). mysqli_fetch_all fetches all result rows and returns the result set as an associative array. mysqli_store_result or mysqli_use_result. Procedural style mixed mysqli_fetch_all( mysqli_result result.

mysqli_result::fetch_array. mysqli_fetch_array Copyright 1997-2012 the PHP Documentation Group.11. MySQL Native Driver Only Available only with mysqlnd. 257 . In addition to storing the data in the numeric indices of the result array. it may consume more memory than some similar functions such as mysqli_fetch_array. MYSQLI_NUM . int resulttype = =MYSQLI_BOTH).mysqli_result::fetch_array. mysqli_fetch_array is an extended version of the mysqli_fetch_row function. 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. [1] • mysqli_result::fetch_array mysqli_fetch_array Fetch a result row as an associative. if you need to iterate over the result set. mysqli_fetch_array resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC . or both Description Object oriented style mixed mysqli_result::fetch_array( int resulttype = =MYSQLI_BOTH). Note Field names returned by this function are case-sensitive. Procedural style mixed mysqli_fetch_array( mysqli_result result. As mysqli_fetch_all returns all the rows as an array in a single step. Return Values Returns an array of associative or numeric arrays holding result rows. which only returns one row at a time from the result set. 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.4. you will need a looping construct that will further impact performance. See Also mysqli_fetch_array mysqli_query 3. or MYSQLI_BOTH . using the field names of the result set as keys. the mysqli_fetch_array function can also store the data in associative indices. Further. a numeric array.

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

mysqli_fetch_assoc Copyright 1997-2012 the PHP Documentation Group. "my_user". /* close connection */ mysqli_close($link). "my_password". $row["Name"]. $row[0].5. $row[1]).mysqli_result::fetch_assoc. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". 259 . exit(). /* numeric array */ $row = mysqli_fetch_array($result. printf ("%s (%s)\n". ?> 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 3. $row[0]. } $query = "SELECT Name. /* associative array */ $row = mysqli_fetch_array($result. printf ("%s (%s)\n". /* free result set */ mysqli_free_result($result). Procedural style array mysqli_fetch_assoc( mysqli_result result). mysqli_connect_error()). MYSQLI_NUM). MYSQLI_BOTH). [1] • mysqli_result::fetch_assoc mysqli_fetch_assoc Fetch a result row as an associative array Description Object oriented style array mysqli_result::fetch_assoc(). MYSQLI_ASSOC). mysqli_fetch_assoc <?php $link = mysqli_connect("localhost". /* associative and numeric array */ $row = mysqli_fetch_array($result. $row["CountryCode"]). CountryCode FROM City ORDER by ID LIMIT 3". $result = mysqli_query($link. $row["CountryCode"]). $query). "world"). mysqli_result::fetch_assoc.11. printf ("%s (%s)\n".

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

0. mysqli_fetch_assoc /* fetch associative array */ while ($row = mysqli_fetch_assoc($result)) { printf ("%s (%s)\n".0.0.0.host FROM mysql. } echo "\n==================\n". } ?> The above example will output something similar to: 'root'@'192.1'. $row["Name"].4) foreach ( $c->query('SELECT user.1' 'root'@'127.user').1. $row['host']).1. $row['user'].0. A mysqli_result example comparing iterator usage <?php $c = mysqli_connect('127. // Using iterators (support was added with PHP 5. } /* free result set */ mysqli_free_result($result).168. ?> The above examples will output: Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) Example 3.user') as $row ) { printf("'%s'@'%s'\n". $row["CountryCode"]).1' 'dude'@'localhost' 'lebowski'@'localhost' See Also mysqli_fetch_array mysqli_fetch_row mysqli_fetch_object mysqli_query mysqli_data_seek 261 . $row['user'].mysqli_result::fetch_assoc. $row['host']).114.168.host FROM mysql.0.'user'.1' 'root'@'127. while ($row = $result->fetch_assoc()) { printf("'%s'@'%s'\n". 'pass'). } /* close connection */ mysqli_close($link). // Not using iterators $result = $c->query('SELECT user.1' 'dude'@'localhost' 'lebowski'@'localhost' ================== 'root'@'192.

int fieldnr).mysqli_result::fetch_field_direct.6. 262 .1. This value must be in the range from 0 to number of fields . Procedural style object mysqli_fetch_field_direct( mysqli_result result. The width of the field. mysqli_fetch_field_direct 3. represented as a string The maximum width of the field for the result set.11. Table 3. The character set number for the field. Object attributes Attribute name orgname table orgtable def max_length length charsetnr flags 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. fieldnr Return Values Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available. mysqli_result::fetch_field_direct. An integer representing the bit-flags for the field. Returns an object which contains field definition information from the specified result set. as specified in the table definition. Parameters result Procedural style only: A result set identifier returned by mysqli_query.16. The field number. [1] • mysqli_result::fetch_field_direct mysqli_fetch_field_direct Fetch meta-data for a single field Description Object oriented style object mysqli_result::fetch_field_direct( int fieldnr). mysqli_store_result or mysqli_use_result. mysqli_fetch_field_direct Copyright 1997-2012 the PHP Documentation Group.

printf("Name: %s\n". SurfaceArea from Country ORDER BY Name LIMIT 5". $finfo->table). "world"). printf("Table: %s\n". if ($result = mysqli_query($link. mysqli_fetch_field_direct Attribute type decimals Examples Example 3. } $query = "SELECT Name. } $query = "SELECT Name. SurfaceArea from Country ORDER BY Name LIMIT 5". "my_user". exit(). exit(). $result->close(). printf("Name: %s\n". printf("Type: %d\n". mysqli_connect_error()).115. "world"). $finfo->type). $finfo->flags).mysqli_result::fetch_field_direct. ?> Example 3. mysqli_free_result($result). printf("max. printf("Type: %d\n". "my_password". Len: %d\n". mysqli_connect_error()). Object oriented style Description The data type used for this field The number of decimals used (for integer fields) <?php $mysqli = new mysqli("localhost". $finfo->name). $finfo->table). $finfo->max_length). 1). } /* close connection */ $mysqli->close(). printf("Flags: %d\n". if ($result = $mysqli->query($query)) { /* Get field information for column 'SurfaceArea' */ $finfo = $result->fetch_field_direct(1). ?> The above examples will output: Name: SurfaceArea 263 . $finfo->max_length). Len: %d\n". $finfo->type). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". printf("Flags: %d\n". $finfo->flags). printf("Table: %s\n". $query)) { /* Get field information for column 'SurfaceArea' */ $finfo = mysqli_fetch_field_direct($result. printf("max. "my_password". $finfo->name). } /* close connection */ mysqli_close($link).116. "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Procedural style <?php $link = mysqli_connect("localhost".

currently always "" Database (since PHP 5. Object properties Property name orgname table orgtable def db 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. Procedural style object mysqli_fetch_field( mysqli_result result).11.mysqli_result::fetch_field. Return Values Returns an object which contains field definition information or FALSE if no field information is available. mysqli_store_result or mysqli_use_result. Returns the definition of one column of a result set as an object. Table 3. mysqli_fetch_field Copyright 1997-2012 the PHP Documentation Group. mysqli_fetch_field Table: max.3. Call this function repeatedly to retrieve information about all columns in the result set. Parameters result Procedural style only: A result set identifier returned by mysqli_query.7. [1] • mysqli_result::fetch_field mysqli_fetch_field Returns the next field in the result set Description Object oriented style object mysqli_result::fetch_field(). mysqli_result::fetch_field.17. Len: Flags: Type: Country 10 32769 4 See Also mysqli_num_fields mysqli_fetch_field mysqli_fetch_fields 3.6) 264 .

} /* close connection */ $mysqli->close(). $finfo->type). $finfo->table). The character set number for the field. Len: %d\n". Procedural style <?php $link = mysqli_connect("localhost". printf("Type: %d\n\n". printf("Table: %s\n". $query)) { /* Get field information for all fields */ while ($finfo = mysqli_fetch_field($result)) { printf("Name: %s\n". $finfo->name). exit(). $finfo->max_length). $finfo->table). $finfo->flags). if ($result = mysqli_query($link.mysqli_result::fetch_field. ?> Example 3. mysqli_connect_error()). printf("max. $finfo->name).6) The maximum width of the field for the result set. as specified in the table definition. "world"). printf("Flags: %d\n".118. SurfaceArea from Country ORDER BY Code LIMIT 5". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "my_user". 265 . exit().3. always "def" (since PHP 5. "world"). "my_password". } mysqli_free_result($result). if ($result = $mysqli->query($query)) { /* Get field information for all columns */ while ($finfo = $result->fetch_field()) { printf("Name: %s\n".117. printf("max. } $query = "SELECT Name. Object oriented style Description The catalog name. } $result->close(). mysqli_fetch_field Property catalog max_length length charsetnr flags type decimals Examples Example 3. An integer representing the bit-flags for the field. printf("Flags: %d\n". "my_user". $finfo->flags). Len: %d\n". $finfo->type). printf("Table: %s\n". "my_password". $finfo->max_length). printf("Type: %d\n\n". The width of the field. mysqli_connect_error()). } $query = "SELECT Name. SurfaceArea from Country ORDER BY Code LIMIT 5". The data type used for this field The number of decimals used (for integer fields) <?php $mysqli = new mysqli("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".

mysqli_result::fetch_fields. the columns are returned as an array of objects. ?> The above examples will output: Name: Table: max. mysqli_fetch_fields Copyright 1997-2012 the PHP Documentation Group. mysqli_fetch_fields } /* close connection */ mysqli_close($link). instead of returning one object at a time for each field.11. Len: Flags: Type: Name: Table: max. Procedural style array mysqli_fetch_fields( mysqli_result result). mysqli_store_result or mysqli_use_result. This function serves an identical purpose to the mysqli_fetch_field function with the single difference that.8.mysqli_result::fetch_fields. Return Values 266 . Parameters result Procedural style only: A result set identifier returned by mysqli_query. [1] • mysqli_result::fetch_fields mysqli_fetch_fields Returns an array of objects representing the fields in a result set Description Object oriented style array mysqli_result::fetch_fields(). 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 3.

"my_password". $val->max_length). "my_user". mysqli_connect_error()). $val->type). printf("Type: %d\n\n". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". /* check connection */ if (mysqli_connect_errno()) { 267 . } $result->close(). "my_user".119. printf("Flags: %d\n". $val->name). "my_password". Table 3.mysqli_result::fetch_fields. exit(). foreach ($finfo as $val) { printf("Name: %s\n".120. $val->flags). as specified in the table definition. } /* close connection */ $mysqli->close(). ?> 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. The width of the field. An integer representing the bit-flags for the field. Object oriented style <?php $mysqli = new mysqli("localhost". printf("max. "world"). The character set number for the field. SurfaceArea from Country ORDER BY Code LIMIT 5". Procedural style <?php $link = mysqli_connect("localhost". printf("Table: %s\n". } $query = "SELECT Name. Object properties Property name orgname table orgtable max_length length charsetnr flags type decimals Examples Example 3. "world"). $val->table). Len: %d\n". The data type used for this field The number of decimals used (for integer fields) Example 3.18. mysqli_fetch_fields Returns an array of objects which contains field definition information or FALSE if no field information is available. if ($result = $mysqli->query($query)) { /* Get field information for all columns */ $finfo = $result->fetch_fields().

$query)) { /* Get field information for all columns */ $finfo = mysqli_fetch_fields($result). Len: %d\n". printf("Type: %d\n\n". array params). foreach ($finfo as $val) { printf("Name: %s\n". ?> The above examples will output: Name: Table: max. $val->type). mysqli_connect_error()). printf("Flags: %d\n". [1] • mysqli_result::fetch_object mysqli_fetch_object Returns the current row of a result set as an object Description Object oriented style object mysqli_result::fetch_object( string class_name. Len: Flags: Type: Name: Table: max. } $query = "SELECT Name. printf("Table: %s\n". mysqli_fetch_object printf("Connect failed: %s\n". 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 3. exit(). $val->max_length). $val->name). Procedural style 268 . printf("max. } /* close connection */ mysqli_close($link). } mysqli_free_result($result). if ($result = mysqli_query($link. $val->table). mysqli_result::fetch_object.mysqli_result::fetch_object. SurfaceArea from Country ORDER BY Code LIMIT 5".9. mysqli_fetch_object Copyright 1997-2012 the PHP Documentation Group. $val->flags).11.

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

5". "my_password". exit().mysqli_result::fetch_row. } /* free result set */ mysqli_free_result($result). ?> 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 3. mysqli_fetch_row Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli_result::fetch_row mysqli_fetch_row Get a result row as an enumerated array Description Object oriented style 270 . mysqli_result::fetch_row.122. mysqli_connect_error()). $obj->Name. if ($result = mysqli_query($link. "world"). Procedural style <?php $link = mysqli_connect("localhost". ?> Example 3. } /* close connection */ mysqli_close($link). $query)) { /* fetch associative array */ while ($obj = mysqli_fetch_object($result)) { printf ("%s (%s)\n".10. } $query = "SELECT Name. $obj->CountryCode).11. CountryCode FROM City ORDER by ID DESC LIMIT 50. mysqli_fetch_row /* close connection */ $mysqli->close(). "my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".

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

mysqli_store_result or mysqli_use_result. ?> 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 3.mysqli_result::$field_count. 272 . } /* free result set */ mysqli_free_result($result). } /* close connection */ mysqli_close($link). mysqli_num_fields /* fetch associative array */ while ($row = mysqli_fetch_row($result)) { printf ("%s (%s)\n". Procedural style int mysqli_num_fields( mysqli_result result). $row[1]). mysqli_result::$field_count. $row[0].11. Returns the number of fields from specified result set. Parameters result Return Values Procedural style only: A result set identifier returned by mysqli_query. mysqli_num_fields Copyright 1997-2012 the PHP Documentation Group.11. [1] • mysqli_result::$field_count mysqli_num_fields Get the number of fields in a result Description Object oriented style int mysqli_result->field_count .

"my_user". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Object oriented style <?php $mysqli = new mysqli("localhost". } if ($result = mysqli_query($link. /* close result set */ $result->close(). "SELECT * FROM City ORDER BY ID LIMIT 1")) { /* determine number of fields in result set */ $field_cnt = mysqli_num_fields($result). mysqli_connect_error()). exit(). mysqli_field_seek Copyright 1997-2012 the PHP Documentation Group.mysqli_result::field_seek. ?> Example 3. "my_user". "world"). printf("Result set has %d fields. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Examples Example 3. ?> The above examples will output: Result set has 5 fields. [1] 273 . } if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) { /* determine number of fields in result set */ $field_cnt = $result->field_count. Procedural style <?php $link = mysqli_connect("localhost". mysqli_connect_error()). } /* close connection */ mysqli_close($link). mysqli_result::field_seek.\n". $field_cnt). printf("Result set has %d fields. See Also mysqli_fetch_field 3.126.12. exit().125. "my_password".11.\n". "world"). mysqli_field_seek The number of fields from a result set. } /* close connection */ $mysqli->close(). $field_cnt). /* close result set */ mysqli_free_result($result). "my_password".

fieldnr Return Values Returns TRUE on success or FALSE on failure. printf("Type: %d\n\n". $finfo->max_length). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". SurfaceArea from Country ORDER BY Code LIMIT 5". Note To seek to the beginning of a row. int fieldnr). mysqli_store_result or mysqli_use_result. Object oriented style <?php $mysqli = new mysqli("localhost". 274 . if ($result = $mysqli->query($query)) { /* Get field information for 2nd column */ $result->field_seek(1). Parameters result Procedural style only: A result set identifier returned by mysqli_query. mysqli_field_seek • mysqli_result::field_seek mysqli_field_seek Set result pointer to a specified field offset Description Object oriented style bool mysqli_result::field_seek( int fieldnr). $finfo->flags). Sets the field cursor to the given offset. pass an offset value of zero. printf("max. printf("Flags: %d\n". printf("Name: %s\n". printf("Table: %s\n". The next call to mysqli_fetch_field will retrieve the field definition of the column associated with that offset. "my_user". Len: %d\n". $result->close(). } $query = "SELECT Name. Examples Example 3. $finfo = $result->fetch_field(). This value must be in the range from 0 to number of fields . mysqli_connect_error()). Procedural style bool mysqli_field_seek( mysqli_result result. $finfo->table). The field number. exit().127. $finfo->name).mysqli_result::field_seek.1. "my_password". "world"). $finfo->type).

$finfo->max_length). mysqli_connect_error()). printf("Flags: %d\n".11. printf("max. Procedural style <?php $link = mysqli_connect("localhost". } /* close connection */ mysqli_close($link). $finfo->type). "my_user". printf("Name: %s\n".mysqli_result::free. printf("Type: %d\n\n". $finfo->table). $finfo->name). mysqli_free_result($result). $query)) { /* Get field information for 2nd column */ mysqli_field_seek($result. [1] • mysqli_result::free mysqli_free_result Frees the memory associated with a result Description Object oriented style 275 .13. 1). $finfo->flags). mysqli_free_result Copyright 1997-2012 the PHP Documentation Group. ?> Example 3. if ($result = mysqli_query($link. "world"). } $query = "SELECT Name. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".128. Len: %d\n". mysqli_free_result } /* close connection */ $mysqli->close(). "my_password". SurfaceArea from Country ORDER BY Code LIMIT 5". printf("Table: %s\n". ?> The above examples will output: Name: Table: max. $finfo = mysqli_fetch_field($result). mysqli_result::free. Len: Flags: Type: SurfaceArea Country 10 32769 4 See Also mysqli_fetch_field 3. exit().

[1] • 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 . mysqli_fetch_lengths Copyright 1997-2012 the PHP Documentation Group.mysqli_result::$lengths. See Also mysqli_query mysqli_stmt_store_result mysqli_store_result mysqli_use_result Procedural style only: A result set identifier returned by mysqli_query. Parameters 276 . void mysqli_result::close(). mysqli_result::$lengths. 3. Note You should always free your result with mysqli_free_result. when your result object is not needed anymore. void mysqli_result::free_result(). Procedural style array mysqli_fetch_lengths( mysqli_result result). mysqli_store_result or mysqli_use_result.14. Procedural style void mysqli_free_result( mysqli_result result). Parameters result Return Values No value is returned. Frees the memory associated with the result.11. The mysqli_fetch_lengths function returns an array containing the lengths of every column of the current row within the result set. mysqli_fetch_lengths void mysqli_result::free().

Return Values An array of integers representing the size of each column (not including any terminating null characters). "my_password". ?> Example 3. if ($result = mysqli_query($link. "world"). /* display column lengths */ foreach ($result->lengths as $i => $val) { printf("Field %2d has Length %2d\n". exit(). mysqli_connect_error()). "my_user". ?> The above examples will output: 277 . mysqli_store_result or mysqli_use_result.129. } /* close connection */ $mysqli->close(). } $result->close(). /* display column lengths */ foreach (mysqli_fetch_lengths($result) as $i => $val) { printf("Field %2d has Length %2d\n". $query)) { $row = mysqli_fetch_row($result).130. $i+1. } /* close connection */ mysqli_close($link). FALSE if an error occurred. $val). } mysqli_free_result($result). Procedural style <?php $link = mysqli_connect("localhost". mysqli_fetch_lengths is valid only for the current row of the result set. } $query = "SELECT * from Country ORDER BY Code LIMIT 1". $val). if ($result = $mysqli->query($query)) { $row = $result->fetch_row(). } $query = "SELECT * from Country ORDER BY Code LIMIT 1". "world").mysqli_result::$lengths. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result. exit(). mysqli_fetch_lengths result Procedural style only: A result set identifier returned by mysqli_query. /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". mysqli_connect_error()). "my_password". "my_user". Object oriented style <?php $mysqli = new mysqli("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". Examples Example 3. $i+1.

Examples Procedural style only: A result set identifier returned by mysqli_query. The behaviour of mysqli_num_rows depends on whether buffered or unbuffered result sets are being used.mysqli_result::$num_rows. Parameters result Return Values Returns number of rows in the result set.15. Procedural style int mysqli_num_rows( mysqli_result result). Returns the number of rows in the result set. mysqli_num_rows 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 3. mysqli_result::$num_rows. mysqli_store_result or mysqli_use_result. Note If the number of rows is greater than MAXINT . the number will be returned as a string. mysqli_num_rows will not return the correct number of rows until all the rows in the result have been retrieved. 278 . For unbuffered result sets. [1] • mysqli_result::$num_rows mysqli_num_rows Gets the number of rows in a result Description Object oriented style int mysqli_result->num_rows . mysqli_num_rows Copyright 1997-2012 the PHP Documentation Group.11.

132. exit(). "world"). mysqli_connect_error()).131. $row_cnt). /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n".\n". } /* close connection */ mysqli_close($link). The mysqli_driver class (mysqli_driver) Copyright 1997-2012 the PHP Documentation Group. exit(). } if ($result = $mysqli->query("SELECT Code. } if ($result = mysqli_query($link. Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = $result->num_rows. $row_cnt). printf("Result set has %d rows. "my_password". ?> The above examples will output: Result set has 239 rows. ?> Example 3.The mysqli_driver class (mysqli_driver) Example 3. Object oriented style <?php $mysqli = new mysqli("localhost". /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n". "SELECT Code. printf("Result set has %d rows.12. "my_user".\n". mysqli_connect_error()). } /* close connection */ $mysqli->close(). /* close result set */ mysqli_free_result($result). Procedural style <?php $link = mysqli_connect("localhost". "my_user". [1] 279 . See Also mysqli_affected_rows mysqli_store_result mysqli_use_result mysqli_query 3. /* close result set */ $result->close(). "world"). "my_password". Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = mysqli_num_rows($result).

See also mysqli_report. public readonly string embedded . mysqli_embedded_server_end MySQLi Driver.mysqli_driver::embedded_server_end. [1] • mysqli_driver::embedded_server_end mysqli_embedded_server_end Stop embedded server 280 . bool mysqli_driver::embedded_server_start( bool start. mysqli_embedded_server_end Copyright 1997-2012 the PHP Documentation Group. mysqli_driver::embedded_server_end. mysqli_driver { mysqli_driver Properties public readonly string client_info .12. MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors). array groups). Methods void mysqli_driver::embedded_server_end(). public readonly string client_version .reconnect INI directive) Set to MYSQLI_REPORT_OFF . public int report_mode .1. public bool reconnect . MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes). 3. array arguments. } client_info client_version driver_version embedded reconnect report_mode 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. public readonly string driver_version .

2. [1] • 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. array groups). public 281 . only its argument list is available. 3. Warning This function is currently not documented. Warning This function is currently not documented. Procedural style bool mysqli_embedded_server_start( bool start. 3. mysqli_embedded_server_start Description Object oriented style void mysqli_driver::embedded_server_end().13.mysqli_driver::embedded_server_start. array arguments. array groups).12. only its argument list is available. Procedural style void mysqli_embedded_server_end(). mysqli_warning { mysqli_warning Properties public message . The mysqli_warning class (mysqli_warning) Copyright 1997-2012 the PHP Documentation Group. [1] Represents a MySQL warning. mysqli_driver::embedded_server_start. mysqli_embedded_server_start Copyright 1997-2012 the PHP Documentation Group. array arguments.

only its argument list is available. Return Values 3. mysqli_warning::__construct Copyright 1997-2012 the PHP Documentation Group.1. } message sqlstate errno Message string SQL state Error number 3. Parameters 282 . only its argument list is available.mysqli_warning::__construct sqlstate . Parameters This function has no parameters.13. public errno . [1] • mysqli_warning::next The next purpose Description public void mysqli_warning::next(). [1] • mysqli_warning::__construct The __construct purpose Description public mysqli_warning::__construct(). Methods public mysqli_warning::__construct(). mysqli_warning::next Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented.13. Warning This function is currently not documented.2. public void mysqli_warning::next().

The line with the error. 3.4. [1] • mysqli_bind_param Alias for mysqli_stmt_bind_param Description This function is an alias of mysqli_stmt_bind_param. Aliases and deprecated Mysqli Functions Copyright 1997-2012 the PHP Documentation Group. The mysqli_sql_exception class (mysqli_sql_exception) Copyright 1997-2012 the PHP Documentation Group. The sql state with the error. Warning This function has been DEPRECATED as of PHP 5.15. Return Values 3. The code causing the error.15. mysqli_bind_param Copyright 1997-2012 the PHP Documentation Group.0. [1] The mysqli exception handling class. } message file line code sqlstate The error message.1.14.The mysqli_sql_exception class (mysqli_sql_exception) This function has no parameters.0 and REMOVED as of PHP 5. [1] 3.3. protected sqlstate . The file with the error. mysqli_sql_exception { mysqli_sql_exceptionextends RuntimeException Properties protected code . See Also mysqli_stmt_bind_param 283 .

0 and REMOVED as of PHP 5.5. [1] 284 .3.3.4.15. [1] • mysqli_connect Alias of mysqli::__construct Description This function is an alias of: mysqli::__construct 3. mysqli_client_encoding Copyright 1997-2012 the PHP Documentation Group. mysqli_disable_reads_from_master Copyright 1997-2012 the PHP Documentation Group. See Also mysqli_real_escape_string 3. Warning This function has been DEPRECATED as of PHP 5.15. mysqli::disable_reads_from_master.15. Warning This function has been DEPRECATED as of PHP 5.4.0. mysqli_bind_result Copyright 1997-2012 the PHP Documentation Group.mysqli_bind_result 3. See Also mysqli_stmt_bind_result 3.0 and REMOVED as of PHP 5.2. [1] • mysqli_client_encoding Alias of mysqli_character_set_name Description This function is an alias of mysqli_character_set_name. [1] • mysqli_bind_result Alias for mysqli_stmt_bind_result Description This function is an alias of mysqli_stmt_bind_result.3.15. mysqli_connect Copyright 1997-2012 the PHP Documentation Group.4.0.

15. [1] • mysqli_disable_rpl_parse Disable RPL parse Description bool mysqli_disable_rpl_parse( mysqli link).3. 285 . Warning This function is currently not documented.15. only its argument list is available. mysqli_disable_rpl_parse Copyright 1997-2012 the PHP Documentation Group.mysqli_disable_rpl_parse • mysqli::disable_reads_from_master mysqli_disable_reads_from_master Disable reads from master Description Object oriented style void mysqli::disable_reads_from_master(). [1] • mysqli_enable_reads_from_master Enable reads from master Description bool mysqli_enable_reads_from_master( mysqli link). Warning This function is currently not documented. only its argument list is available. mysqli_enable_reads_from_master Copyright 1997-2012 the PHP Documentation Group.6. Warning This function has been DEPRECATED and REMOVED as of PHP 5.7. 3. Procedural style bool mysqli_disable_reads_from_master( mysqli link).3. 3.0. Warning This function has been DEPRECATED and REMOVED as of PHP 5.0.

mysqli_execute Copyright 1997-2012 the PHP Documentation Group. Warning This function has been DEPRECATED and REMOVED as of PHP 5. [1] • mysqli_execute Alias for mysqli_stmt_execute Description This function is an alias of mysqli_stmt_execute.3. Warning This function has been DEPRECATED and REMOVED as of PHP 5. 3.8.0. 286 . [1] • 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.0.15. only its argument list is available. mysqli_enable_rpl_parse Copyright 1997-2012 the PHP Documentation Group.15.10. mysqli_escape_string Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli_enable_rpl_parse Enable RPL parse Description bool mysqli_enable_rpl_parse( mysqli link). 3. Warning This function is currently not documented. Notes Note mysqli_execute is deprecated and will be removed.15.3.9.mysqli_enable_rpl_parse Warning This function is currently not documented. 3.

3.15. [1] • mysqli_fetch Alias for mysqli_stmt_fetch Description This function is an alias of mysqli_stmt_fetch.11.mysqli_fetch See Also mysqli_stmt_execute 3. only its argument list is available. FALSE otherwise.0. mysqli_fetch Copyright 1997-2012 the PHP Documentation Group.0 and REMOVED as of PHP 5.133. print_r(mysqli_get_cache_stats()). Warning This function has been DEPRECATED as of PHP 5.12. Examples Example 3. See Also mysqli_stmt_fetch 3. Available only with mysqlnd. A mysqli_get_cache_stats example <?php $link = mysqli_connect(). Warning This function is currently not documented. Returns client Zval cache statistics. Parameters Return Values Returns an array with client Zval cache stats if success. ?> 287 .15. mysqli_get_cache_stats Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli_get_cache_stats Returns client Zval cache statistics Description array mysqli_get_cache_stats().4.

mysqli_get_cache_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 [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 288 .

mysqli_get_cache_stats [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 ) See Also Stats description 289 .

Warning This function has been DEPRECATED as of PHP 5. mysqli_param_count Copyright 1997-2012 the PHP Documentation Group. 290 .0 and REMOVED as of PHP 5.13. [1] • mysqli_master_query Enforce execution of a query on the master in a master/slave setup Description bool mysqli_master_query( mysqli link.3.15. Warning This function has been DEPRECATED and REMOVED as of PHP 5.3. Warning This function has been DEPRECATED as of PHP 5.4.15. See Also mysqli_stmt_result_metadata 3. string query). [1] • mysqli_param_count Alias for mysqli_stmt_param_count Description This function is an alias of mysqli_stmt_param_count. mysqli_get_metadata Copyright 1997-2012 the PHP Documentation Group.0. only its argument list is available. mysqli_master_query Copyright 1997-2012 the PHP Documentation Group.4.0 and REMOVED as of PHP 5. Warning This function is currently not documented.15.mysqli_get_metadata 3.15. 3.3.0. [1] • mysqli_get_metadata Alias for mysqli_stmt_result_metadata Description This function is an alias of mysqli_stmt_result_metadata.14.0.

16.mysqli_report See Also mysqli_stmt_param_count 3. "my_user". rather than per-process. Changelog Version 5. $mysqli = new mysqli("localhost". mysqli_report is a powerful function to improve your queries and code during development and testing phase.134. "world").15 & 5.15. [1] • mysqli_report Enables or disables internal report functions Description bool mysqli_report( int flags). Supported flags Name MYSQLI_REPORT_OFF MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT MYSQLI_REPORT_INDEX MYSQLI_REPORT_ALL Return Values Returns TRUE on success or FALSE on failure.2.3. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).4 Description Changing the reporting mode is now be per-request. Object oriented style <?php /* activate reporting */ mysqli_report(MYSQLI_REPORT_ALL). mysqli_report Copyright 1997-2012 the PHP Documentation Group. /* check connection */ if (mysqli_connect_errno()) { 291 . Parameters flags Table 3. "my_password".19. 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) Examples Example 3.

18.3. exit(). [1] • mysqli_rpl_parse_enabled Check if RPL parse is enabled Description int mysqli_rpl_parse_enabled( mysqli link).15. $result->close(). mysqli_rpl_probe Copyright 1997-2012 the PHP Documentation Group.3. /* this query should report a bad index */ $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"). only its argument list is available. only its argument list is available. Warning This function has been DEPRECATED and REMOVED as of PHP 5. [1] • mysqli_rpl_probe RPL probe Description bool mysqli_rpl_probe( mysqli link). $mysqli->close(). 292 . Warning This function is currently not documented.15. } /* this query should report an error */ $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000"). mysqli_connect_error()). mysqli_rpl_parse_enabled Copyright 1997-2012 the PHP Documentation Group. ?> See Also mysqli_driver::$report_mode mysqli_debug mysqli_dump_debug_info 3.17.mysqli_rpl_parse_enabled printf("Connect failed: %s\n". Warning This function is currently not documented.0. Warning This function has been DEPRECATED and REMOVED as of PHP 5.0. 3.

15. 3. Warning This function has been DEPRECATED as of PHP 5.15.0 and REMOVED as of PHP 5.21. mysqli_slave_query Copyright 1997-2012 the PHP Documentation Group.20. 3. only its argument list is available.19. [1] 293 . string query).4.3.0. mysqli_send_long_data Copyright 1997-2012 the PHP Documentation Group. [1] • mysqli_send_long_data Alias for mysqli_stmt_send_long_data Description This function is an alias of mysqli_stmt_send_long_data. Changelog Copyright 1997-2012 the PHP Documentation Group.mysqli_send_long_data 3. Warning This function has been DEPRECATED and REMOVED as of PHP 5.0.16. mysqli_set_opt Copyright 1997-2012 the PHP Documentation Group. Warning This function is currently not documented.15.3. [1] • mysqli_slave_query Force execution of a query on a slave in a master/slave setup Description bool mysqli_slave_query( mysqli link. [1] • mysqli_set_opt Alias of mysqli_options Description This function is an alias of mysqli_options. See Also mysqli_stmt_send_long_data 3.

Changelog

The following changes have been made to classes/functions/methods of this extension.

294

Chapter 4. MySQL Native Driver (Mysqlnd)
Table of Contents
4.1. 4.2. 4.3. 4.4. 4.5. 4.6. 4.7. Overview ................................................................................................................................. Installation ............................................................................................................................... Runtime Configuration .............................................................................................................. Persistent Connections ............................................................................................................. Statistics .................................................................................................................................. Notes ...................................................................................................................................... MySQL Native Driver Plugin API .............................................................................................. 4.7.1. A comparison of mysqlnd plugins with MySQL Proxy ...................................................... 4.7.2. Obtaining the mysqlnd plugin API .................................................................................. 4.7.3. MySQL Native Driver Plugin Architecture ....................................................................... 4.7.4. The mysqlnd plugin API ................................................................................................ 4.7.5. Getting started building a mysqlnd plugin ....................................................................... 295 296 297 301 302 316 316 317 318 319 323 325

Copyright 1997-2012 the PHP Documentation Group. [1] MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0. The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its clientserver protocol. With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library. MySQL Native Driver is written in C as a PHP extension.

4.1. Overview
Copyright 1997-2012 the PHP Documentation Group. [1] What it is not Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API. Why use it? Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library. The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past. Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions

295

Installation

would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications. Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory. Reporting memory usage Because MySQL Native Driver uses the PHP memory management system, its memory usage can be tracked with memory_get_usage. This is not possible with libmysql because it uses the C function malloc() instead. Special features MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below: • Improved persistent connections • The special function mysqli_fetch_all • Performance statistics calls: mysqli_get_cache_stats, mysqli_get_client_stats, mysqli_get_connection_stats The performance statistics facility can prove to be very useful in identifying performance bottlenecks. MySQL Native Driver also allows for persistent connections when used with the mysqli extension. SSL Support MySQL Native Driver has supported SSL since PHP version 5.3.3 Compressed Protocol Support As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, that are configured to use MySQL Native Driver, can also take advantage of this feature. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd. Named Pipes Support Named pipes support for Windows was added in PHP version 5.4.0.

4.2. Installation
Copyright 1997-2012 the PHP Documentation Group. [1] Changelog Table 4.1. Changelog Version 5.3.0 Description The MySQL Native Driver was added, with support for all MySQL extensions (i.e., mysql, mysqli

296

Runtime Configuration

Version

Description and PDO_MYSQL). Passing in mysqlnd to the appropriate configure switch enables this support. The MySQL Native Driver is now the default for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to configure is now optional. SHA-256 Authentication Plugin support was added

5.4.0

5.5.0 Installation on Unix

The MySQL database extensions must be configured to use the MySQL Client Library. In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code. For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:
./configure --with-mysql=mysqlnd \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ [other options]

Installation on Windows In the official PHP Windows distributions from 5.3 onwards, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case. SHA-256 Authentication Plugin support The MySQL Native Driver requires the OpenSSL functionality of PHP to be loaded and enabled to connect to MySQL through accounts that use the MySQL SHA-256 Authentication Plugin. For example, PHP could be configured using:
./configure --with-mysql=mysqlnd \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ --with-openssl [other options]

4.3. Runtime Configuration
Copyright 1997-2012 the PHP Documentation Group. [1] The behaviour of these functions is affected by settings in php.ini. Table 4.2. MySQL Native Driver Configuration Options Name Default Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM Changelog Available since PHP 5.3.0. Available since PHP 5.3.0.

mysqlnd.collect_statistics "1" mysqlnd.collect_memory_statistics "0"

297

Runtime Configuration

Name mysqlnd.debug mysqlnd.log_mask

Default "0" 0

Changeable PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_SYSTEM PHP_INI_PERDIR

Changelog Available since PHP 5.3.0. Available since PHP 5.3.0 Available since PHP 5.3.3 Available since PHP 5.3.0. Available since PHP 5.3.0. Available since PHP 5.3.0. Available since PHP 5.5.0.

mysqlnd.mempool_default_size 16000 mysqlnd.net_read_timeout"31536000" mysqlnd.net_cmd_buffer_size - "2048", 5.3.1 5.3.0 "4096" mysqlnd.net_read_buffer_size "32768" mysqlnd.sha256_server_public_key ""

For further details and definitions of the PHP_INI_* modes, see the http://www.php.net/manual/en/ configuration.changes.modes. Here's a short explanation of the configuration directives. mysqlnd.collect_statisticsEnables the collection of various client statistics which boolean can be accessed through mysqli_get_client_stats, mysqli_get_connection_stats, mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well. This configuration setting enables all MySQL Native Driver statistics except those relating to memory management. mysqlnd.collect_memory_statistics collection of various memory statistics which Enable the boolean can be accessed through mysqli_get_client_stats, mysqli_get_connection_stats, mysqli_get_cache_stats and are shown in mysqlnd section of the output of the phpinfo function as well. This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics. mysqlnd.debug string Records communication from all extensions using mysqlnd to the specified log file. The format of the directive is mysqlnd.debug = "option1[,parameter_option1] [:option2[,parameter_option2]]". The options for the format string are as follows: • A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash. 298

Runtime Configuration

• a[,file] - Appends trace output to the specified file. • d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros. • f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected. • F - Marks each debugger output line with the name of the source file containing the macro causing the output. • i - Marks each debugger output line with the PID of the current process. • L - Marks each debugger output line with the name of the source file line number of the macro causing the output. • n - Marks each debugger output line with the current function nesting depth • o[,file] - Similar to a[,file] but overwrites old file, and does not append. • O[,file] - Similar to A[,file] but overwrites old file, and does not append. • t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200. • x - This option activates profiling. Example:
d:t:x:O,/tmp/mysqlnd.trace

Note This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above. mysqlnd.log_mask integer Defines which queries will be logged. The default 0, which disables logging. Define using an integer, and not with PHP constants. For example, a value of 48 (16 + 32) will log slow queries which either use 'no good index' (SERVER_QUERY_NO_GOOD_INDEX_USED = 16) or no index at all (SERVER_QUERY_NO_INDEX_USED = 32). A value of 2043 (1 + 2 + 8 + ... + 1024) will log all slow query types. The types are as follows: SERVER_STATUS_IN_TRANS=1, SERVER_STATUS_AUTOCOMMIT=2, SERVER_MORE_RESULTS_EXISTS=8, SERVER_QUERY_NO_GOOD_INDEX_USED=16, SERVER_QUERY_NO_INDEX_USED=32,

299

Runtime Configuration

SERVER_STATUS_CURSOR_EXISTS=64, SERVER_STATUS_LAST_ROW_SENT=128, SERVER_STATUS_DB_DROPPED=256, SERVER_STATUS_NO_BACKSLASH_ESCAPES=512, and SERVER_QUERY_WAS_SLOW=1024. mysqlnd.mempool_default_size Default size of the mysqlnd memory pool, which is used by result sets. integer mysqlnd.net_read_timeout integer mysqlnd and the MySQL Client Library, libmysql use different networking APIs. mysqlnd uses PHP streams, whereas libmysql uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message “2006 - MySQL Server has gone away”. The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout. The value is configurable through a new php.ini setting: mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by any extension (ext/ mysql, ext/mysqli, PDO_MySQL) that uses mysqlnd. mysqlnd tells PHP Streams to use mysqlnd.net_read_timeout. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt.

mysqlnd.net_cmd_buffer_size mysqlnd allocates an internal command/network buffer of long mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (“normal” query), does not fit into the buffer, mysqlnd will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, command_buffer_too_small will be incremented by one. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, you should consider increasing the default size to avoid re-allocations. The default buffer size is 2048 bytes in PHP 5.3.0. In later versions the default is 4096 bytes. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size). It is recommended that the buffer size be set to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence, mysqlnd is unable to decode the

300

mysqlnd reads the body in chunks of MIN(header. size). For example: shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" .Persistent Connections packet and the client application will get an error./configure --with-mysql=/usr/local/mysql/ --with-mysql Or alternatively: shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" 301 . specify the key through this PHP configuration setting or set the key at runtime using mysqli_options.net_cmd_buffer_size in PHP 5. 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). The size of the body is encoded in the header. size). There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd. when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server.net_read_buffer_size) bytes.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes. The packets consist of a small header and a body with the actual payload. Persistent Connections Copyright 1997-2012 the PHP Documentation Group. then the key will be exchanged as part of the standard SHA-256 Authentication Plugin authentication procedure. Clients can either omit setting a public RSA key.3.sha256_server_public_key Authentication Plugin related.size. As of PHP 5.0: the packet transports a very long error message. If not public RSA key file is given by the client.net_read_buffer_size Maximum read chunk size in bytes when reading the body of a MySQL long command packet. mysqlnd. This ensures that re-authentication of the connection takes place. mysqlnd. 4. mysqlnd. MYSQLI_OPT_NET_READ_BUFFER_SIZE. MYSQLI_OPT_NET_CMD_BUFFER_SIZE.4.net_read_buffer_size bytes. mysqlnd has to call read() multiple times. it is possible to switch this off at compile time. File with the MySQL server SHA-256 string public RSA key. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable. The value can also be set using mysqli_options(link. If a packet body is larger than mysqlnd. As there is some overhead associated with the COM_CHANGE_USER call. [1] Using Persistent Connections If mysqli is used with mysqlnd. The value can also be set using mysqli_options(link. The MySQL client server protocol encapsulates all its commands in packets. Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT.

you need to call mysqli_get_client_stats. Accessing Zval Cache Statistics 302 . Other extension-driver combinations use COM_PING on initial use of a persistent connection. when compiling both ext/mysql and ext/mysqli against MySQL Native Driver. Client statistics can also be accessed by calling the phpinfo function.5. Statistics Copyright 1997-2012 the PHP Documentation Group. When doing so. This takes the database connection handle as the parameter. Accessing Connection Statistics To access connection statistics call mysqli_get_connection_stats. The function call does not require any parameters. ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. all three extensions will change the statistics. these statistics can be obtained through three API calls: • mysqli_get_client_stats • mysqli_get_connection_stats • mysqli_get_cache_stats Note Statistics are aggregated among all extensions that use MySQL Native Driver. Accessing Client Statistics To access client statistics. 4. 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 statistics gathered are of three main types: • Client statistics • Connection statistics • Zval cache statistics If you are using the mysqli extension. The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value. [1] Using Statistical Data MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. You can configure the PDO MySQL Driver. For example. both function calls of ext/mysql and ext/mysqli will change the statistics. The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.Statistics shell# configure --whatever-option shell# make clean shell# make Note that only mysqli on mysqlnd uses COM_CHANGE_USER.

use unbuffered results. Clients typically scale better than servers. If you want to reduce memory consumption on the client. but increase load on the server. before a result set can be freed.3.Statistics The MySQL Native Driver also collects statistics from its internal Zval cache. “Load” does not only refer to memory buffers . However. for example file handles and threads. The Zval cache statistics obtained may lead to a tweaking of php. Table 4. you should consider moving the load to the clients. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. mysqli_get_connection_stats and mysqli_get_cache_stats functions. protocol_overhead_out = packets_sent * 4 Used for debugging Client Server protocol implementation Used for debugging Client Server protocol implementation bytes_received_ok_packet bytes of MySQL Client Connection Total size of Used for debugging CS protocol Server protocol OK packets received. Using default settings.ini settings related to the Zval cache. you can use mysqli_stmt_store_result to enable buffered result sets. Prepared Statements use unbuffered result sets by default. If you experience a high server load and the figures for unbuffered result sets are high. protocol_overhead_in = packets_received * 4 protocol_overhead_out Client Server protocol Connection MySQL overhead in bytes for outgoing traffic. ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. These statistics can be accessed by calling mysqli_get_cache_stats. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set. Currently only the Packet Header (4 bytes) is considered as overhead. Returned mysqlnd statistics: Network Statistic Scope Description Notes Can be used to check the efficiency of the compression protocol Can be used to check the efficiency of the compression protocol bytes_sent Connection Number of bytes sent from PHP to the MySQL server bytes_received Number of bytes received from MySQL Connection server packets_sent Connection Number of MySQL Client Server protocol Used for debugging Client Server packets sent protocol implementation packets_receivedNumber of MySQL Client Server protocol Used for debugging Client Server Connection packets received protocol implementation protocol_overhead_in Client Server protocol Connection MySQL overhead in bytes for incoming traffic. resulting in better performance. OK implementation. Buffered result sets are cached on the client. once the results have been fetched by the client. Unbuffered result sets on the other hand are kept much longer on the server. Note that the total size 303 . Buffered and Unbuffered Result Sets Result sets can be buffered or unbuffered. Currently only the Packet Header (4 bytes) is considered as overhead. Statistics returned by MySQL Native Driver The following tables show a list of statistics returned by the mysqli_get_client_stats.the server also needs to keep other resources open.

Note that the total size in bytes includes the size of the header packet (4 bytes. bytes_received_rset_row_packet MySQL Client Connection Total size in bytes of Server protocol result set row data packets. The packet may also transport an error or an EOF packet. packets_received_rset_field_meta Connection Number of MySQL Client Server protocol Only useful for debugging CS protocol result set meta data (field information) implementation. bytes_received_rset_field_meta_packet Client Connection Total size in bytes of MySQL Server protocol result set meta data (field information) packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE. see protocol overhead). error message). Used for debugging CS protocol implementation. see protocol overhead). Of course the size varies with the fields in the result set. bytes_received_eof_packet bytes of MySQL Client Connection Total size in Server protocol EOF packets received. an error message.Statistics Statistic Scope Description Notes packets can contain a status message. Note that the total size in bytes includes the size of the header packet (4 bytes. implementation. see protocol overhead). EOF can vary in size depending on the server version. SELECT. see protocol overhead). The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. Also. see protocol overhead). see protocol overhead). implementation. for example. 304 . Note that the total size packets. packets_received_rset_header Client Server protocol Used for debugging CS protocol Connection Number of MySQL result set header packets. 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. Note that the total size in bytes includes the size of the header packet (4 bytes. see protocol overhead). Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes. Note that the total size in bytes includes the size of the header packet (4 bytes. EOF can transport an error message. UPDATE. You can reverse engineer the number of error and EOF packets by subtracting rows_fetched_from_server_normal and rows_fetched_from_server_ps Only useful for debugging CS protocol implementation. INSERT. vary and thus the size of an OK packet is not fixed. Used for debugging CS protocol implementation. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but. Note that the total size in bytes includes the size of the header packet (4 bytes. Used for debugging CS protocol implementation. see protocol overhead). see protocol overhead). in bytes includes the size of the header The length of the status message can packet (4 bytes. packets_received_eof of MySQL Client Server protocol Connection Number EOF packets. bytes_received_rset_header_packet Connection Total size in bytes of MySQL Client Server protocol result set header packets. packets_received_ok Connection Number of MySQL Client Server protocol Used for debugging CS protocol OK packets received.

Only useful for debugging CS protocol implementation. Note that the total size size in bytes. bytes_received_change_user_packet Connection Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. packets_sent_command of MySQL Client Server protocol Only useful for debugging CS protocol Connection Number commands sent from PHP to MySQL.Statistics Statistic Scope Description Notes from bytes_received_rset_row_packet. The packet packet (4 bytes. see protocol overhead). The only error that is recorded is command_buffer_too_small (see below). At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. may also transport an error. The packet may also transport an error or EOF.0 on. 305 . packets_received_prepare_response Server Connection Number of MySQL Client protocol OK for Prepared Statement Initialization packets (prepared statement init packets). packets_received_rset_row Connection Number of MySQL Client Server protocol Only useful for debugging CS protocol result set row data packets and their total implementation. There is no safe way to know how many errors happened. packets_received_change_user Client Server protocol Only useful for debugging CS protocol Connection Number of MySQL COM_CHANGE_USER packets implementation. you always connect to MySQL 5. Note that the total size Statement Initialization packets (prepared in bytes includes the size of the header statement init packets). bytes_received_prepare_response_packet Connection Total size in bytes of MySQL Client Only useful for debugging CS protocol Server protocol OK for Prepared implementation.0 or newer and. Note that the total size in bytes includes the size of the header packet (4 bytes. You may be able to guess that an error has occurred if. see protocol overhead). for example. bytes_received_prepare_response_packet != packets_received_prepare_response * 12. Note that the total size in bytes includes the size of the header packet (4 bytes. ps_prepared_once_executed. Note that the total size in bytes includes the size of the header packet (4 bytes. Only useful for debugging CS protocol implementation. see protocol overhead).1 and 12 bytes from MySQL 5. see protocol overhead). see protocol overhead). There is no way to know which specific commands and how many of them have been sent. See also ps_prepared_never_executed. in bytes includes the size of the header packet (4 bytes. implementation. The packet size depends on the MySQL version: 9 bytes with MySQL 4.

but not fetched. bytes_received_real_data_ps of the payload fetched Connection Number of bytes by the PHP client from mysqlnd using the prepared statement protocol. See also bytes_received_real_data_normal. $res->close(). This statistic is available as of PHP version 5. The 306 . this statistic only counts actual data pulled from mysqlnd by the PHP client. Result Set Table 4.4. $res->fetch_assoc().3. The statistic will not be increased if the result set is only buffered on the client. Every fetch operation will increase the value.4. This statistic is available as of PHP version 5. such as in the following example: $mysqli = new mysqli(). Note that although a full result set may have been pulled from MySQL by mysqlnd.4. this statistic only counts actual data pulled from mysqlnd by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd. $res->close(). Returned mysqlnd statistics: Result Set Statistic Scope Description Notes result_set_queries Connection Number of queries that have generated You may use it as an indirect measure for a result set. $res = $mysqli->query("SELECT 'abc'"). $res = $mysqli->query("SELECT 'abc'"). Examples of queries that the number of queries PHP has sent to generate a result set: SELECT. SHOW.Statistics Statistic Scope Description Notes 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. bytes_received_real_data_normal Connection Number of bytes of payload fetched by the PHP client from mysqlnd using the text protocol.3. This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. An example of a code sequence that will increase the value is as follows: $mysqli = new mysqli().

mysqli_query. mysqli_stmt_get_result. to identify a client that causes a high database load. Notes MySQL. for example.Statistics Statistic Scope Description statistic will not be incremented if there is an error reading the result set header packet from the line. Examples of queries that do not generate a result set: INSERT. This is also the reason why memory_get_usage reports 307 . If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. SHOW. UPDATE. to identify a client that causes a high database load. If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. bad_index_used Number of queries that have generated Connection a result set and did not use a good index (see also mysqld start option –log-slowqueries). for example. Examples of API calls that will buffer result sets on the client: mysql_query. The statistic will not be incremented if there is an error reading the result set header packet from the line. LOAD DATA. mysqli_store_result. buffered_sets Connection Number of buffered result sets returned by “normal” queries. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT). no_index_used Connection Number of queries that have generated a result set but did not use an index (see also mysqld start option –log-queriesnot-using-indexes). You may use it as an indirect measure for the number of queries PHP has sent to MySQL. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT) slow_queries Connection SQL statements that took more Not reported through mysqli_report than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. non_result_set_queries of queries that did not generate Connection Number a result set. Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. “Normal” means “not prepared statement” in the following notes. The downside is the additional memory consumption on the client for buffering data.

flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. ps_unbuffered_sets Connection Number of unbuffered result sets returned by prepared statements. rows_skipped_ps. If the application does not fetch all rows from an unbuffered result set. See also rows_skipped_normal.Statistics Statistic Scope Description Notes a higher memory consumption when using mysqlnd instead of the MySQL Client Library. 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 unbuffered_sets Number of unbuffered result sets Connection returned by normal (non prepared statement) queries. Flushing happens only with unbuffered result sets. By default prepared statements are unbuffered. If the application does not fetch all rows from an unbuffered result set. rows_skipped_ps. See also rows_skipped_normal. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. 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! Examples of API calls that will not buffer result sets on the client: mysqli_use_result Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_result By default prepared statements are unbuffered. Some possible causes for an implicit flush: • Faulty client application • Client stopped reading after it found what it was looking for but has made 308 . flushed_ps_sets Number of result sets from prepared Connection statements with unread data which have been flushed silently for you. ps_buffered_setsNumber of buffered result sets returned Connection by prepared statements. mysqlnd does implicitly fetch the result set to clear the line. Flushing happens only with unbuffered result sets. mysqlnd does implicitly fetch the result set to clear the line.

See also packets_received_rset_row rows_buffered_from_client_normal. if statement execution is split up in separate prepare and execute stages. 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. or a prepared statement. for example. 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). 309 . prepared statements that are executed only once may cause performance hurts. the parse tree to be reused during multiple statement executions. 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. Connection Total number of successfully buffered Examples of queries that will rows_buffered_from_client_psfrom a "normal" query rows originating buffer results: mysqli_query.Statistics Statistic Scope Description Notes MySQL calculate more records than needed • Client application has stopped unexpectedly ps_prepared_never_executed Connection Number of statements prepared but never executed. Some of the rows may not have been fetched by the client application but have been flushed implicitly. rows_fetched_from_server_normal. set rows Connection Total number of result rows_fetched_from_server_ps successfully fetched from MySQL regardless if the client application has consumed them or not. Prepared statements occupy server resources. This is the mysqli_store_result number of rows that have been fetched from MySQL and buffered on client. The idea is to prepare once and “cache” results. Consequently. You should not prepare a statement if you do not plan to execute it. ps_prepared_once_executed Connection Number of prepared statements executed One of the ideas behind prepared only one. 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.

Connection Total number of rows fetched by the rows_fetched_from_client_ps_unbuffered set created client from a unbuffered result by a "normal" query or a prepared statement. fetched data will be kept only once in memory. proto_text_fetched_year proto_text_fetched_time. If you do not change the variables. proto_text_fetched_date. mysqlnd.) 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 310 . proto_text_fetched_int24. proto_text_fetched_int proto_text_fetched_bigint. proto_text_fetched_float proto_text_fetched_double. explicit_free_result. Connection Total number of rows fetched by the rows_fetched_from_client_ps_buffered set created client from a buffered result by a normal query or a prepared statement. note that the memory saving cannot be measured using memory_get_usage. implicit_free_result Process (only during prepared statement cleanup) proto_text_fetched_null. Connection Reserved for future use (currently not rows_skipped_ps supported) copy_on_write_saved. proto_text_fetched_decimal. Connection Total number of columns of a certain type proto_text_fetched_bit. . proto_text_fetched_short. mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. mysqli_options(MYSQLI_INIT_COMMAND . rows_skipped_normal. Connection. The free is always considered explicit but for result sets created by an init command. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. rows_fetched_from_client_ps_cursor by the client Connection Total number of rows fetch from a cursor created by a prepared statement. Total number of freed result sets. However..Statistics Statistic Scope Description Notes rows_fetched_from_client_normal_buffered. rows_fetched_from_client_normal_unbuffered. If you change the variables. In theory mysqlnd can save up to 40% memory. variables returned by the Process With copy_on_write_performed point into mysqlnd internal extensions network result buffers.. fetched from a normal query (MySQL text proto_text_fetched_tinyint protocol). for example. With the MySQL Client Library you always hold fetched data twice in memory.

proto_text_fetched_blob. proto_text_fetched_geometry. proto_text_fetched_other Notes • MYSQL_TYPE_SHORT proto_text_fetched_short • MYSQL_TYPE_INT24 proto_text_fetched_int24 • MYSQL_TYPE_LONG proto_text_fetched_int • MYSQL_TYPE_LONGLONG proto_text_fetched_bigint • MYSQL_TYPE_DECIMAL. MYSQL_TYPE_LONG_BLOB. 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_MEDIUM_BLOB. MYSQL_TYPE_VARSTRING. MYSQL_TYPE_VARCHAR proto_text_fetched_string • MYSQL_TYPE_TINY_BLOB. 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. proto_text_fetched_timestamp proto_text_fetched_string. MYSQL_TYPE_BLOB proto_text_fetched_blob • MYSQL_TYPE_ENUM proto_text_fetched_enum • MYSQL_TYPE_SET proto_text_fetched_set 311 .Statistics Statistic Scope Description proto_text_fetched_datetime. proto_text_fetched_enum proto_text_fetched_set.

The number of successful non-persistent connection connect_success.. proto_binary_fetched_date.. $link>connect(. proto_binary_fetched_int24.. of columns of a certain Connection Total number proto_binary_fetched_bit. proto_binary_fetched_other Table 4. reconnectrocess P Total number of (real_)connect attempts made on an already opened connection handle.) will not because $link->connect(. from a prepared statement type fetched proto_binary_fetched_tinyint (MySQL binary protocol). The code sequence $link = new mysqli(.5. proto_binary_fetched_enum. proto_binary_fetched_decimal. proto_binary_fetched_float. But $link = new mysqli(. proto_binary_fetched_set. proto_binary_fetched_time. proto_binary_fetched_null..).) will cause a reconnect. proto_binary_fetched_year. proto_binary_fetched_bigint.. Returned mysqlnd statistics: Connection Statistic Scope Description For type mapping see proto_text_* described in the preceding text.... Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. proto_binary_fetched_string. proto_binary_fetched_datetime. proto_binary_fetched_short. 312 . proto_binary_fetched_geometry. Notes Reused connections and all other kinds of connections are included. $link>real_connect(.). proto_binary_fetched_int. proto_binary_fetched_double.. proto_binary_fetched_timestamp. Total number of successful / failed Connection connect_failure connection attempt. proto_binary_fetched_blob..Statistics Statistic Scope Description Notes • 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.) will explicitly close the existing connection before a new connection is established. pconnect_successTotal number of successful persistent Connection connection attempts.

). while transferring data with LOAD DATA). init_command_executed_count mysqli_options(MYSQLI_INIT_COMMAND .) $link = new mysqli(.... Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you. The total number of active non-persistent connections is active_connections active_persistent_connections.) • unset($link) • Persistent connection: pooled connection has been created with real_connect and there may be unknown options set . $link->real_connect(.. init_command_executed_count init command Connection Total number of The number of successful executions is executions. ... It is called disconnect_close because the connection handle passed to the C API call will be closed.. while fetching data.)..).. $link->close(. Examples of code snippets that cause an implicit close : • $link = new mysqli(.). init_command_failed_count.. Connection Total number 313 . active_connections number of active persistent and Connection Total non-persistent connections.Statistics Statistic Scope Description Notes attempts is connect_success pconnect_success.close implicitly to avoid returning a connection with unknown options • Persistent connection: ping/ change_user fails and ext/mysqli closes the connection • end of script execution: close connections that have not been closed by the user disconnect_closeConnection failures indicated by the C Connection API call mysql_real_connect during an attempt to establish a connection. Examples of code snippets that cause an explicit close : $link = new mysqli(. init_command_failed_count of failed init commands.) implicit_close Total number of implicitly closed Connection connections (ext/mysqli only).. for example. $link->connect(... explicit_close Total number of explicitly closed Connection connections (ext/mysqli only). after sending a query and before retrieving an answer. in_middle_of_command_closehas been closed in Process A connection the middle of a command execution (outstanding result sets not fetched. active_persistent_connections Connection Total number of active persistent connections..

MySQL. mem_emalloc_count. PID= %d. mem_erealloc_ammount. com_shutdown. mem_emalloc_ammount. for example. com_process_info.Statistics Table 4. explicit_stmt_close. certain COM_* command from PHP to com_query. 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 nonprepared 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 com_quit.6. com_stmt_close. mem_realloc_ammount. com_change_user. com_drop_db. mem_free_count 314 . com_stmt_send_long_data. com_create_db. com_register_slave. number of close prepared Process Total implicit_stmt_close statements. mem_malloc_ammount. com_table_dump. com_binlog_dump. com_delayed_insert. Process Memory management calls. com_field_list. mem_ecalloc_count. mem_ecalloc_ammount. com_statistics. In case of a failure mysqlnd emits a PHP warning “Error while sending %s packet. Returned mysqlnd statistics: COM_* Command Statistic Scope Description Notes The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. Returned mysqlnd statistics: Miscellaneous Statistic Scope Description Notes A close is always considered explicit but for a failed prepare.7. com_stmt_fetch. com_process_kill. com_debug. com_stmt_execute.” Usage examples: • Check if PHP sends certain commands to MySQL. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. com_stmt_reset. com_stmt_set_option. mem_malloc_count. com_time. mem_calloc_ammount. mem_erealloc_count. mem_realloc_count. com_refresh. com_connect_out. mem_efree_count. mem_calloc_count. com_daemon Miscellaneous Table 4. Connection Total number of attempts to send a com_init_db. com_connect. Development only. com_ping. com_stmt_prepare.

net_cmd_buffer_size (php. 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.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields) and the meta data comes from a string column with a very long default value (>1900 bytes). you should consider to increase the default size to avoid reallocations.0. The default buffer size is 2048 bytes in PHP 5.ini) bytes for every connection. If a MySQL Client Server protocol command. does not fit into the buffer. 315 . In PHP 5. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size (php.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFF int size).ini) bytes for almost every connection. command_buffer_too_smallnetwork command buffer Connection Number of extensions while sending commands from PHP to MySQL. The default can changed either through the php.ini setting mysqlnd. As a consequence mysqlnd is unable to decode the packet and the client application will get an error.3. If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.3. In future versions the default will be 4kB or larger. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one. mysqlnd will grow the buffer to what is needed for sending the command. mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer.0.Statistics Statistic Scope Description Notes mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size in PHP 5. COM_QUERY (normal query). for example.

4. monitoring and performance optimizations. There are no restrictions on manipulating mysqlnd internal function tables. Plugins can intercept the majority of mysqlnd functions.7. with plugins. MySQL Proxy operates on a layer between any MySQL client application. or mysqlnd. the call is directed to the appropriate function in the mysqlnd plugin. connection_reused 4. 316 . For mysqlnd. [1] This section provides a collection of miscellaneous notes on MySQL Native Driver usage. the MySQL server.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes. mysqlnd). Internal mysqlnd function calls can also be intercepted. or replaced. The mysqlnd functions are called by the PHP MySQL extensions such as ext/ mysql. MySQL Native Driver Plugin API Copyright 1997-2012 the PHP Documentation Group. Plugins can be made 100% transparent to PHP applications. It is possible to set things up so that when certain mysqlnd functions are called by the extensions that use mysqlnd. As a result. As of PHP 5. there is no single point of failure. for example. [1] The MySQL Native Driver Plugin API is a feature of MySQL Native Driver. the PHP streams documentation (http://www. Mysqlnd plugins operate in the layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. The mysqlnd plugin can be thought of as operating in a layer below mysqlnd.php. Notes Copyright 1997-2012 the PHP Documentation Group. This extension splits read/write queries for a replication setup. Mysqlnd plugins can undertake typical MySQL Proxy tasks such as load balancing. The following list represents some possible applications of mysqlnd plugins. • Using mysqlnd means using PHP streams for underlying connectivity.it should happen rarely. • Load Balancing • Read/Write Splitting.stream) should be consulted on such details as timeout settings. No application changes are needed because plugins operate on a different layer. and PDO_MYSQL. The ability to manipulate mysqlnd internal function tables in this way allows maximum flexibility for plugins.Notes Statistic Scope Description Notes No bug report on this exists . ext/mysqli. that use the mysqlnd plugin API (which is built into MySQL Native Driver. Mysqlnd plugins are in fact PHP Extensions. A mysqlnd plugin can be thought of as an extension to mysqlnd. a PHP application and. Due to the different architecture and location. no dedicated proxy server to deploy. written in C. For example.6. not the documentation for the MySQL Client Library. and no new programming language to learn (Lua).net/manual/en/book. it is possible for a mysqlnd plugin to intercept all calls made to these extensions from the client application. mysqlnd plugins do not have some of MySQL Proxy's disadvantages. An example of this is the PECL/mysqlnd_ms (Master Slave) extension.

• Performance • Caching.Master Slave plugin. Deploying MySQL Proxy on the application server has two advantages: 1. • PECL/mysqlnd_qc . SELECT LIMIT part_n. As a PHP Extension.7.SQL Injection Protection plugin. LIMIT part_1. A comparison of mysqlnd plugins with MySQL Proxy Copyright 1997-2012 the PHP Documentation Group. along with the rest of PHP. least loaded • Monitoring • Query Logging • Query Analysis • Query Auditing. and performance enhancements. Easy to scale out (horizontal scale out. These include: • PECL/mysqlnd_mc . This extension will attempt to split a SELECT statement into n-parts. MySQL Native Driver Plugins Available There are a number of mysqlnd plugins already available.Prepared Statement Handle Cache plugin. • PECL/mysqlnd_ms .Multi Connect plugin. scale by client) 317 . An important difference is that MySQL Proxy works with all MySQL clients. An example of this is the PECL/mysqlnd_qc (Query Cache) extension. 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.. a mysqlnd plugin gets installed on the PHP application server.User Handler plugin. • PECL/mysqlnd_uh . monitoring. Both are valid tools for solving a variety of common tasks such as load balancing. • PECL/mysqlnd_pscache .A comparison of mysqlnd plugins with MySQL Proxy • Failover • Round-Robin. • Throttling • Sharding. • PECL/mysqlnd_sip . [1] Mysqlnd plugins and MySQL Proxy are different technologies using different approaches. using SELECT . An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. No single point of failure 2. whereas mysqlnd plugins are specific to PHP applications.. This extension inspects queries and executes only those that are allowed according to a ruleset.Query Cache plugin. 4.1. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. It sends the queries to distinct MySQL servers and merges the result at the client.

Mysqlnd plugins work on top of the C API. The following table shows PHP versions and the corresponding mysqlnd version contained within. Plugins can therefore parse. Table 4.5 5. and as such is available to the public either via Git.a background process. as it is sometimes called. This C API is basically a wrapper around the MySQL Client Server protocol.2.1 5.3. If a mysqlnd plugin is implemented using the C API. manipulate and even replace the communication protocol. ext/mysqlnd.0.3. MySQL Proxy runs as a daemon . Another daemon would need to be used for this purpose. MySQL Proxy can recall earlier decisions. or through source snapshot downloads. [1] The mysqlnd plugin API is simply part of the MySQL Native Driver PHP extension. they have greater flexibility than MySQL Proxy. or wire protocol. However. You can intercept all C API calls. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol.5 5. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well. It is developed as part of the PHP source repository.0.0 5. therefore you can hook all PHP calls. Actions are limited to those that can be achieved by manipulating the communication protocol.7. • MySQL Proxy requires knowledge of the Lua scripting language. as all state can be retained. this is usually not required. However.0. Obtaining the mysqlnd plugin API Copyright 1997-2012 the PHP Documentation Group. reverse engineer. As plugins allow you to create implementations that use two levels (C API and wire protocol). It is also possible to write plugins in PHP using PECL/mysqlnd_uh.2 5.7 318 .7 5.0. any subsequent changes to the wire protocol do not require changes to the plugin itself. However.Obtaining the mysqlnd plugin API MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications. such as Memcache.3.3 MySQL Native Driver version 5. Lua is the preferred scripting language of MySQL Proxy. This gives MySQL Proxy an advantage in this case. The bundled mysqlnd version per PHP release PHP Version 5. MySQL Proxy does have some disadvantages: • MySQL Proxy is a new component and technology to master and deploy. PHP makes use of the C API. 4.3. MySQL Proxy can also share one-time computed results among multiple application servers. Development started on the mysqlnd plugin API in December 2009. MySQL Proxy can be customized with C and Lua programming. a mysqlnd plugin is bound to the request-based lifecycle of PHP. which mirrors the libmysql client and Connector/C APIs. MySQL Proxy works on top of the wire protocol. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. without the need to program at the level of the wire protocol.8. For most PHP experts Lua is a new language to learn. Mysqlnd implements the wire protocol. A mysqlnd plugin can be written in C.

there are some conventions that need to be followed that will be discussed later.7 Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION.9.MySQL Native Driver Plugin Architecture PHP Version 5.c mysqlnd_result.c mysqlnd_net.0.$Revision: 300535”. mysqlnd_statistics. there are no fixed rules on inheritance in the C object oriented paradigm. However.10. MySQL Native Driver Plugin Architecture Copyright 1997-2012 the PHP Documentation Group. it is useful to know a little of how mysqlnd itself is organized.c mysqlnd.4 MySQL Native Driver version 5. Unlike with other languages such as C++ or Java. Members of the struct represent object properties.0. [1] This section provides an overview of the mysqlnd plugin architecture.c 319 . MYSQLND_VERSION_ID calculation table Version (part) Major*10000 Minor*100 Patch MYSQLND_VERSION_ID Example 5*10000 = 50000 0*100 = 0 7=7 50007 During development. The mysqlnd organization chart. which is an integer such as 50007. as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.c mysqlnd_ps.3. which is a string of the format “mysqlnd 5. In C you use a struct to represent an object.091210 .c mysqlnd_wireprotocol. per module Modules Statistics Connection Resultset Resultset Metadata Statement Network Wire protocol C Object Oriented Paradigm At the code level.7. or through MYSQLND_VERSION_ID. mysqlnd uses a C pattern for implementing object orientation. 4. Developers can calculate the version number as follows: Table 4.c mysqlnd_result_meta.7-dev . Mysqlnd consists of the following modules: Table 4. Struct members pointing to functions represent methods. developers should refer to the mysqlnd version number for compatibility and version tests.3. MySQL Native Driver Overview Before developing mysqlnd plugins.

During the lifetime of the PHP engine it will receive a number of requests. The following code shows how the mysqlnd function table is replaced: /* a place to store original function table */ struct st_mysqlnd_conn_methods org_methods. such as for Connection::stmt_init(). On each request the PHP engine will call the request initialization function of each extension. This is achieved by obtaining the mysqlnd function table. In some cases. sizeof(struct st_mysqlnd_conn_methods). it is still possible to call the original function table entries . The extension can perform any variable setup and resource allocation required for request processing. The function table is a global shared resource. which calls the functions of the plugin as required. it is vital to call the parent method prior to any other activity in the derived method. 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. How a plugin works A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. backing it up.the parent methods. } Connection function table manipulations must be done during Module Initialization (MINIT). The function table may change at any time in the future. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required. void minit_register_hooks(TSRMLS_D) { /* active function table */ struct st_mysqlnd_conn_methods * current_methods = mysqlnd_conn_get_methods(). /* install new methods */ current_methods->query = MYSQLND_METHOD(my_conn_class. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension. Calling parent methods If the original function table entries are backed up. current_methods. the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.MySQL Native Driver Plugin Architecture 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. query). /* backup original function table */ memcpy(&org_methods. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. 320 . Each request constitutes another life cycle. with a TSRM build. In an multi-threaded environment. and replacing it by a custom function table.

The mysqlnd allocator has some useful features. if (!props || !(*props)) { *props = mnd_pecalloc(1. query. } The plugin developer is responsible for the management of plugin data memory. Use of the mysqlnd memory allocator is recommended for plugin data. query)(MYSQLND *conn. void minit_register_hooks(TSRMLS_D) { /* obtain unique plugin ID */ my_plugin_id = mysqlnd_plugin_register(). Users of mysqlnd objects cannot simply add properties to the objects. /* return with call to parent */ } Extending properties A mysqlnd object is represented by a C struct. } MY_CONN_PROPERTIES. The following table shows how to calculate the position of the pointer for a specific plugin: Table 4. These functions are named using the convention: mnd_*loc(). unsigned int query_len TSRMLS_DC) { php_printf("my_conn_class::query(query = %s)\n". conn->persistent).query(conn. (*props)->query_counter = 0.see Extending Connection: methods */ } static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) { MY_CONN_PROPERTIES** props. mysqlnd reserves space for one void * pointer per plugin. which is allowed. my_plugin_id).MySQL Native Driver Plugin Architecture MYSQLND_METHOD(my_conn_class. such as the ability to use a debug allocator in a non-debug build. query = "SELECT 'query rewritten' FROM DUAL". query). } return props. props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data( conn. return org_methods. Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. 321 . /* snip . /* plugin id */ unsigned int my_plugin_id. sizeof(MY_CONN_PROPERTIES). query_len). query_len = strlen(query). When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data. const char *query. Pointer calculations for mysqlnd 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. 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. It is not possible to add a member to a C struct at run time.11.

Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. Other classes use copies of a globally shared function table. This gives you two options: you can manipulate the default function table of an object at MINIT. (MYSQLND_RES_METADATA) Result::read_result_metadata() Can be modified? No Yes. in particular in threaded environments. The advantage of the shared function table approach is performance.MySQL Native Driver Plugin Architecture Table 4. When and how to subclass When to subclass? Each instance has its own private function table? No Yes How to subclass? Connection (MYSQLND) MINIT Resultset (MYSQLND_RES) MINIT or later mysqlnd_conn_get_methods() mysqlnd_result_get_methods() or object method function table manipulation Resultset Meta MINIT (MYSQLND_RES_METADATA) Statement (MYSQLND_STMT) Network (MYSQLND_NET) MINIT MINIT or later No No Yes mysqlnd_result_metadata_get_method mysqlnd_stmt_get_methods() mysqlnd_net_get_methods() or object method function table manipulation mysqlnd_protocol_get_methods() or object method function table manipulation Wire protocol MINIT or later (MYSQLND_PROTOCOL) Yes You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table. Each object uses its own function table. Constructor status Allocation. and you can additionally refine methods of an object without impacting other instances of the same class. construction. Table 4. To avoid chaos. but call parent! Caller mysqlnd_connect() • Connection::list_fields() • Statement::get_result() • Statement::prepare() (Metadata only) • Statement::resultMetaData() 322 . There is no need to copy a function table for each and every object.13. reset Connection (MYSQLND) mysqlnd_init() Resultset(MYSQLND_RES) Allocation: • Connection::result_init() Reset and re-initialized during: • Result::use_result() • Result::store_result Resultset Meta Connection::result_meta_init() but call parent! Yes. The class function table copy is created together with the object. such function tables must only be manipulated during MINIT.12.

Destruction status Derived method must call parent? Destructor Connection Resultset Resultset Meta Statement Network Wire protocol yes. However. Network. such as Resultset. Regardless of all warnings.The mysqlnd plugin API Statement (MYSQLND_STMT) Network (MYSQLND_NET) Connection::stmt_init() mysqlnd_net_init() Yes. after method execution yes. it can be useful to subclass constructors.14. The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. [1] The following is a list of functions provided in the mysqlnd plugin API: • mysqlnd_plugin_register() 323 . after method execution yes.4. The mysqlnd plugin API Copyright 1997-2012 the PHP Documentation Group.3. 4. end_psession() free_result() free() dtor(). As with constructors you may replace the methods entirely but this is not recommended. but call parent! No No Connection::stmt_init() Connection::init() Connection::init() Wire protocol mysqlnd_protocol_init() (MYSQLND_PROTOCOL) It is strongly recommended that you do not entirely replace a constructor.3. The recommended method for plugins is to simply hook the methods.4.3. plugins do not associate plugin data with a persistent connection.0 to 5. 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. 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. Table 4.3. mysqlnd_plugin_get_plugin_<object>_data(). after method execution yes. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables. Caution Due to a bug in PHP versions 5. after method execution yes. after method execution yes. If you do not care about warnings and insist on hooking the constructors. The constructors perform memory allocations. The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. Wire Protocol.7. after method execution free_contents(). they are the best possible place for you to hook in and free your plugin data. This has been fixed in PHP 5. free_stmt_content() free() free() The destructors are the appropriate place to free properties. you should at least call the parent constructor before doing anything in your constructor. free your memory and call the parent implementation immediately following this.

query() 2. It is recommended that you write cooperative plugins. Components often found in plugins mechanisms are: • A plugin manager • A plugin API • Application services (or modules) • Application service APIs (or module APIs) The mysqlnd plugin concept employs these features. and can point into another plugin's data. The plugins should always cooperate with mysqlnd itself.query() 1. As discussed previously. Table 4. Simple offset arithmetic can be used to read another plugin's data. and that you always call the parent method.query() pointer mysqlnd.15.query ext/mysqlnd_monitor mysqlnd_monitor. mysqlnd_cache. Everything can be overwritten to implement friendly or hostile algorithms. and additionally enjoys an open architecture.query() call stack if calling parent mysqlnd. No Restrictions A plugin has full access to the inner workings of mysqlnd. mysqlnd_monitor. plugins can use pointers freely. These pointers are not restricted in any way.query 1. There are no security limits or restrictions.query() mysqlnd_cache.The mysqlnd plugin API • 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. It is recommended you only deploy plugins from a trusted source. mysqlnd. Issues: an example of chaining and cooperation Extension ext/mysqlnd ext/mysqlnd_cache mysqlnd.query() 324 .

0. • Mysqlnd calls its connect method. conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn. which exposes the mysqlnd C plugin API to PHP: • Any PHP MySQL application tries to establish a connection to 192.0. ini entries.query In this scenario.0. The following code shows the basic structure of the MINIT function that will be used in the typical mysqlnd plugin: /* my_php_mysqlnd_plugin. which has been subclassed by ext/mysqlnd_plugin. sizeof(struct st_mysqlnd_conn_methods)).0. conn_m. The circle is closed.c */ static PHP_MINIT_FUNCTION(mysqlnd_plugin) { /* globals.0. mysqlnd_cache. mysqlnd.1.5. } 325 .168. PHP calls extensions in alphabetical order by default.29.168.29 • The PHP application will either use ext/mysql. • The userspace hook changes the connection host IP from 192. conn_m = mysqlnd_get_conn_methods().Getting started building a mysqlnd plugin 2. query). PHP Extension Recap This is a recap of what happens when using an example plugin. a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded. 4. classes */ /* register mysqlnd plugin */ mysqlnd_plugin_id = mysqlnd_plugin_register(). • ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user. • ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. connect). All three PHP MySQL extensions use mysqlnd to establish the connection to 192.29 to 127. [1] It is important to remember that a mysqlnd plugin is itself a PHP extension. ext/ mysqlnd_plugin returns as well. Plugin registration happens at MINIT using the logic shown previously. ext/mysqlnd_plugin.2. Plugins are not aware of each other and do not set extension dependencies. By default the plugins call the parent implementation of the query method in their derived version of the method.2. resources. memcpy(org_conn_m.1 and returns the connection established by parent::connect(). • Whatever PHP MySQL extension had been used by the application.0. Getting started building a mysqlnd plugin Copyright 1997-2012 the PHP Documentation Group. conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn. it receives a connection to 127. ext/mysqli or PDO_MYSQL.query() 3. Both subclass Connection::query().7.1) by calling the original mysqlnd method for establishing a connection. • ext/mysqlnd_plugin performs the equivalent of parent::connect(127. The PHP MySQL extension itself returns to the PHP application.168.2.

Optimization: calling methods from C using zend_call_method The following code snippet shows the prototype for the zend_call_method function. } } mysqlnd_plugin_set_conn_proxy(new proxy()). PHP: user registers plugin callback 2. C: ext/mysqlnd_plugin a.. */) { /* . connect)(/* . Write a class "mysqlnd_plugin_connection" in C 2..h... ZEND_API zval* zend_call_method( zval **object_pp.. zval* arg2 TSRMLS_DC ).) { . zval* arg1. taken from zend_interfaces. PHP: user calls any PHP MySQL API to connect to MySQL 3. C: mysqlnd ends up in ext/mysqlnd_plugin 5. zval **retval_ptr_ptr. Zend API supports only two arguments.Getting started building a mysqlnd plugin /* my_mysqlnd_plugin. for example: enum_func_status (*func_mysqlnd_conn__connect)( MYSQLND *conn. C: ext/*mysql* calls mysqlnd method 4..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().zend_interfaces.. */ } enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn. */) { /* .. if userspace callback not set You need to carry out the following: 1.c */ enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn. Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()" 3. char *function_name. . const char *host. Or orginal mysqlnd method. Calls userspace callback b. zend_function **fn_proxy. int function_name_len.. 326 . */ } Task analysis: from C to userspace class proxy extends mysqlnd_plugin_connection { public function connect($host. zend_class_entry *obj_ce... int param_count. You may need more. query)(/* . Process: 1. Call userspace proxy methods from C (optimization .

.. MAKE_STD_ZVAL(zv_host). MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy. unsigned int mysql_flags TSRMLS_DC To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters. Calling PHP userspace This code snippet shows the optimized method for calling a userspace function from C: /* my_mysqlnd_plugin.. /* . passwd_len.Getting started building a mysqlnd plugin const char * unsigned int unsigned int const char * ). */ if (global_user_conn_proxy) { /* ... const char *host. user. zval_ptr_dtor(&zv_host).c */ MYSQLND_METHOD(my_conn_class.. ZEND_REGISTER_RESOURCE(zv_conn. /* . (void *)conn. connect)( MYSQLND *conn. if (global_user_conn_proxy) { /* call userspace proxy */ ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy. */ 327 . socket. . /* .*/) { /* ....connect)( MYSQLND *conn. zv_conn. passwd_len. ZVAL_STRING(zv_host. . zv_retval. MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy.*/).. db_len. user..connect)( /* . unsigned int port.. const char * db.*/)..... You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros.. /* . 1). zval_ptr_dtor(&zv_conn). */ TSRMLS_DC) { enum_func_status ret = FAIL.. passwd. zv_retval. le_mysqlnd_plugin_conn). } return ret... */ if (global_user_conn_proxy) { /* . socket.. db. */ zval* zv_host.. */ } /* . } Calling userspace: simple arguments /* my_mysqlnd_plugin. host..connect(conn. const char *host /* . host. */. */ } Calling userspace: structs as arguments /* my_mysqlnd_plugin...*/) { /* ... host... /*.c */ MYSQLND_METHOD(my_conn_class. be transparent */ ret = org_methods. port. */ zval* zv_conn. zv_host /*. */ } /* .c */ MYSQLND_METHOD(my_conn_class. zval * global_user_conn_proxy = fetch_userspace_proxy(). } else { /* or original mysqlnd method = do nothing. zv_host /*.*/).. const char * passwd. db_len. mysql_flags TSRMLS_CC).

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

... and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime.4. When writing transactional database code using a table type that does not support transactions. 331 Copyright 1997-2012 the PHP Documentation Group.Chapter 5.. Added SSL support with mysqlnd and OpenSSL....x and 5...0 5... including PDO_MYSQL. Warning Beware: Some MySQL table types (storage engines) do not support transactions.. In addition.. PDO will emulate them for you. 4...x databases.1 and below are no longer supported.. any DDL queries issued will implicitly commit any pending transactions.. Changelog Version 5. If you're using an older version of the mysql client libraries.. PDO_MYSQL DSN . PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.... See also the MySQL documentation about connecting to MySQL with SSL......... where the optional [=DIR] is the MySQL base install directory..../configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql. If unspecified. Added SSL support with libmysql and OpenSSL..3........ the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions.sock SSL support is enabled using the appropriate PDO_MySQL constants [329]... these driver-specific constants should only be used if you are using this driver... the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.x.1..1 and higher... $ . Optionally... which is equivalent to calling the MySQL C API function mysql_ssl_set()...... Use --with-pdo-mysql[=DIR] to install the PDO MySQL extension......... Optionally. MySQL Functions (PDO_MYSQL) (MySQL (PDO)) Table of Contents 5.. Table 5.. SSL cannot be enabled with PDO::setAttribute because the connection already exists... MySQL will pretend that a transaction was initiated successfully......... The constants below are defined by this driver. [1] PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3...... the default locations are searched............. Using driver-specific attributes with 329 ... If mysqlnd is passed as [=DIR]..........9 5.. then the MySQL native driver will be used.. Also.3..7 Description MySQL client libraries 4...1....... In addition...

Note. I should use \$stmt->fetchAll() } ?> PDO::MYSQL_ATTR_LOCAL_INFILE Enable LOAD LOCAL INFILE. If you're writing portable code. PDO::MYSQL_ATTR_READ_DEFAULT_FILE Read options from the named option file instead of from my. PDO::MYSQL_ATTR_IGNORE_SPACE Permit spaces after function names. Will (integer) automatically be re-executed when reconnecting. don't use prepared statements. 330 . this constant can only be used in the driver_options array when constructing a new database handle. PDO::MYSQL_ATTR_INIT_COMMAND Command to execute when connecting to the MySQL server.7. PDO::MYSQL_ATTR_COMPRESS (integer) PDO::MYSQL_ATTR_SSL_CA (integer) Enable network communication compression. } else { die("my application only works with mysql. PDO::MYSQL_ATTR_READ_DEFAULT_GROUP from the named group from my. This constant is not supported Maximum (integer) when compiled against mysqlnd. you should use PDOStatement::fetchAll instead. This (integer) option is not available if mysqlnd is used. Defaults to 1 MiB. This option is not available if mysqlnd is used. PDO::MYSQL_ATTR_MAX_BUFFER_SIZE buffer size. Example 5. this constant can only be used in the driver_options array when constructing a new database handle.3. because mysqlnd does not read the mysql configuration files. This exists as of PHP 5. Forcing queries to be buffered in mysql <?php if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') { $stmt = $db->prepare('select * from foo'. The file path to the SSL certificate authority.another driver may result in unexpected behaviour. the MySQL driver (integer) will use the buffered versions of the MySQL API.cnf. because mysqlnd does not read the mysql configuration files. array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true)). PDO::getAttribute may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver. This is not supported when compiled against mysqlnd. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY If this attribute is set to TRUE on a PDOStatement. PDO::MYSQL_ATTR_DIRECT_QUERY Perform direct queries. (integer) PDO::MYSQL_ATTR_FOUND_ROWSReturn the number of found (matched) rows. not the number of changed (integer) rows. Makes all functions names (integer) reserved words.cnf or the file specified Read options (integer) with MYSQL_READ_DEFAULT_FILE . if your code can run against multiple drivers.1. (integer) Note.

php. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.sock" NULL Changeable PHP_INI_SYSTEM PHP_INI_SYSTEM For further details and definitions of the PHP_INI_* modes.3.7. This ini setting is Unix only.3.7. The hostname on which the database server resides.1.changes. in a format understood by OpenSSL. 331 . which are stored in PEM format.debug boolean Sets a Unix domain socket.default_socket string pdo_mysql.7. Enables debugging for PDO_MYSQL.net/manual/en/ configuration.7. The port number where the database server is listening. The behaviour of these functions is affected by settings in php. PDO::MYSQL_ATTR_SSL_CERT (integer) PDO::MYSQL_ATTR_CIPHER (integer) The file path to the SSL certificate.PDO_MYSQL DSN PDO::MYSQL_ATTR_SSL_CAPATHThe file path to the directory that contains the trusted SSL CA (integer) certificates. PDO_MYSQL Configuration Options Name pdo_mysql. PDO::MYSQL_ATTR_KEY (integer) The file path to the SSL key.debug Default "/tmp/mysql.default_socket pdo_mysql. [1] • PDO_MYSQL DSN Connecting to MySQL databases Description The PDO_MYSQL Data Source Name (DSN) is composed of the following elements: DSN prefix host port The DSN prefix is mysql:.modes. This exists as of PHP 5. A list of one or more permissible ciphers to use for SSL encryption. This value can either be set at compile time if a domain socket is found at configure.ini.3. pdo_mysql.3. Table 5. PDO_MYSQL DSN Copyright 1997-2012 the PHP Documentation Group. see the http://www. This exists as of PHP 5. Here's a short explanation of the configuration directives. 5. For example: DHE-RSA-AES256SHA:AES128-SHA This exists as of PHP 5.2. This exists as of PHP 5.

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

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

334 .

along with the mysqlnd core library and all of its plugins. which includes the three APIs that are described above. 335 . This term refers to the full set of MySQL related functionality in PHP. and other publications.Chapter 6. Connector/PHP This documentation. sometimes uses the term Connector/PHP.

336 .

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

338 .

you should try the following procedure. It might look like this (all on one line): EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lresolv -lm -ldl -lnsl -lxml2 -lz -lm -lxml2 -lz -lm -lmysqlclient -lz -lcrypt -lnsl -lm -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt Remove all duplicates. so that the line looks like this (all on one line): EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lresolv -lm -ldl -lnsl -lxml2 3./configure --with-mysqli=/usr/bin/mysql_config --with-mysql=/usr 2. 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.Chapter 8. Edit the Makefile and search for a line that starts with EXTRA_LIBS. 1. Configure PHP like this: . Build and install PHP: make make install 339 .

340 .