Spec-Zone .ru
спецификации, руководства, описания, API

22.9.3.9. The mysqli class (mysqli)

Copyright 1997-2012 the PHP Documentation Group.

Represents a connection between PHP and a MySQL database.

 mysqli {
mysqliProperties 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= =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(int flags,
string name);

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 static int mysqli::poll(array read,
array error,
array reject,
int sec,
int usec);

mysqli_stmt mysqli::prepare(string query);
mixed mysqli::query(string query,
int resultmode= =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 flags,
string name);

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();
}

22.9.3.9.1. mysqli::$affected_rows,mysqli_affected_rows

Copyright 1997-2012 the PHP Documentation Group.

  • 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 were 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 the maximum integer value( PHP_INT_MAX ), the number of affected rows will be returned as a string.

Examples

Example 22.106. $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 */$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 rows (INSERT): 984Affected rows (UPDATE): 168Affected rows (DELETE): 815Affected rows (SELECT): 169

See Also

mysqli_num_rows
mysqli_info

22.9.3.9.2. mysqli::autocommit,mysqli_autocommit

Copyright 1997-2012 the PHP Documentation Group.

  • 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

mode

Whether to turn on auto-commit or not.

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 22.107. mysqli::autocommitexample

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

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_begin_transaction
mysqli_commit
mysqli_rollback

22.9.3.9.3. mysqli::begin_transaction,mysqli_begin_transaction

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::begin_transaction

    mysqli_begin_transaction

    Starts a transaction

Description

Object oriented style (method):

public bool mysqli::begin_transaction(int flags,
string name);

Procedural style:

bool mysqli_begin_transaction(mysqli link,
int flags,
string name);

Warning

This function iscurrently not documented; only its argument list is available.

Parameters

link

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

flags

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_autocommit
mysqli_commit
mysqli_rollback

22.9.3.9.4. mysqli::change_user,mysqli_change_user

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::change_user

    mysqli_change_user

    Changes the user of the specified database connection

Description

Object oriented style

bool mysqli::change_user(string user,
string password,
string database);

Procedural style

bool mysqli_change_user(mysqli link,
string user,
string password,
string database);

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Parameters

link

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

user

The MySQL user name.

password

The MySQL password.

database

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 22.108. mysqli::change_userexample

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();    if ($row[0] === NULL) {        printf("Value of variable a is NULL\n");    }    $result->close();}/* close connection */$mysqli->close();?>   

Procedural style

<?php/* connect database test */$link = mysqli_connect("localhost", "my_user", "my_password", "test");/* check connection */if (!$link) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* Set Variable a */mysqli_query($link, "SET @a:=1");/* reset all and select a new database */mysqli_change_user($link, "my_user", "my_password", "world");if ($result = mysqli_query($link, "SELECT DATABASE()")) {    $row = mysqli_fetch_row($result);    printf("Default database: %s\n", $row[0]);    mysqli_free_result($result);}if ($result = mysqli_query($link, "SELECT @a")) {    $row = mysqli_fetch_row($result);    if ($row[0] === NULL) {        printf("Value of variable a is NULL\n");    }    mysqli_free_result($result);}/* close connection */mysqli_close($link);?>   

The above examples will output:

Default database: worldValue of variable a is NULL

See Also

mysqli_connect
mysqli_select_db

22.9.3.9.5. mysqli::character_set_name,mysqli_character_set_name

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::character_set_name

    mysqli_character_set_name

    Returns the default character set for the database connection

Description

Object oriented style

string mysqli::character_set_name();

Procedural style

string mysqli_character_set_name(mysqli link);

Returns the current character set for the database connection.

Parameters

link

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

Return Values

The default character set for the current connection

Examples

Example 22.109. mysqli::character_set_nameexample

Object oriented style

<?php/* Open a connection */$mysqli = new mysqli("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* Print current character set */$charset = $mysqli->character_set_name();printf ("Current character set is %s\n", $charset);$mysqli->close();?>   

Procedural style

<?php/* Open a connection */$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (!$link) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* Print current character set */$charset = mysqli_character_set_name($link);printf ("Current character set is %s\n",$charset);/* close connection */mysqli_close($link);?>   

The above examples will output:

Current character set is latin1_swedish_ci

See Also

mysqli_set_charset
mysqli_client_encoding
mysqli_real_escape_string

22.9.3.9.6. mysqli::$client_info,mysqli_get_client_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$client_info

    mysqli_get_client_info

    Get MySQL client info

Description

Object oriented style

string mysqli->client_info ;

Procedural style

string mysqli_get_client_info(mysqli link);

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example 22.110. mysqli_get_client_info

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

See Also

mysqli_get_client_version
mysqli_get_server_info
mysqli_get_server_version

22.9.3.9.7. mysqli::$client_version,mysqli_get_client_version

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$client_version

    mysqli_get_client_version

    Returns the MySQL client version as a string

Description

Object oriented style

int mysqli->client_version ;

Procedural style

int mysqli_get_client_version(mysqli link);

Returns client version number as an integer.

Return Values

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exists.

Examples

Example 22.111. 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

22.9.3.9.8. mysqli::close, mysqli_close

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::close

    mysqli_close

    Closes a previously opened database connection

Description

Object oriented style

bool mysqli::close();

Procedural style

bool mysqli_close(mysqli link);

Closes a previously opened database 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.

Examples

See mysqli_connect.

See Also

mysqli::__construct
mysqli_init
mysqli_real_connect

22.9.3.9.9. mysqli::commit, mysqli_commit

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::commit

    mysqli_commit

    Commits the current transaction

Description

Object oriented style

bool mysqli::commit(int flags,
string name);

Procedural style

bool mysqli_commit(mysqli link,
int flags,
string name);

Commits the current transaction for the database connection.

Parameters

link

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

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then COMMIT/*name*/ is executed.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.5.0 Added flags and nameparameters.

Examples

Example 22.112. mysqli::commitexample

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();}$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");/* set autocommit to off */$mysqli->autocommit(FALSE);/* Insert some values */$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");/* commit transaction */$mysqli->commit();/* drop table */$mysqli->query("DROP TABLE Language");/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "test");/* check connection */if (!$link) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* set autocommit to off */mysqli_autocommit($link, FALSE);mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");/* Insert some values */mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");/* commit transaction */mysqli_commit($link);/* close connection */mysqli_close($link);?>

See Also

mysqli_autocommit
mysqli_begin_transaction
mysqli_rollback
mysqli_savepoint

22.9.3.9.10. mysqli::$connect_errno,mysqli_connect_errno

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$connect_errno

    mysqli_connect_errno

    Returns the error code from last connect call

Description

Object oriented style

string mysqli->connect_errno ;

Procedural style

int mysqli_connect_errno();

Returns the last error code number from the last call to mysqli_connect.

Note

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Return Values

An error code value for the last call to mysqli_connect, if it failed. zero means no error occurred.

Examples

Example 22.113. $mysqli->connect_errno example

Object oriented style

<?php$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');if ($mysqli->connect_errno) {    die('Connect Error: ' . $mysqli->connect_errno);}?>   

Procedural style

<?php$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');if (!$link) {    die('Connect Error: ' . mysqli_connect_errno());}?>   

The above examples will output:

Connect Error: 1045

See Also

mysqli_connect
mysqli_connect_error
mysqli_errno
mysqli_error
mysqli_sqlstate

22.9.3.9.11. mysqli::$connect_error,mysqli_connect_error

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$connect_error

    mysqli_connect_error

    Returns a string description of the last connect error

Description

Object oriented style

string mysqli->connect_error ;

Procedural style

string mysqli_connect_error();

Returns the last error message string from the last call to mysqli_connect.

Return Values

A string that describes the error. NULL is returned if no error occurred.

Examples

Example 22.114. $mysqli->connect_error example

Object oriented style

<?php$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');// Works as of PHP 5.2.9 and 5.3.0.if ($mysqli->connect_error) {    die('Connect Error: ' . $mysqli->connect_error);}?>   

Procedural style

<?php$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');if (!$link) {    die('Connect Error: ' . mysqli_connect_error());}?>   

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.2.9 and 5.3.0. Use the mysqli_connect_error function if compatibility with earlier PHP versions is required.

See Also

mysqli_connect
mysqli_connect_errno
mysqli_errno
mysqli_error
mysqli_sqlstate

22.9.3.9.12. mysqli::__construct,mysqli_connect

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::__construct

    mysqli_connect

    Open a new connection to the MySQL server

Description

Object oriented style

mysqli::__construct(string host= =ini_get("mysqli.default_host"),
string username= =ini_get("mysqli.default_user"),
string passwd= =ini_get("mysqli.default_pw"),
string dbname= ="",
int port= =ini_get("mysqli.default_port"),
string socket= =ini_get("mysqli.default_socket"));

Procedural style

mysqli mysqli_connect(string host= =ini_get("mysqli.default_host"),
string username= =ini_get("mysqli.default_user"),
string passwd= =ini_get("mysqli.default_pw"),
string dbname= ="",
int port= =ini_get("mysqli.default_port"),
string socket= =ini_get("mysqli.default_socket"));

Opens a connection to the MySQL Server running on.

Parameters

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Prepending host by p: opens a persistent connection. mysqli_change_user is automatically called on connections opened from the connection pool.

username

The MySQL user name.

passwd

If not provided or NULL , the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

Return Values

Returns an object which represents the connection to a MySQL Server.

Changelog

Version Description
5.3.0 Added the ability of persistent connections.

Examples

Example 22.115. mysqli::__constructexample

Object oriented style

<?php$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');/* * This is the "official" OO way to do it, * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */if ($mysqli->connect_error) {    die('Connect Error (' . $mysqli->connect_errno . ') '            . $mysqli->connect_error);}/* * Use this instead of $connect_error if you need to ensure * compatibility with PHP versions prior to 5.2.9 and 5.3.0. */if (mysqli_connect_error()) {    die('Connect Error (' . mysqli_connect_errno() . ') '            . mysqli_connect_error());}echo 'Success... ' . $mysqli->host_info . "\n";$mysqli->close();?>   

Object oriented style when extending mysqli class

<?phpclass foo_mysqli extends mysqli {    public function __construct($host, $user, $pass, $db) {        parent::__construct($host, $user, $pass, $db);        if (mysqli_connect_error()) {            die('Connect Error (' . mysqli_connect_errno() . ') '                    . mysqli_connect_error());        }    }}$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');echo 'Success... ' . $db->host_info . "\n";$db->close();?>   

Procedural style

<?php$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');if (!$link) {    die('Connect Error (' . mysqli_connect_errno() . ') '            . mysqli_connect_error());}echo 'Success... ' . mysqli_get_host_info($link) . "\n";mysqli_close($link);?>   

The above examples will output:

Success... MySQL host info: localhost via TCP/IP

Notes

Note

MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

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

Note

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error function or the mysqli->connect_error property as in the preceding examples.

Note

If it is necessary to set options, such as the connection timeout, mysqli_real_connect must be used instead.

Note

Calling the constructor with no parameters is the same as calling mysqli_init.

Note

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

mysqli_real_connect
mysqli_options
mysqli_connect_errno
mysqli_connect_error
mysqli_close

22.9.3.9.13. mysqli::debug, mysqli_debug

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::debug

    mysqli_debug

    Performs debugging operations

Description

Object oriented style

bool mysqli::debug(string message);

Procedural style

bool mysqli_debug(string message);

Performs debugging operations using the Fred Fish debugging library.

Parameters

message

A string representing the debugging operation to perform

Return Values

Returns TRUE .

Notes

Note

To use the mysqli_debug function you must compile the MySQL client library to support debugging.

Examples

Example 22.116. Generating a Trace File

<?php/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */mysqli_debug("d:t:o,/tmp/client.trace");?>

See Also

mysqli_dump_debug_info
mysqli_report

22.9.3.9.14. mysqli::dump_debug_info,mysqli_dump_debug_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::dump_debug_info

    mysqli_dump_debug_info

    Dump debugging information into the log

Description

Object oriented style

bool mysqli::dump_debug_info();

Procedural style

bool mysqli_dump_debug_info(mysqli link);

This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.

Parameters

link

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

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_debug

22.9.3.9.15. mysqli::$errno, mysqli_errno

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$errno

    mysqli_errno

    Returns the error code for the most recent function call

Description

Object oriented style

int mysqli->errno ;

Procedural style

int mysqli_errno(mysqli link);

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

link

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

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example 22.117. $mysqli->errno 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();}if (!$mysqli->query("SET a=1")) {    printf("Errorcode: %d\n", $mysqli->errno);}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}if (!mysqli_query($link, "SET a=1")) {    printf("Errorcode: %d\n", mysqli_errno($link));}/* close connection */mysqli_close($link);?>   

The above examples will output:

Errorcode: 1193

See Also

mysqli_connect_errno
mysqli_connect_error
mysqli_error
mysqli_sqlstate

22.9.3.9.16. mysqli::$error_list,mysqli_error_list

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$error_list

    mysqli_error_list

    Returns a list of errors from the last command executed

Description

Object oriented style

array mysqli->error_list ;

Procedural style

array mysqli_error_list(mysqli link);

Returns a array of errors for the most recent MySQLi function call that can succeed or fail.

Parameters

link

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

Return Values

A list of errors, each as an associative array containing the errno, error, and sqlstate.

Examples

Example 22.118. $mysqli->error_list example

Object oriented style

<?php$mysqli = new mysqli("localhost", "nobody", "");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}if (!$mysqli->query("SET a=1")) {    print_r($mysqli->error_list);}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}if (!mysqli_query($link, "SET a=1")) {    print_r(mysqli_error_list($link));}/* close connection */mysqli_close($link);?>   

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

22.9.3.9.17. mysqli::$error, mysqli_error

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$error

    mysqli_error

    Returns a string description of the last error

Description

Object oriented style

string mysqli->error ;

Procedural style

string mysqli_error(mysqli link);

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

link

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

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example 22.119. $mysqli->error 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();}if (!$mysqli->query("SET a=1")) {    printf("Errormessage: %s\n", $mysqli->error);}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}if (!mysqli_query($link, "SET a=1")) {    printf("Errormessage: %s\n", mysqli_error($link));}/* close connection */mysqli_close($link);?>   

The above examples will output:

Errormessage: Unknown system variable 'a'

See Also

mysqli_connect_errno
mysqli_connect_error
mysqli_errno
mysqli_sqlstate

22.9.3.9.18. mysqli::$field_count,mysqli_field_count

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$field_count

    mysqli_field_count

    Returns the number of columns for the most recent query

Description

Object oriented style

int mysqli->field_count ;

Procedural style

int mysqli_field_count(mysqli link);

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Parameters

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.

Examples

Example 22.120. $mysqli->field_count example

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password", "test");$mysqli->query( "DROP TABLE IF EXISTS friends");$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");$mysqli->real_query("SELECT * FROM friends");if ($mysqli->field_count) {    /* this was a select/show or describe query */    $result = $mysqli->store_result();    /* process resultset */    $row = $result->fetch_row();    /* free resultset */    $result->close();}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "test");mysqli_query($link, "DROP TABLE IF EXISTS friends");mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");mysqli_real_query($link, "SELECT * FROM friends");if (mysqli_field_count($link)) {    /* this was a select/show or describe query */    $result = mysqli_store_result($link);    /* process resultset */    $row = mysqli_fetch_row($result);    /* free resultset */    mysqli_free_result($result);}/* close connection */mysqli_close($link);?>

22.9.3.9.19. mysqli::get_charset,mysqli_get_charset

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::get_charset

    mysqli_get_charset

    Returns a character set object

Description

Object oriented style

object mysqli::get_charset();

Procedural style

object mysqli_get_charset(mysqli link);

Returns a character set object providing several properties of the current active character set.

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

Character set name

collation

Collation name

dir

Directory the charset description was fetched from (?) or "" for built-in character sets

min_length

Minimum character length in bytes

max_length

Maximum character length in bytes

number

Internal character set number

state

Character set status (?)

Examples

Example 22.121. mysqli::get_charsetexample

Object oriented style

<?php  $db = mysqli_init();  $db->real_connect("localhost","root","","test");  var_dump($db->get_charset());?>   

Procedural style

<?php  $db = mysqli_init();  mysqli_real_connect($db, "localhost","root","","test");  var_dump($db->get_charset());?>   

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

22.9.3.9.20. mysqli::get_client_info,mysqli_get_client_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::get_client_info

    mysqli_get_client_info

    Get MySQL client info

Description

Object oriented style

string mysqli::get_client_info();

Procedural style

string mysqli_get_client_info(mysqli link);

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example 22.122. mysqli_get_client_info

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

See Also

mysqli_get_client_version
mysqli_get_server_info
mysqli_get_server_version

22.9.3.9.21. mysqli_get_client_stats

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli_get_client_stats

    Returns client per-process statistics

Description

array mysqli_get_client_stats();

Returns client per-process statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client stats if success, FALSE otherwise.

Examples

Example 22.123. A mysqli_get_client_statsexample

<?php$link = mysqli_connect();print_r(mysqli_get_client_stats());?>    

The above example will output something similar to:

Array(    [bytes_sent] => 43    [bytes_received] => 80    [packets_sent] => 1    [packets_received] => 2    [protocol_overhead_in] => 8    [protocol_overhead_out] => 4    [bytes_received_ok_packet] => 11    [bytes_received_eof_packet] => 0    [bytes_received_rset_header_packet] => 0    [bytes_received_rset_field_meta_packet] => 0    [bytes_received_rset_row_packet] => 0    [bytes_received_prepare_response_packet] => 0    [bytes_received_change_user_packet] => 0    [packets_sent_command] => 0    [packets_received_ok] => 1    [packets_received_eof] => 0    [packets_received_rset_header] => 0    [packets_received_rset_field_meta] => 0    [packets_received_rset_row] => 0    [packets_received_prepare_response] => 0    [packets_received_change_user] => 0    [result_set_queries] => 0    [non_result_set_queries] => 0    [no_index_used] => 0    [bad_index_used] => 0    [slow_queries] => 0    [buffered_sets] => 0    [unbuffered_sets] => 0    [ps_buffered_sets] => 0    [ps_unbuffered_sets] => 0    [flushed_normal_sets] => 0    [flushed_ps_sets] => 0    [ps_prepared_never_executed] => 0    [ps_prepared_once_executed] => 0    [rows_fetched_from_server_normal] => 0    [rows_fetched_from_server_ps] => 0    [rows_buffered_from_client_normal] => 0    [rows_buffered_from_client_ps] => 0    [rows_fetched_from_client_normal_buffered] => 0    [rows_fetched_from_client_normal_unbuffered] => 0    [rows_fetched_from_client_ps_buffered] => 0    [rows_fetched_from_client_ps_unbuffered] => 0    [rows_fetched_from_client_ps_cursor] => 0    [rows_skipped_normal] => 0    [rows_skipped_ps] => 0    [copy_on_write_saved] => 0    [copy_on_write_performed] => 0    [command_buffer_too_small] => 0    [connect_success] => 1    [connect_failure] => 0    [connection_reused] => 0    [reconnect] => 0    [pconnect_success] => 0    [active_connections] => 1    [active_persistent_connections] => 0    [explicit_close] => 0    [implicit_close] => 0    [disconnect_close] => 0    [in_middle_of_command_close] => 0    [explicit_free_result] => 0    [implicit_free_result] => 0    [explicit_stmt_close] => 0    [implicit_stmt_close] => 0    [mem_emalloc_count] => 0    [mem_emalloc_ammount] => 0    [mem_ecalloc_count] => 0    [mem_ecalloc_ammount] => 0    [mem_erealloc_count] => 0    [mem_erealloc_ammount] => 0    [mem_efree_count] => 0    [mem_malloc_count] => 0    [mem_malloc_ammount] => 0    [mem_calloc_count] => 0    [mem_calloc_ammount] => 0    [mem_realloc_count] => 0    [mem_realloc_ammount] => 0    [mem_free_count] => 0    [proto_text_fetched_null] => 0    [proto_text_fetched_bit] => 0    [proto_text_fetched_tinyint] => 0    [proto_text_fetched_short] => 0    [proto_text_fetched_int24] => 0    [proto_text_fetched_int] => 0    [proto_text_fetched_bigint] => 0    [proto_text_fetched_decimal] => 0    [proto_text_fetched_float] => 0    [proto_text_fetched_double] => 0    [proto_text_fetched_date] => 0    [proto_text_fetched_year] => 0    [proto_text_fetched_time] => 0    [proto_text_fetched_datetime] => 0    [proto_text_fetched_timestamp] => 0    [proto_text_fetched_string] => 0    [proto_text_fetched_blob] => 0    [proto_text_fetched_enum] => 0    [proto_text_fetched_set] => 0    [proto_text_fetched_geometry] => 0    [proto_text_fetched_other] => 0    [proto_binary_fetched_null] => 0    [proto_binary_fetched_bit] => 0    [proto_binary_fetched_tinyint] => 0    [proto_binary_fetched_short] => 0    [proto_binary_fetched_int24] => 0    [proto_binary_fetched_int] => 0    [proto_binary_fetched_bigint] => 0    [proto_binary_fetched_decimal] => 0    [proto_binary_fetched_float] => 0    [proto_binary_fetched_double] => 0    [proto_binary_fetched_date] => 0    [proto_binary_fetched_year] => 0    [proto_binary_fetched_time] => 0    [proto_binary_fetched_datetime] => 0    [proto_binary_fetched_timestamp] => 0    [proto_binary_fetched_string] => 0    [proto_binary_fetched_blob] => 0    [proto_binary_fetched_enum] => 0    [proto_binary_fetched_set] => 0    [proto_binary_fetched_geometry] => 0    [proto_binary_fetched_other] => 0)

See Also

Stats description

22.9.3.9.22. mysqli_get_client_version,mysqli::$client_version

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli_get_client_version

    mysqli::$client_version

    Returns the MySQL client version as a string

Description

Object oriented style

int mysqli->client_version ;

Procedural style

int mysqli_get_client_version(mysqli link);

Returns client version number as an integer.

Return Values

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exits.

Examples

Example 22.124. 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

22.9.3.9.23. mysqli::get_connection_stats,mysqli_get_connection_stats

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::get_connection_stats

    mysqli_get_connection_stats

    Returns statistics about the client connection

Description

Object oriented style

bool mysqli::get_connection_stats();

Procedural style

array mysqli_get_connection_stats(mysqli link);

Returns statistics about the client connection. Available only with mysqlnd.

Parameters

link

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

Return Values

Returns an array with connection stats if success, FALSE otherwise.

Examples

Example 22.125. A mysqli_get_connection_statsexample

<?php$link = mysqli_connect();print_r(mysqli_get_connection_stats($link));?>    

The above example will output something similar to:

Array(    [bytes_sent] => 43    [bytes_received] => 80    [packets_sent] => 1    [packets_received] => 2    [protocol_overhead_in] => 8    [protocol_overhead_out] => 4    [bytes_received_ok_packet] => 11    [bytes_received_eof_packet] => 0    [bytes_received_rset_header_packet] => 0    [bytes_received_rset_field_meta_packet] => 0    [bytes_received_rset_row_packet] => 0    [bytes_received_prepare_response_packet] => 0    [bytes_received_change_user_packet] => 0    [packets_sent_command] => 0    [packets_received_ok] => 1    [packets_received_eof] => 0    [packets_received_rset_header] => 0    [packets_received_rset_field_meta] => 0    [packets_received_rset_row] => 0    [packets_received_prepare_response] => 0    [packets_received_change_user] => 0    [result_set_queries] => 0    [non_result_set_queries] => 0    [no_index_used] => 0    [bad_index_used] => 0    [slow_queries] => 0    [buffered_sets] => 0    [unbuffered_sets] => 0    [ps_buffered_sets] => 0    [ps_unbuffered_sets] => 0    [flushed_normal_sets] => 0    [flushed_ps_sets] => 0    [ps_prepared_never_executed] => 0    [ps_prepared_once_executed] => 0    [rows_fetched_from_server_normal] => 0    [rows_fetched_from_server_ps] => 0    [rows_buffered_from_client_normal] => 0    [rows_buffered_from_client_ps] => 0    [rows_fetched_from_client_normal_buffered] => 0    [rows_fetched_from_client_normal_unbuffered] => 0    [rows_fetched_from_client_ps_buffered] => 0    [rows_fetched_from_client_ps_unbuffered] => 0    [rows_fetched_from_client_ps_cursor] => 0    [rows_skipped_normal] => 0    [rows_skipped_ps] => 0    [copy_on_write_saved] => 0    [copy_on_write_performed] => 0    [command_buffer_too_small] => 0    [connect_success] => 1    [connect_failure] => 0    [connection_reused] => 0    [reconnect] => 0    [pconnect_success] => 0    [active_connections] => 1    [active_persistent_connections] => 0    [explicit_close] => 0    [implicit_close] => 0    [disconnect_close] => 0    [in_middle_of_command_close] => 0    [explicit_free_result] => 0    [implicit_free_result] => 0    [explicit_stmt_close] => 0    [implicit_stmt_close] => 0    [mem_emalloc_count] => 0    [mem_emalloc_ammount] => 0    [mem_ecalloc_count] => 0    [mem_ecalloc_ammount] => 0    [mem_erealloc_count] => 0    [mem_erealloc_ammount] => 0    [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

22.9.3.9.24. mysqli::$host_info,mysqli_get_host_info

Copyright 1997-2012 the PHP Documentation Group.

  • 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);

Returns a string describing the connection represented by the link parameter (including the server host name).

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.

Examples

Example 22.126. $mysqli->host_info 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();}/* print host information */printf("Host info: %s\n", $mysqli->host_info);/* 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();}/* print host information */printf("Host info: %s\n", mysqli_get_host_info($link));/* close connection */mysqli_close($link);?>   

The above examples will output:

Host info: Localhost via UNIX socket

See Also

mysqli_get_proto_info

22.9.3.9.25. mysqli::$protocol_version,mysqli_get_proto_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$protocol_version

    mysqli_get_proto_info

    Returns the version of the MySQL protocol used

Description

Object oriented style

string mysqli->protocol_version ;

Procedural style

int mysqli_get_proto_info(mysqli link);

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parameters

link

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

Return Values

Returns an integer representing the protocol version.

Examples

Example 22.127. $mysqli->protocol_version example

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print protocol version */printf("Protocol version: %d\n", $mysqli->protocol_version);/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print protocol version */printf("Protocol version: %d\n", mysqli_get_proto_info($link));/* close connection */mysqli_close($link);?>   

The above examples will output:

Protocol version: 10

See Also

mysqli_get_host_info

22.9.3.9.26. mysqli::$server_info,mysqli_get_server_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$server_info

    mysqli_get_server_info

    Returns the version of the MySQL server

Description

Object oriented style

string mysqli->server_info ;

Procedural style

string mysqli_get_server_info(mysqli link);

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parameters

link

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

Return Values

A character string representing the server version.

Examples

Example 22.128. $mysqli->server_info example

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print server version */printf("Server version: %s\n", $mysqli->server_info);/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print server version */printf("Server version: %s\n", mysqli_get_server_info($link));/* close connection */mysqli_close($link);?>   

The above examples will output:

Server version: 4.1.2-alpha-debug

See Also

mysqli_get_client_info
mysqli_get_client_version
mysqli_get_server_version

22.9.3.9.27. mysqli::$server_version,mysqli_get_server_version

Copyright 1997-2012 the PHP Documentation Group.

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

Procedural style

int mysqli_get_server_version(mysqli link);

The mysqli_get_server_version function returns the version of the server connected to (represented by the link parameter) as an integer.

Parameters

link

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

Return Values

An integer representing the server version.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).

Examples

Example 22.129. $mysqli->server_version example

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print server version */printf("Server version: %d\n", $mysqli->server_version);/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* print server version */printf("Server version: %d\n", mysqli_get_server_version($link));/* close connection */mysqli_close($link);?>   

The above examples will output:

Server version: 40102

See Also

mysqli_get_client_info
mysqli_get_client_version
mysqli_get_server_info

22.9.3.9.28. mysqli::get_warnings,mysqli_get_warnings

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::get_warnings

    mysqli_get_warnings

    Get result of SHOW WARNINGS

Description

Object oriented style

mysqli_warning mysqli::get_warnings();

Procedural style

mysqli_warning mysqli_get_warnings(mysqli link);
Warning

This function iscurrently not documented; only its argument list is available.

22.9.3.9.29. mysqli::$info, mysqli_info

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$info

    mysqli_info

    Retrieves information about the most recently executed query

Description

Object oriented style

string mysqli->info ;

Procedural style

string mysqli_info(mysqli link);

The mysqli_info function returns a string providing information about the last query executed. The nature of this string is provided below:

Table 22.49. Possible mysqli_info return values

Query type Example result string
INSERT INTO...SELECT... Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... Rows matched: 40 Changed: 40 Warnings: 0
Note

Queries which do not fall into one of the preceding formats are not supported. In these situations, mysqli_info will return an empty string.

Parameters

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.

Examples

Example 22.130. $mysqli->info 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();}$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");/* INSERT INTO .. SELECT */$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");printf("%s\n", $mysqli->info);/* 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();}mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");/* INSERT INTO .. SELECT */mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");printf("%s\n", mysqli_info($link));/* close connection */mysqli_close($link);?>   

The above examples will output:

Records: 150  Duplicates: 0  Warnings: 0

See Also

mysqli_affected_rows
mysqli_warning_count
mysqli_num_rows

22.9.3.9.30. mysqli::init, mysqli_init

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::init

    mysqli_init

    Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

Object oriented style

mysqli mysqli::init();

Procedural style

mysqli mysqli_init();

Allocates or initializes a MYSQL object suitable for mysqli_options and mysqli_real_connect.

Note

Any subsequent calls to any mysqli function (except mysqli_options) will fail until mysqli_real_connect was called.

Return Values

Returns an object.

Examples

See mysqli_real_connect.

See Also

mysqli_options
mysqli_close
mysqli_real_connect
mysqli_connect

22.9.3.9.31. mysqli::$insert_id,mysqli_insert_id

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$insert_id

    mysqli_insert_id

    Returns the auto generated id used in the last query

Description

Object oriented style

mixed mysqli->insert_id ;

Procedural style

mixed mysqli_insert_id(mysqli link);

The mysqli_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Note

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id function.

Parameters

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. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.

Note

If the number is greater than maximal int value, mysqli_insert_id will return a string.

Examples

Example 22.131. $mysqli->insert_id 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();}$mysqli->query("CREATE TABLE myCity LIKE City");$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";$mysqli->query($query);printf ("New Record has id %d.\n", $mysqli->insert_id);/* drop table */$mysqli->query("DROP TABLE myCity");/* 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();}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.

22.9.3.9.32. mysqli::kill, mysqli_kill

Copyright 1997-2012 the PHP Documentation Group.

  • 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

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

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 22.132. mysqli::killexample

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

22.9.3.9.33. mysqli::more_results,mysqli_more_results

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::more_results

    mysqli_more_results

    Check if there are any more query results from a multi query

Description

Object oriented style

bool mysqli::more_results();

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 if one or more result sets are available from a previous call to mysqli_multi_query, otherwise FALSE .

Examples

See mysqli_multi_query.

See Also

mysqli_multi_query
mysqli_next_result
mysqli_store_result
mysqli_use_result

22.9.3.9.34. mysqli::multi_query,mysqli_multi_query

Copyright 1997-2012 the PHP Documentation Group.

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

query

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 22.133. mysqli::multi_queryexample

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

Procedural style

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

The above examples will output something similar to:

my_user@localhost-----------------AmersfoortMaastrichtDordrechtLeidenHaarlemmermeer

See Also

mysqli_query
mysqli_use_result
mysqli_store_result
mysqli_next_result
mysqli_more_results

22.9.3.9.35. mysqli::next_result,mysqli_next_result

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::next_result

    mysqli_next_result

    Prepare next result from multi_query

Description

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

22.9.3.9.36. mysqli::options, mysqli_options

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::options

    mysqli_options

    Set options

Description

Object oriented style

bool mysqli::options(int option,
mixed value);

Procedural style

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

Used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

mysqli_options should be called after mysqli_init and before mysqli_real_connect.

Parameters

link

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

option

The option that you want to set. It can be one of the following values:

Table 22.50. Valid options

Name Description
MYSQLI_OPT_CONNECT_TIMEOUT connection timeout in seconds (supported on Windows with TCP/IP since PHP 5.3.1)
MYSQLI_OPT_LOCAL_INFILE enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND command to execute after when connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE Read options from named option file instead of my.cnf
MYSQLI_READ_DEFAULT_GROUP Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.
MYSQLI_SERVER_PUBLIC_KEY RSA public key file used with the SHA-256 based authentication.
value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.5.0 The MYSQLI_SERVER_PUBLIC_KEYoption 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.

Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init.

See Also

mysqli_init
mysqli_real_connect

22.9.3.9.37. mysqli::ping, mysqli_ping

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::ping

    mysqli_ping

    Pings a server connection, or tries to reconnect if the connection has gone down

Description

Object oriented style

bool mysqli::ping();

Procedural style

bool mysqli_ping(mysqli link);

Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Parameters

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

Example 22.134. mysqli::pingexample

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();}/* check if server is alive */if ($mysqli->ping()) {    printf ("Our connection is ok!\n");} else {    printf ("Error: %s\n", $mysqli->error);}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* check if server is alive */if (mysqli_ping($link)) {    printf ("Our connection is ok!\n");} else {    printf ("Error: %s\n", mysqli_error($link));}/* close connection */mysqli_close($link);?>   

The above examples will output:

Our connection is ok!

22.9.3.9.38. mysqli::poll, mysqli_poll

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::poll

    mysqli_poll

    Poll connections

Description

Object oriented style

public static int mysqli::poll(array read,
array error,
array reject,
int sec,
int usec);

Procedural style

int mysqli_poll(array read,
array error,
array reject,
int sec,
int usec);
Warning

This function iscurrently not documented; only its argument list is available.

Poll connections. Available only with mysqlnd. The method can be used as static.

Parameters

read

error

reject

sec

Number of seconds to wait, must be non-negative.

usec

Number of microseconds to wait, must be non-negative.

Return Values

Returns number of ready connections upon success, FALSE otherwise.

Examples

Example 22.135. A mysqli_pollexample

<?php$link1 = mysqli_connect();$link1->query("SELECT 'test'", MYSQLI_ASYNC);$all_links = array($link1);$processed = 0;do {    $links = $errors = $reject = array();    foreach ($all_links as $link) {        $links[] = $errors[] = $reject[] = $link;    }    if (!mysqli_poll($links, $errors, $reject, 1)) {        continue;    }    foreach ($links as $link) {        if ($result = $link->reap_async_query()) {            print_r($result->fetch_row());            if (is_object($result))                mysqli_free_result($result);           } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));        $processed++;    }} while ($processed < count($all_links));?>    

The above example will output:

Array(    [0] => test)

See Also

mysqli_query
mysqli_reap_async_query

22.9.3.9.39. mysqli::prepare, mysqli_prepare

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::prepare

    mysqli_prepare

    Prepare an SQL statement for execution

Description

Object oriented style

mysqli_stmt mysqli::prepare(string query);

Procedural style

mysqli_stmt mysqli_prepare(mysqli link,
string query);

Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param and/or mysqli_stmt_bind_result before executing the statement or fetching rows.

Parameters

link

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

query

The query, as a string.

Note

You should not add a terminating semicolon or \g to the statement.

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

mysqli_prepare returns a statement object or FALSE if an error occurred.

Examples

Example 22.136. mysqli::prepareexample

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();}$city = "Amersfoort";/* create a prepared statement */if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {    /* bind parameters for markers */    $stmt->bind_param("s", $city);    /* execute query */    $stmt->execute();    /* bind result variables */    $stmt->bind_result($district);    /* fetch value */    $stmt->fetch();    printf("%s is in district %s\n", $city, $district);    /* close statement */    $stmt->close();}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}$city = "Amersfoort";/* create a prepared statement */if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {    /* bind parameters for markers */    mysqli_stmt_bind_param($stmt, "s", $city);    /* execute query */    mysqli_stmt_execute($stmt);    /* bind result variables */    mysqli_stmt_bind_result($stmt, $district);    /* fetch value */    mysqli_stmt_fetch($stmt);    printf("%s is in district %s\n", $city, $district);    /* close statement */    mysqli_stmt_close($stmt);}/* close connection */mysqli_close($link);?>   

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

22.9.3.9.40. mysqli::query, mysqli_query

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::query

    mysqli_query

    Performs a query on the database

Description

Object oriented style

mixed mysqli::query(string query,
int resultmode= =MYSQLI_STORE_RESULT);

Procedural style

mixed mysqli_query(mysqli link,
string query,
int resultmode= =MYSQLI_STORE_RESULT);

Performs a query against the database.

For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling mysqli_real_query followed by either mysqli_use_result or mysqli_store_result.

Note

In the case where you pass a statement to mysqli_query that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

Parameters

link

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

query

The query string.

Data inside the query should be properly escaped.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll is then used to get results from such queries.

Return Values

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query will return a mysqli_result object. For other successful queries mysqli_query will return TRUE .

Changelog

Version Description
5.3.0 Added the ability of async queries.

Examples

Example 22.137. mysqli::queryexample

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

The above examples will output:

Table myCity successfully created.Select returned 10 rows.Error: Commands out of sync;  You can't run this command now

See Also

mysqli_real_query
mysqli_multi_query
mysqli_free_result

22.9.3.9.41. mysqli::real_connect,mysqli_real_connect

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::real_connect

    mysqli_real_connect

    Opens a connection to a mysql server

Description

Object oriented style

bool mysqli::real_connect(string host,
string username,
string passwd,
string dbname,
int port,
string socket,
int flags);

Procedural style

bool mysqli_real_connect(mysqli link,
string host,
string username,
string passwd,
string dbname,
int port,
string socket,
int flags);

Establish a connection to a MySQL database engine.

This function differs from mysqli_connect:

Parameters

link

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

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL , the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

flags

With the parameter flags you can set different connection options:

Table 22.51. Supported flags

Name Description
MYSQLI_CLIENT_COMPRESS Use compression protocol
MYSQLI_CLIENT_FOUND_ROWS return number of matched rows, not the number of affected rows
MYSQLI_CLIENT_IGNORE_SPACE Allow spaces after function names. Makes all function names reserved words.
MYSQLI_CLIENT_INTERACTIVE Allow interactive_timeout seconds (instead of wait_timeout seconds) ofinactivity before closing the connection
MYSQLI_CLIENT_SSL Use SSL (encryption)

Note

For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 22.138. mysqli::real_connectexample

Object oriented style

<?php$mysqli = mysqli_init();if (!$mysqli) {    die('mysqli_init failed');}if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {    die('Setting MYSQLI_INIT_COMMAND failed');}if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');}if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {    die('Connect Error (' . mysqli_connect_errno() . ') '            . mysqli_connect_error());}echo 'Success... ' . $mysqli->host_info . "\n";$mysqli->close();?>   

Object oriented style when extending mysqli class

<?phpclass foo_mysqli extends mysqli {    public function __construct($host, $user, $pass, $db) {        parent::init();        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {            die('Setting MYSQLI_INIT_COMMAND failed');        }        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');        }        if (!parent::real_connect($host, $user, $pass, $db)) {            die('Connect Error (' . mysqli_connect_errno() . ') '                    . mysqli_connect_error());        }    }}$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');echo 'Success... ' . $db->host_info . "\n";$db->close();?>   

Procedural style

<?php$link = mysqli_init();if (!$link) {    die('mysqli_init failed');}if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {    die('Setting MYSQLI_INIT_COMMAND failed');}if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');}if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {    die('Connect Error (' . mysqli_connect_errno() . ') '            . mysqli_connect_error());}echo 'Success... ' . mysqli_get_host_info($link) . "\n";mysqli_close($link);?>   

The above examples will output:

Success... MySQL host info: localhost via TCP/IP

Notes

Note

MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect, but after mysqli_init.

See Also

mysqli_connect
mysqli_init
mysqli_options
mysqli_ssl_set
mysqli_close

22.9.3.9.42. mysqli::real_escape_string,mysqli_real_escape_string

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::real_escape_string

    mysqli_real_escape_string

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

Description

Object oriented style

string mysqli::escape_string(string escapestr);
string mysqli::real_escape_string(string escapestr);

Procedural style

string mysqli_real_escape_string(mysqli link,
string escapestr);

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.

Security: the default character set

The character set must be set either at the server level, or with the API function mysqli_set_charset for it to affect mysqli_real_escape_string. 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

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return Values

Returns an escaped string.

Examples

Example 22.139. mysqli::real_escape_stringexample

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();}$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");$city = "'s Hertogenbosch";/* this query will fail, cause we didn't escape $city */if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {    printf("Error: %s\n", $mysqli->sqlstate);}$city = $mysqli->real_escape_string($city);/* this query with escaped $city will work */if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {    printf("%d Row inserted.\n", $mysqli->affected_rows);}$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");$city = "'s Hertogenbosch";/* this query will fail, cause we didn't escape $city */if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {    printf("Error: %s\n", mysqli_sqlstate($link));}$city = mysqli_real_escape_string($link, $city);/* this query with escaped $city will work */if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {    printf("%d Row inserted.\n", mysqli_affected_rows($link));}mysqli_close($link);?>   

The above examples will output:

Error: 420001 Row inserted.

Notes

Note

For those accustomed to using mysql_real_escape_string, note that the arguments of mysqli_real_escape_string differ from what mysql_real_escape_string expects. The link identifier comes first in mysqli_real_escape_string, whereas the string to be escaped comes first in mysql_real_escape_string.

See Also

mysqli_set_charset
mysqli_character_set_name

22.9.3.9.43. mysqli::real_query,mysqli_real_query

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::real_query

    mysqli_real_query

    Execute an SQL query

Description

Object oriented style

bool mysqli::real_query(string query);

Procedural style

bool mysqli_real_query(mysqli link,
string query);

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result or mysqli_use_result functions.

In order to determine if a given query should return a result set or not, see mysqli_field_count.

Parameters

link

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

query

The query, as a string.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_query
mysqli_store_result
mysqli_use_result

22.9.3.9.44. mysqli::reap_async_query,mysqli_reap_async_query

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::reap_async_query

    mysqli_reap_async_query

    Get result from async query

Description

Object oriented style

public mysqli_result mysqli::reap_async_query();

Procedural style

mysqli_result mysqli_reap_async_query(mysql link);
Warning

This function iscurrently not documented; only its argument list is available.

Get result from async query. Available only with mysqlnd.

Parameters

link

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

Return Values

Returns mysqli_result in success, FALSE otherwise.

See Also

mysqli_poll

22.9.3.9.45. mysqli::refresh, mysqli_refresh

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::refresh

    mysqli_refresh

    Refreshes

Description

Object oriented style

public bool mysqli::refresh(int options);

Procedural style

int mysqli_refresh(resource link,
int options);

Flushes tables or caches, or resets the replication server information.

Parameters

link

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

options

The options to refresh, using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation.

See also the official MySQL Refresh documentation.

Return Values

TRUE if the refresh was a success, otherwise FALSE

See Also

mysqli_poll

22.9.3.9.46. mysqli::release_savepoint,mysqli_release_savepoint

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::release_savepoint

    mysqli_release_savepoint

    Rolls back a transaction to the named savepoint

Description

Object oriented style (method):

public bool mysqli::release_savepoint(string name);

Procedural style:

bool mysqli_release_savepoint(mysqli link,
string name);

Warning

This function iscurrently not documented; only its argument list is available.

Parameters

link

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

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_rollback

22.9.3.9.47. mysqli::rollback, mysqli_rollback

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::rollback

    mysqli_rollback

    Rolls back current transaction

Description

Object oriented style

bool mysqli::rollback(int flags,
string name);

Procedural style

bool mysqli_rollback(mysqli link,
int flags,
string name);

Rollbacks the current transaction for the database.

Parameters

link

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

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then ROLLBACK/*name*/ is executed.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.5.0 Added flags and nameparameters.

Examples

Example 22.140. mysqli::rollbackexample

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();}/* disable autocommit */$mysqli->autocommit(FALSE);$mysqli->query("CREATE TABLE myCity LIKE City");$mysqli->query("ALTER TABLE myCity Type=InnoDB");$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");/* commit insert */$mysqli->commit();/* delete all rows */$mysqli->query("DELETE FROM myCity");if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {    $row = $result->fetch_row();    printf("%d rows in table myCity.\n", $row[0]);    /* Free result */    $result->close();}/* Rollback */$mysqli->rollback();if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {    $row = $result->fetch_row();    printf("%d rows in table myCity (after rollback).\n", $row[0]);    /* Free result */    $result->close();}/* Drop table myCity */$mysqli->query("DROP TABLE myCity");$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* disable autocommit */mysqli_autocommit($link, FALSE);mysqli_query($link, "CREATE TABLE myCity LIKE City");mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");/* commit insert */mysqli_commit($link);/* delete all rows */mysqli_query($link, "DELETE FROM myCity");if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {    $row = mysqli_fetch_row($result);    printf("%d rows in table myCity.\n", $row[0]);    /* Free result */    mysqli_free_result($result);}/* Rollback */mysqli_rollback($link);if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {    $row = mysqli_fetch_row($result);    printf("%d rows in table myCity (after rollback).\n", $row[0]);    /* Free result */    mysqli_free_result($result);}/* Drop table myCity */mysqli_query($link, "DROP TABLE myCity");mysqli_close($link);?>   

The above examples will output:

0 rows in table myCity.50 rows in table myCity (after rollback).

See Also

mysqli_begin_transaction
mysqli_commit
mysqli_autocommit
mysqli_release_savepoint

22.9.3.9.48. mysqli::rpl_query_type,mysqli_rpl_query_type

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::rpl_query_type

    mysqli_rpl_query_type

    Returns RPL query type

Description

Object oriented style

int mysqli::rpl_query_type(string query);

Procedural style

int mysqli_rpl_query_type(mysqli link,
string query);

Returns MYSQLI_RPL_MASTER , MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.

Warning

This function iscurrently not documented; only its argument list is available.

Warning

This function has beenDEPRECATED and REMOVED as of PHP 5.3.0.

22.9.3.9.49. mysqli::savepoint,mysqli_savepoint

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::savepoint

    mysqli_savepoint

    Set a named transaction savepoint

Description

Object oriented style (method):

public bool mysqli::savepoint(string name);

Procedural style:

bool mysqli_savepoint(mysqli link,
string name);

Warning

This function iscurrently not documented; only its argument list is available.

Parameters

link

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

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_commit

22.9.3.9.50. mysqli::select_db,mysqli_select_db

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::select_db

    mysqli_select_db

    Selects the default database for database queries

Description

Object oriented style

bool mysqli::select_db(string dbname);

Procedural style

bool mysqli_select_db(mysqli link,
string dbname);

Selects the default database to be used when performing queries against the database connection.

Note

This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect.

Parameters

link

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

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 22.141. mysqli::select_dbexample

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password", "test");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* return name of current default database */if ($result = $mysqli->query("SELECT DATABASE()")) {    $row = $result->fetch_row();    printf("Default database is %s.\n", $row[0]);    $result->close();}/* change db to world db */$mysqli->select_db("world");/* return name of current default database */if ($result = $mysqli->query("SELECT DATABASE()")) {    $row = $result->fetch_row();    printf("Default database is %s.\n", $row[0]);    $result->close();}$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "test");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* return name of current default database */if ($result = mysqli_query($link, "SELECT DATABASE()")) {    $row = mysqli_fetch_row($result);    printf("Default database is %s.\n", $row[0]);    mysqli_free_result($result);}/* change db to world db */mysqli_select_db($link, "world");/* return name of current default database */if ($result = mysqli_query($link, "SELECT DATABASE()")) {    $row = mysqli_fetch_row($result);    printf("Default database is %s.\n", $row[0]);    mysqli_free_result($result);}mysqli_close($link);?>   

The above examples will output:

Default database is test.Default database is world.

See Also

mysqli_connect
mysqli_real_connect

22.9.3.9.51. mysqli::send_query,mysqli_send_query

Copyright 1997-2012 the PHP Documentation Group.

  • 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,
string query);
Warning

This function iscurrently not documented; only its argument list is available.

Warning

This function has beenDEPRECATED and REMOVED as of PHP 5.3.0.

22.9.3.9.52. mysqli::set_charset,mysqli_set_charset

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::set_charset

    mysqli_set_charset

    Sets the default client character set

Description

Object oriented style

bool mysqli::set_charset(string charset);

Procedural style

bool mysqli_set_charset(mysqli link,
string charset);

Sets the default character set to be used when sending data from and to the database server.

Parameters

link

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

charset

The charset to be set as default.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note

To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).

Note

This is the preferred way to change the charset. Using mysqli_query to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

Examples

Example 22.142. mysqli::set_charsetexample

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password", "test");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* change character set to utf8 */if (!$mysqli->set_charset("utf8")) {    printf("Error loading character set utf8: %s\n", $mysqli->error);} else {    printf("Current character set: %s\n", $mysqli->character_set_name());}$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* change character set to utf8 */if (!mysqli_set_charset($link, "utf8")) {    printf("Error loading character set utf8: %s\n", mysqli_error($link));} else {    printf("Current character set: %s\n", mysqli_character_set_name($link));}mysqli_close($link);?>   

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

22.9.3.9.53. mysqli::set_local_infile_default,mysqli_set_local_infile_default

Copyright 1997-2012 the PHP Documentation Group.

  • 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);

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler.

Parameters

link

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

Return Values

No value is returned.

Examples

See mysqli_set_local_infile_handler examples

See Also

mysqli_set_local_infile_handler

22.9.3.9.54. mysqli::set_local_infile_handler,mysqli_set_local_infile_handler

Copyright 1997-2012 the PHP Documentation Group.

  • 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,
callable read_func);

Procedural style

bool mysqli_set_local_infile_handler(mysqli link,
callable read_func);

Set callback function for LOAD DATA LOCAL INFILE command

The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE.

The returned data needs to match the format specified in the LOAD DATA

Parameters

link

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

read_func

A callback function or object method taking the following parameters:

stream

A PHP stream associated with the SQL commands INFILE

&buffer

A string buffer to store the rewritten input into

buflen

The maximum number of characters to be stored in the buffer

&errormsg

If an error occurs you can store an error message in here

The callback function should return the number of characters stored in the buffer or a negative value if an error occurred.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 22.143. mysqli::set_local_infile_handlerexample

Object oriented style

<?php  $db = mysqli_init();  $db->real_connect("localhost","root","","test");  function callme($stream, &$buffer, $buflen, &$errmsg)  {    $buffer = fgets($stream);    echo $buffer;    // convert to upper case and replace "," delimiter with [TAB]    $buffer = strtoupper(str_replace(",", "\t", $buffer));    return strlen($buffer);  }  echo "Input:\n";  $db->set_local_infile_handler("callme");  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");  $db->set_local_infile_default();  $res = $db->query("SELECT * FROM t1");  echo "\nResult:\n";  while ($row = $res->fetch_assoc()) {    echo join(",", $row)."\n";  }?>   

Procedural style

<?php  $db = mysqli_init();  mysqli_real_connect($db, "localhost","root","","test");  function callme($stream, &$buffer, $buflen, &$errmsg)  {    $buffer = fgets($stream);    echo $buffer;    // convert to upper case and replace "," delimiter with [TAB]    $buffer = strtoupper(str_replace(",", "\t", $buffer));    return strlen($buffer);  }  echo "Input:\n";  mysqli_set_local_infile_handler($db, "callme");  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");  mysqli_set_local_infile_default($db);  $res = mysqli_query($db, "SELECT * FROM t1");  echo "\nResult:\n";  while ($row = mysqli_fetch_assoc($res)) {    echo join(",", $row)."\n";  }?>   

The above examples will output:

Input:23,foo42,barOutput:23,FOO42,BAR

See Also

mysqli_set_local_infile_default

22.9.3.9.55. mysqli::$sqlstate, mysqli_sqlstate

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$sqlstate

    mysqli_sqlstate

    Returns the SQLSTATE error from previous MySQL operation

Description

Object oriented style

string mysqli->sqlstate ;

Procedural style

string mysqli_sqlstate(mysqli link);

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.

Note

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Parameters

link

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

Return Values

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

Examples

Example 22.144. $mysqli->sqlstate example

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* Table City already exists, so we should get an error */if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);}$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}/* Table City already exists, so we should get an error */if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));}mysqli_close($link);?>   

The above examples will output:

Error - SQLSTATE 42S01.

See Also

mysqli_errno
mysqli_error

22.9.3.9.56. mysqli::ssl_set, mysqli_ssl_set

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::ssl_set

    mysqli_ssl_set

    Used for establishing secure connections using SSL

Description

Object oriented style

bool mysqli::ssl_set(string key,
string cert,
string ca,
string capath,
string cipher);

Procedural style

bool mysqli_ssl_set(mysqli link,
string key,
string cert,
string ca,
string capath,
string cipher);

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect. This function does nothing unless OpenSSL support is enabled.

Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.

Parameters

link

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

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Any unused SSL parameters may be given as NULL

Return Values

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect will return an error when you attempt to connect.

See Also

mysqli_options
mysqli_real_connect

22.9.3.9.57. mysqli::stat, mysqli_stat

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::stat

    mysqli_stat

    Gets the current system status

Description

Object oriented style

string mysqli::stat();

Procedural style

string mysqli_stat(mysqli link);

mysqli_stat returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.

Parameters

link

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

Return Values

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

Examples

Example 22.145. mysqli::statexample

Object oriented style

<?php$mysqli = new mysqli("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}printf ("System status: %s\n", $mysqli->stat());$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}printf("System status: %s\n", mysqli_stat($link));mysqli_close($link);?>   

The above examples will output:

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632Memory in use: 8496K  Max memory used: 8560K

See Also

mysqli_get_server_info

22.9.3.9.58. mysqli::stmt_init,mysqli_stmt_init

Copyright 1997-2012 the PHP Documentation Group.

  • 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_stmt mysqli_stmt_init(mysqli link);

Allocates and initializes a statement object suitable for mysqli_stmt_prepare.

Note

Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare was called.

Parameters

link

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

Return Values

Returns an object.

See Also

mysqli_stmt_prepare

22.9.3.9.59. mysqli::store_result,mysqli_store_result

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::store_result

    mysqli_store_result

    Transfers a result set from the last query

Description

Object oriented style

mysqli_result mysqli::store_result();

Procedural style

mysqli_result mysqli_store_result(mysqli link);

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek function.

Parameters

link

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

Return Values

Returns a buffered result object or FALSE if an error occurred.

Note

mysqli_store_result returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error doesn't return an empty string, if mysqli_errno returns a non zero value, or if mysqli_field_count returns a non zero value. Also possible reason for this function returning FALSE after successful call to mysqli_query can be too large result set (memory for it cannot be allocated). If mysqli_field_count returns a non-zero value, the statement should have produced a non-empty result set.

Notes

Note

Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result function, when transferring large result sets using the mysqli_store_result this becomes particularly important.

Examples

See mysqli_multi_query.

See Also

mysqli_real_query
mysqli_use_result

22.9.3.9.60. mysqli::$thread_id,mysqli_thread_id

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$thread_id

    mysqli_thread_id

    Returns the thread ID for the current connection

Description

Object oriented style

int 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. If the connection is lost and you reconnect with mysqli_ping, the thread ID will be other. Therefore you should get the thread ID only when you need it.

Note

The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

To kill a running query you can use the SQL command KILL QUERY processid.

Parameters

link

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

Return Values

Returns the Thread ID for the current connection.

Examples

Example 22.146. $mysqli->thread_id 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();}/* 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_kill

22.9.3.9.61. mysqli::thread_safe,mysqli_thread_safe

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::thread_safe

    mysqli_thread_safe

    Returns whether thread safety is given or not

Description

Procedural style

bool mysqli_thread_safe();

Tells whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE .

22.9.3.9.62. mysqli::use_result,mysqli_use_result

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::use_result

    mysqli_use_result

    Initiate a result set retrieval

Description

Object oriented style

mysqli_result mysqli::use_result();

Procedural style

mysqli_result mysqli_use_result(mysqli link);

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query function on the database connection.

Either this or the mysqli_store_result function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Note

The mysqli_use_result function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result. One should not use mysqli_use_result if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Return Values

Returns an unbuffered result object or FALSE if an error occurred.

Examples

Example 22.147. mysqli::use_resultexample

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->use_result()) {            while ($row = $result->fetch_row()) {                printf("%s\n", $row[0]);            }            $result->close();        }        /* print divider */        if ($mysqli->more_results()) {            printf("-----------------\n");        }    } while ($mysqli->next_result());}/* close connection */$mysqli->close();?>   

Procedural style

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

The above examples will output:

my_user@localhost-----------------AmersfoortMaastrichtDordrechtLeidenHaarlemmermeer

See Also

mysqli_real_query
mysqli_store_result

22.9.3.9.63. mysqli::$warning_count,mysqli_warning_count

Copyright 1997-2012 the PHP Documentation Group.

  • mysqli::$warning_count

    mysqli_warning_count

    Returns the number of warnings from the last query for the given link

Description

Object oriented style

int mysqli->warning_count ;

Procedural style

int mysqli_warning_count(mysqli link);

Returns the number of warnings from the last query in the connection.

Note

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parameters

link

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

Return Values

Number of warnings or zero if there are no warnings.

Examples

Example 22.148. $mysqli->warning_count 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();}$mysqli->query("CREATE TABLE myCity LIKE City");/* a remarkable city in Wales */$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";$mysqli->query($query);if ($mysqli->warning_count) {    if ($result = $mysqli->query("SHOW WARNINGS")) {        $row = $result->fetch_row();        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);        $result->close();    }}/* close connection */$mysqli->close();?>   

Procedural style

<?php$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}mysqli_query($link, "CREATE TABLE myCity LIKE City");/* a remarkable long city name in Wales */$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";mysqli_query($link, $query);if (mysqli_warning_count($link)) {    if ($result = mysqli_query($link, "SHOW WARNINGS")) {        $row = mysqli_fetch_row($result);        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);        mysqli_free_result($result);    }}/* close connection */mysqli_close($link);?>   

The above examples will output:

Warning (1264): Data truncated for column 'Name' at row 1

See Also

mysqli_errno
mysqli_error
mysqli_sqlstate