PHP MySQLi

fMust Watch!



MustWatch



MySQLi Introduction

The MySQLi functions allows you to access MySQL database servers. Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.

Installation / Runtime Configuration

For the MySQLi functions to be available, you must compile PHP with support for the MySQLi extension. The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0. For installation details, go to: http://php.net/manual/en/mysqli.installation.php For runtime configuration details, go to: http://php.net/manual/en/mysqli.configuration.php

MySQLi Functions

FunctionDescription
affected_rows()Returns the number of affected rows in the previous MySQL operation
autocommit()Turns on or off auto-committing database modifications
begin_transaction()Starts a transaction
change_user()Changes the user of the specified database connection
character_set_name()Returns the default character set for the database connection
close()Closes a previously opened database connection
commit()Commits the current transaction
connect()Opens a new connection to the MySQL server
connect_errno()Returns the error code from the last connection error
connect_error()Returns the error description from the last connection error
data_seek()Adjusts the result pointer to an arbitrary row in the result-set
debug()Performs debugging operations
dump_debug_info()Dumps debugging info into the log
errno()Returns the last error code for the most recent function call
error()Returns the last error description for the most recent function call
error_list()Returns a list of errors for the most recent function call
fetch_all()Fetches all result rows as an associative array, a numeric array, or both
fetch_array()Fetches a result row as an associative, a numeric array, or both
fetch_assoc()Fetches a result row as an associative array
fetch_field()Returns the next field in the result-set, as an object
fetch_field_direct()Returns meta-data for a single field in the result-set, as an object
fetch_fields()Returns an array of objects that represent the fields in a result-set
fetch_lengths()Returns the lengths of the columns of the current row in the result-set
fetch_object()Returns the current row of a result-set, as an object
fetch_row()Fetches one row from a result-set and returns it as an enumerated array
field_count()Returns the number of columns for the most recent query
field_seek()Sets the field cursor to the given field offset
get_charset()Returns a character set object
get_client_info()Returns the MySQL client library version
get_client_stats()Returns statistics about client per-process
get_client_version()Returns the MySQL client library version as an integer
get_connection_stats()Returns statistics about the client connection
get_host_info()Returns the MySQL server hostname and the connection type
get_proto_info()Returns the MySQL protocol version
get_server_info()Returns the MySQL server version
get_server_version()Returns the MySQL server version as an integer
info()Returns information about the last executed query
init()Initializes MySQLi and returns a resource for use with real_connect()
insert_id()Returns the auto-generated id from the last query
kill()Asks the server to kill a MySQL thread
more_results()Checks if there are more results from a multi query
multi_query()Performs one or more queries on the database
next_result()Prepares the next result-set from multi_query()
options()Sets extra connect options and affect behavior for a connection
ping()Pings a server connection, or tries to reconnect if the connection has gone down
poll()Polls connections
prepare()Prepares an SQL statement for execution
query()Performs a query against a database
real_connect()Opens a new connection to the MySQL server
real_escape_string()Escapes special characters in a string for use in an SQL statement
real_query()Executes a single SQL query
reap_async_query()Returns result from an async SQL query
refresh()Refreshes/flushes tables or caches, or resets the replication server information
rollback()Rolls back the current transaction for the database
select_db()Select the default database for database queries
set_charset()Sets the default client character set
set_local_infile_default()Unsets user defined handler for load local infile command
set_local_infile_handler()Set callback function for LOAD DATA LOCAL INFILE command
sqlstate()Returns the SQLSTATE error code for the error
ssl_set()Used to establish secure connections using SSL
stat()Returns the current system status
stmt_init()Initializes a statement and returns an object for use with stmt_prepare()
store_result()Transfers a result-set from the last query
thread_id()Returns the thread ID for the current connection
thread_safe()Returns whether the client library is compiled as thread-safe
use_result()Initiates the retrieval of a result-set from the last query executed
warning_count()Returns the number of warnings from the last query in the connection

affected_rows Function

Example - Object Oriented style

Return the number of affected rows from different queries: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform queries and print out affected rows $conn -> query("SELECT * FROM Persons"); echo "Affected rows: " . $conn -> affected_rows; $conn -> query("DELETE FROM Persons WHERE Age>32"); echo "Affected rows: " . $conn -> affected_rows; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.

Syntax

Object oriented style:

$conn -> affected_rows

Procedural style:

mysqli_affected_rows(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:The number of rows affected. -1 indicates that the query returned an error
PHP Version:5+

Example - Procedural style

Return the number of affected rows from different queries: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform queries and print out affected rows mysqli_query($con, "SELECT * FROM Persons"); echo "Affected rows: " . mysqli_affected_rows($con); mysqli_query($con, "DELETE FROM Persons WHERE Age>32"); echo "Affected rows: " . mysqli_affected_rows($con); mysqli_close($con); ?>

autocommit() Function

Example - Object Oriented style

Turn off auto-committing, make some queries, then commit the queries: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Turn autocommit off $conn -> autocommit(FALSE); // Insert some values $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn -> commit()) { echo "Commit transaction failed"; exit(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The autocommit() / mysqli_autocommit() function turns on or off auto-committing database modifications. Tip: Also look at the commit() function, which commits the current transaction for the specified database connection, and the rollback() function, which rolls back the current transaction.

Syntax

Object oriented style:

$conn -> autocommit(mode)

Procedural style:

mysqli_autocommit(connection, mode)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
modeRequired. FALSE turns auto-commit off. TRUE turns auto-commit on (and commits any waiting queries)

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Turn off auto-committing, make some queries, then commit the queries: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Turn autocommit off mysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn_commit($con)) { echo "Commit transaction failed"; exit(); } // Close connection mysqli_close($con); ?>

change_user() Function

Example - Object Oriented style

Change the user of the specified database connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Reset all and select a new database $conn -> change_user("my_user", "my_password", "test"); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The change_user() / mysqli_change_user() function changes the user of the specified database connection, and sets the current database.

Syntax

Object oriented style:

$conn -> change_user(username, password, dbname)

Procedural style:

mysqli_change_user(connection, username, password, dbname)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
usernameRequired. Specifies the MySQL user name
passwordRequired. Specifies the MySQL password
dbnameRequired. Specifies the database to change to

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Change the user of the specified database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Reset all and select a new database mysqli_change_user($con, "my_user", "my_password", "test"); mysqli_close($con); ?>

character_set_name() Function

Example - Object Oriented style

Return the default character set for the database connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $charset = $conn -> character_set_name(); echo "Default character set is: " . $charset; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The character_set_name() / mysqli_character_set_name() function returns the default character set for the database connection.

Syntax

Object oriented style:

$conn -> character_set_name()

Procedural style:

mysqli_character_set_name(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:The default character set for the specified connection
PHP Version:5+

Example - Procedural style

Return the default character set for the database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $charset=mysqli_character_set_name($con); echo "Default character set is: " . $charset; mysqli_close($con); ?>

close() Function

Example - Object Oriented style

Close a previously opened database connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // ....some PHP code... $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The close() / mysqli_close() function closes a previously opened database connection.

Syntax

Object oriented style:

$conn -> close()

Procedural style:

mysqli_close(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to close

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Close a previously opened database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // ....some PHP code... mysqli_close($con); ?>

commit() Function

Example - Object Oriented style

Turn off auto-committing, make some queries, then commit the queries: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Turn autocommit off $conn -> autocommit(FALSE); // Insert some values $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn -> commit()) { echo "Commit transaction failed"; exit(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The commit() / mysqli_commit() function commits the current transaction for the specified database connection. Tip: Also look at the autocommit() function, which turns on or off auto-committing database modifications, and the rollback() function, which rolls back the current transaction.

Syntax

Object oriented style:

$conn -> commit(flags, name)

Procedural style:

mysqli_commit(connection, flags, name)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
flagsOptional. A constant:
  • MYSQLI_TRANS_COR_AND_CHAIN - Appends "AND CHAIN"
  • MYSQLI_TRANS_COR_AND_NO_CHAIN - Appends "AND NO CHAIN"
  • MYSQLI_TRANS_COR_RELEASE - Appends "RELEASE"
  • MYSQLI_TRANS_COR_NO_RELEASE - Appends "NO RELEASE"
nameOptional. COMMIT/*name*/ is executed if this parameter is specified

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+
PHP Changelog:PHP 5.5: Added the flags and name parameters

Example - Procedural style

Turn off auto-committing, make some queries, then commit the queries: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Turn autocommit off mysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn_commit($con)) { echo "Commit transaction failed"; exit(); } // Close connection mysqli_close($con); ?>

connect() Function

Example - Object Oriented style

Open a new connection to the MySQL server: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } ?> Look at example of procedural style at the bottom.

Definition and Usage

The connect() / mysqli_connect() function opens a new connection to the MySQL server.

Syntax

Object oriented style:

$conn -> new mysqli(host, username, password, dbname, port, socket)

Procedural style:

mysqli_connect(host, username, password, dbname, port, socket)

Parameter Values

ParameterDescription
hostOptional. Specifies a host name or an IP address
usernameOptional. Specifies the MySQL username
passwordOptional. Specifies the MySQL password
dbnameOptional. Specifies the default database to be used
portOptional. Specifies the port number to attempt to connect to the MySQL server
socketOptional. Specifies the socket or named pipe to be used

Technical Details

Return Value:Returns an object representing the connection to the MySQL server
PHP Version:5+

Example - Procedural style

Open a new connection to the MySQL server: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } ?>

connect_errno() Function

Example - Object Oriented style

Return an error code from the last connection error, if any: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } ?> Look at example of procedural style at the bottom.

Definition and Usage

The connect_errno / mysqli_connect_errno() function returns the error code from the last connection error, if any.

Syntax

Object oriented style:

$conn -> connect_errno

Procedural style:

mysqli_connect_errno()

Technical Details

Return Value:Returns an error code value. Zero if no error occurred
PHP Version:5+

Example - Procedural style

Return an error code from the last connection error, if any: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } ?>

connect_error() Function

Example - Object Oriented style

Return the error description from the last connection error, if any: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } ?> Look at example of procedural style at the bottom.

Definition and Usage

The connect_error / mysqli_connect_error() function returns the error description from the last connection error, if any.

Syntax

Object oriented style:

$conn -> connect_error

Procedural style:

mysqli_connect_error();

Technical Details

Return Value:Returns a string that describes the error. NULL if no error occurred
PHP Version:5+

Example - Procedural style

Return the error description from the last connection error, if any: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } ?>

mysqli_data_seek() Function

Example

Seek to row number 15 in the result-set: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Seek to row number 15 mysqli_data_seek($result,14); // Fetch row $row=mysqli_fetch_row($result); printf ("Lastname: %s Age: %s\n", $row[0], $row[1]); // Free result set mysqli_free_result($result); } mysqli_close($con); ?>

Definition and Usage

The mysqli_data_seek() function adjusts the result pointer to an arbitrary row in the result-set.

Syntax

mysqli_data_seek(result,offset);

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
offsetRequired. Specifies the field offset. Must be between 0 and the total number of rows - 1

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

mysqli_debug() Function

Example

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

Definition and Usage

The mysqli_debug() function is used to perform debugging operations. Note: In order to use this function, you must compile the MySQL client library to support debugging.

Syntax

mysqli_debug(message);

Parameter Values

ParameterDescription
messageRequired. A string that represents the debugging operation to perform

Technical Details

Return Value:TRUE
PHP Version:5+

dump_debug_info() Function

Example - Object Oriented style

Dump debug info into the log: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); $conn -> dump_debug_info(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The dump_debug_info() / mysqli_dump_debug_info() function dumps debugging info into the log.

Syntax

Object oriented style:

$conn -> dump_debug_info()

Procedural style:

mysqli_dump_debug_info(link);

Parameter Values

ParameterDescription
linkRequired. A link identifier returned by connect() or init()

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Dump debug info into the log: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); mysqli_dump_debug_info($con); ?>

errno() Function

Example - Object Oriented style

Return the last error code for the most recent function call, if any: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform a query, check for error if (!$conn -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Errorcode: " . $conn -> errno); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The errno / mysqli_errno() function returns the last error code for the most recent function call, if any.

Syntax

Object oriented style:

$conn -> errno

Procedural style:

mysqli_errno(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an error code value. Zero if no error occurred
PHP Version:5+

Example - Procedural style

Return the last error code for the most recent function call, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform a query, check for error if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Errorcode: " . mysqli_errno($con)); } mysqli_close($con); ?>

error() Function

Example - Object Oriented style

Return the last error description for the most recent function call, if any: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform a query, check for error if (!$conn -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . $conn -> error); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The error / mysqli_error() function returns the last error description for the most recent function call, if any.

Syntax

Object oriented style:

$conn -> error

Procedural style:

mysqli_error(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns a string with the error description. " if no error occurred
PHP Version:5+

Example - Procedural Oriented style

Return the last error description for the most recent function call, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform a query, check for error if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . mysqli_error($con)); } mysqli_close($con); ?>

error_list() Function

Example - Object Oriented style

Return a list of errors from the last executed command, if any: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform a query, check for error if (!$conn -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { print_r($conn -> error_list); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The error_list / mysqli_error_list() function returns a list of errors from the last executed command, if any.

Syntax

Object oriented style:

$conn -> error_list

Procedural style:

mysqli_error_list(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns a list of errors as an associative array; with errno (error code), error (error text), and sqlstate
PHP Version:5.4+

Example - Procedural style

Return a list of errors from the last executed command, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform a query, check for error if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { print_r(mysqli_error_list($con)); } mysqli_close($con); ?>

fetch_all() Function

Example - Object Oriented style

Fetch all rows and return the result-set as an associative array: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result -> $conn -> query($sql); // Fetch all $result -> fetch_all(MYSQLI_ASSOC); // Free result set $result -> free_result(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both. Note: This function is available only with MySQL Native Driver.

Syntax

Object oriented style:

$conn_result -> fetch_all(resulttype)

Procedural style:

mysqli_fetch_all(result, resulttype)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
resulttypeOptional. Specifies what type of array that should be produced. Can be one of the following values:
  • MYSQLI_ASSOC
  • MYSQLI_NUM (this is default)
  • MYSQLI_BOTH

Technical Details

Return Value:Returns an array of associative or numeric arrays holding the result rows
PHP Version:5.3+

Example - Procedural style

Fetch all rows and return the result-set as an associative array: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con, $sql); // Fetch all mysqli_fetch_all($result, MYSQLI_ASSOC); // Free result set mysqli_free_result($result); mysqli_close($con); ?>

fetch_array() Function

Example - Object Oriented style

Fetch a result row as a numeric array and as an associative array: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result -> $conn -> query($sql); // Numeric array $row = $result -> fetch_array(MYSQLI_NUM); printf ("%s (%s)\n", $row[0], $row[1]); // Associative array $row = $result -> fetch_array(MYSQLI_ASSOC); printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set $result -> free_result(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_array() / mysqli_fetch_array() function fetches a result row as an associative array, a numeric array, or both. Note: Fieldnames returned from this function are case-sensitive.

Syntax

Object oriented style:

$conn_result -> fetch_array(resulttype)

Procedural style:

mysqli_fetch_array(result,resulttype)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
resulttypeOptional. Specifies what type of array that should be produced. Can be one of the following values:
  • MYSQLI_ASSOC
  • MYSQLI_NUM
  • MYSQLI_BOTH (this is default)

Technical Details

Return Value:Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result-set
PHP Version:5+

Example - Procedural style

Fetch a result row as a numeric array and as an associative array: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con,$sql); // Numeric array $row = mysqli_fetch_array($result, MYSQLI_NUM); printf ("%s (%s)\n", $row[0], $row[1]); // Associative array $row = mysqli_fetch_array($result, MYSQLI_ASSOC); printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set mysqli_free_result($result); mysqli_close($con); ?>

fetch_assoc() Function

Example - Object Oriented style

Fetch a result row as an associative array: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = $conn -> query($sql); // Associative array $row = $result -> fetch_assoc(); printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set $result -> free_result(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_assoc() / mysqli_fetch_assoc() function fetches a result row as an associative array. Note: Fieldnames returned from this function are case-sensitive.

Syntax

Object oriented style:

$conn_result -> fetch_assoc()

Procedural style:

mysqli_fetch_assoc(result)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an associative array of strings representing the fetched row. NULL if there are no more rows in result-set
PHP Version:5+

Example - Procedural style

Fetch a result row as an associative array: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con, $sql); // Associative array $row = mysqli_fetch_assoc($result); printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set mysqli_free_result($result); mysqli_close($con); ?>

fetch_field() Function

Example - Object Oriented style

Return the next field (column) in the result-set, then print each field's name, table, and max length: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { // Get field information for all fields while ($fieldinfo = $result -> fetch_field()) { printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); } $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_field() / mysqli_fetch_field() function returns the next field (column) in the result-set, as an object.

Syntax

Object oriented style:

$conn_result -> fetch_field()

Procedural style:

mysqli_fetch_field(result)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an object containing field definition information. FALSE if no info is available. The object has the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • def - reserved for default values, currently always "
  • db - database (new in PHP 5.3.6)
  • catalog - catalog name, always "def" (since PHP 5.3.6)
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
PHP Version:5+

Example - Procedural style

Return the next field (column) in the result-set, then print each field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Get field information for all fields while ($fieldinfo = mysqli_fetch_field($result)) { printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("max. Len: %d\n", $fieldinfo -> max_length); } mysqli_free_result($result); } mysqli_close($con); ?>

fetch_field_direct() Function

Example - Object Oriented style

Return meta-data for a single field in the result-set, then print the field's name, table, and max length: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { // Get field information for column "Age" $fieldinfo = $result -> fetch_field_direct(1); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_field_direct() / mysqli_fetch_field_direct() function returns meta-data for a single field in a result-set, as an object.

Syntax

Object oriented style:

$conn_result -> fetch_field_direct(fieldnr)

Procedural style:

mysqli_fetch_field_direct(result, fieldnr)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
fieldnrRequired. Specifies the field number. Must be an integer from 0 to number of fields-1

Technical Details

Return Value:Returns an object containing field definition information. FALSE if no info is available. The object has the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • def - default value for this field
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
PHP Version:5+

Example - Procedural style

Return meta-data for a single field in the result-set, then print the field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Get field information for column "Age" $fieldinfo = mysqli_fetch_field_direct($result, 1); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); mysqli_free_result($result); } mysqli_close($con); ?>

fetch_fields() Function

Example - Object Oriented style

Return an array of objects that represent the fields in a result-set, then print each field's name, table, and max length: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { // Get field information for all fields $fieldinfo = $result -> fetch_fields(); foreach ($fieldinfo as $val) { printf("Name: %s\n", $val -> name); printf("Table: %s\n", $val -> table); printf("Max. Len: %d\n", $val -> max_length); } $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_fields() / mysqli_fetch_fields() function returns an array of objects that represent the fields in a result-set.

Syntax

Object oriented style:

$conn_result -> fetch_fields()

Procedural style:

mysqli_fetch_fields(result)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an array of objects containing field definition information. FALSE if no info is available. The objects have the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
PHP Version:5+

Example - Procedural style

Return an array of objects that represent the fields in a result-set, then print each field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con , $sql)) { // Get field information for all fields $fieldinfo = mysqli_fetch_fields($result); foreach ($fieldinfo as $val) { printf("Name: %s\n", $val->name); printf("Table: %s\n", $val->table); printf("Max. Len: %d\n", $val->max_length); } mysqli_free_result($result); } mysqli_close($con); ?>

lengths / mysqli_fetch_lengths() Function

Example - Object Oriented style

Return the length of the fields of the current row in the result-set: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT * FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { $row = $result -> fetch_row(); // Display field lengths foreach ($result -> lengths as $i => $val) { printf("Field %2d has length: %2d\n", $i + 1, $val); } $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The lengths / mysqli_fetch_lengths() function returns the length of the fields of the current row in the result-set.

Syntax

Object oriented style:

$conn_result -> lengths

Procedural style:

mysqli_fetch_lengths(result)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an array of integers that represents the size of each field (column). FALSE if an error occurs
PHP Version:5+

Example - Procedural style

Return the length of the fields of the current row in the result-set: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT * FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { $row = mysqli_fetch_row($result); // Display field lengths foreach (mysqli_fetch_lengths($result) as $i => $val) { printf("Field %2d has length: %2d\n", $i+1, $val); } mysqli_free_result($result); } mysqli_close($con); ?>

fetch_object() Function

Example - Object Oriented style

Return the current row of a result set, then print each field's value: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { while ($obj = $result -> fetch_object()) { printf("%s (%s)\n", $obj->Lastname, $obj->Age); } $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_object() / mysqli_fetch_object() function returns the current row of a result-set, as an object. Note: Fieldnames returned from this function are case-sensitive.

Syntax

Object oriented style:

$conn_result -> fetch_object(classname, params)

Procedural style:

mysqli_fetch_object(result, classname, params)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
classnameOptional. Specifies the name of the class to instantiate, set the properties of, and return
paramsOptional. Specifies an array of parameters to pass to the constructor for classname objects

Technical Details

Return Value:Returns an object with string properties for the fetched row. NULL if there are no more rows in the result set
PHP Version:5+
Changelog:The ability to return as a different object was added in PHP 5.0.0

Example - Procedural style

Return the current row of a result set, then print each field's value: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { while ($obj = mysqli_fetch_object($result)) { printf("%s (%s)\n", $obj->Lastname, $obj->Age); } mysqli_free_result($result); } mysqli_close($con); ?>

fetch_row() Function

Example - Object Oriented style

Fetch rows from a result-set: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { while ($row = $result -> fetch_row()) { printf ("%s (%s)\n", $row[0], $row[1]); } $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.

Syntax

Object oriented style:

$conn_result -> fetch_row()

Procedural style:

mysqli_fetch_row(result)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result set
PHP Version:5+

Example - Procedural style

Fetch rows from a result-set: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Fetch one and one row while ($row = mysqli_fetch_row($result)) { printf ("%s (%s)\n", $row[0], $row[1]); } mysqli_free_result($result); } mysqli_close($con); ?>

field_count() Function

Example - Object Oriented style

Assume we have a table named "Friends" (with 3 columns and 20 rows). This example returns the number of columns for the most recent query: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $conn -> query("SELECT * FROM Friends"); // Get number of columns - will return 3 $conn -> field_count(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The field_count() / mysqli_field_count() function returns the number of columns for the most recent query.

Syntax

Object oriented style:

$conn -> field_count()

Procedural style:

mysqli_field_count(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an integer that represents the number of columns in the result set
PHP Version:5+

Example - Procedural style

Assume we have a table named "Friends" (with 3 columns and 20 rows). This example returns the number of columns for the most recent query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } mysqli_query($con, "SELECT * FROM Friends"); // Get number of columns - will return 3 mysqli_field_count($con); mysqli_close($con); ?>

field_seek() Function

Example - Object Oriented style

Set the field cursor to the second column ("Age") in the result-set, get field info with fetch_field(), then print the field's name, table, and max length: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $conn -> query($sql)) { // Get field information for second column $result = field_seek(1); $fieldinfo = $result -> fetch_field(); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The field_seek() / mysqli_field_seek() function sets the field cursor to the given field offset.

Syntax

Object oriented style:

$conn_result -> field_seek(fieldnr)

Procedural style:

mysqli_field_seek(result, fieldnr)

Parameter Values

ParameterDescription
resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
fieldnrRequired. Specifies the field number. Must be an integer from 0 to number of fields-1

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Set the field cursor to the second column ("Age") in the result-set, get field info with mysqli_fetch_field(), then print the field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql="SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con,$sql)) { // Get field information for second column mysqli_field_seek($result, 1); $fieldinfo = mysqli_fetch_field($result); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("max. Len: %d\n", $fieldinfo -> max_length); mysqli_free_result($result); } mysqli_close($con); ?>

get_charset() Function

Example - Object Oriented style

Return a character set object, with several properties: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } var_dump($conn -> get_charset()); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The get_charset() / mysqli_get_charset() function returns a character set object with several properties for the current character set.

Syntax

Object oriented style:

$conn -> get_charset()

Procedural style:

mysqli_get_charset(connection);

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns a character set object with the following properties:
  • charset - character set name
  • collation - collation name
  • dir - directory the charset was fetched from or "
  • min_length - min character length in bytes
  • max_length - max character length in bytes
  • number - internal character set number
  • state - character set status
PHP Version:5.1+

Example - Procedural style

Return a character set object, with several properties: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } var_dump(mysqli_get_charset($con)); mysqli_close($con); ?>

get_client_info() Function

Example

Return the MySQL client library version: <?php echo mysqli_get_client_info(); ?>

Definition and Usage

The get_client_info() / mysqli_get_client_info() function returns the MySQL client library version.

Syntax

Object oriented style:

$conn -> get_client_info()

Procedural style:

mysqli_get_client_info(connection)

Parameter Values

ParameterDescription
connectionOptional. Specifies the MySQL connection to use

Technical Details

Return Value:Returns a string that represents the MySQL client library version
PHP Version:5+

mysqli_get_client_stats() Function

Example

Return stats about client per-process: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); print_r(mysqli_get_client_stats()); ?>

Definition and Usage

The mysqli_get_client_stats() function returns client per-process statistics.

Syntax

mysqli_get_client_stats()

Technical Details

Return Value:An array with client stats on success. FALSE on failure
PHP Version:5.3+

client_version / mysqli get_client_version() Function

Example

Return the MySQL client version as an integer: <?php echo mysqli_get_client_version(); ?>

Definition and Usage

The client_version / mysqli_get_client_version() function returns the MySQL client version as an integer. The MySQL client version is returned in the following format: main_version*10000 + minor_version*100 + sub_version. So, version 6.3.0 is returned as 60300.

Syntax

Object oriented style:

$conn -> client_version

Procedural style:

mysqli_get_client_version(connection)

Parameter Values

ParameterDescription
connectionOptional. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an integer that represents the MySQL client version
PHP Version:5+

get_connection_stats() Function

Example

Return stats about the client connection: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); print_r(mysqli_get_connection_stats($con)); ?>

Definition and Usage

The mysqli_get_connection_stats() function returns statistics about the client connection.

Syntax

Object oriented style:

$conn -> get_connection_stats()

Procedural style:

mysqli_get_connection_stats(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an array with connection stats on success. FALSE on failure
PHP Version:5.3+

host_info() / mysqli_get_host_info() Function

Example - Object Oriented style

Return the server hostname and connection type: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo $conn -> host_info(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The host_info() / mysqli_get_host_info() function returns the MySQL server hostname and the connection type.

Syntax

Object oriented style:

$conn -> host_info

Procedural style:

mysqli_get_host_info(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns a string that represents the MySQL server hostname and the connection type
PHP Version:5+

Example - Procedural style

Return the server hostname and connection type: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } echo mysqli_get_host_info($con); mysqli_close($con); ?>

protocol_version() / mysqli_get_proto_info() Function

Example - Object Oriented style

Return the MySQL protocol version: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo $conn -> protocol_version; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The mysqli_get_proto_info() function returns the MySQL protocol version.

Syntax

Object oriented style:

$conn -> protocol_version

Procedural style:

mysqli_get_proto_info(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an integer that represents the MySQL protocol version
PHP Version:5+

Example - Procedural style

Return the MySQL protocol version: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } echo mysqli_get_proto_info($con); mysqli_close($con); ?>

server_info / mysqli_get_server_info() Function

Example - Object Oriented style

Return the MySQL protocol version: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo $conn -> server_info; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The server_info / mysqli_get_server_info() function returns the MySQL server version.

Syntax

Object oriented style:

$conn -> server_info

Procedural style:

mysqli_get_server_info(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:A string that represents the MySQL server version
PHP Version:5+

Example - Procedural style

Return the MySQL server version: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } echo mysqli_get_server_info($con); mysqli_close($con); ?>

server_version / mysqli_get_server_version() Function

Example - Object Oriented style

Return the MySQL server version as an integer: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo $conn -> server_version; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The server_version / mysqli_get_server_version() function returns the MySQL server version as an integer. The server version is returned in the following format: main_version*10000 + minor_version*100 + sub_version. So, version 6.3.0 is returned as 60300.

Syntax

Object oriented style:

$conn -> server_version

Procedural style:

mysqli_get_server_version(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an integer that represents the MySQL server version
PHP Version:5+

Example - Procedural style

Return the MySQL server version as an integer: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } echo mysqli_get_server_version($con); mysqli_close($con); ?>

info() Function

Example - Object Oriented style

Return information about the last executed query: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform some queries $conn -> query("CREATE TABLE testPersons LIKE Persons"); $conn -> query("INSERT INTO testPersons SELECT * FROM Persons ORDER BY LastName"); echo $conn -> info; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The info / mysqli_info() function returns information about the last executed query. This function works with the following query types:

Syntax

Object oriented style:

$conn -> info

Procedural style:

mysqli_info(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:A string that contains additional info about the last executed query
PHP Version:5+

Example - Procedural style

Return information about the last executed query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform som queries mysqli_query($con, "CREATE TABLE testPersons LIKE Persons"); mysqli_query($con, "INSERT INTO testPersons SELECT * FROM Persons ORDER BY LastName"); echo mysqli_info($con); mysqli_close($con); ?>

init() Function

Example

Use of the mysqli_init() function: <?php $con = mysqli_init(); if (!$con) { die("mysqli_init failed"); } if (!mysqli_real_connect($con,"localhost","my_user","my_password","my_db")) { die("Connect Error: " . mysqli_connect_error()); } mysqli_close($con); ?>

Definition and Usage

The init / mysqli_init() function initializes MySQLi and returns an object to use with the mysqli_real_connect() function.

Syntax

Object oriented style:

$conn -> init

Procedural style:

mysqli_init()

Technical Details

Return Value:An object to use with the mysqli_real_connect() function
PHP Version:5+

insert_id() Function

Example - Object Oriented style

Assume that the "Persons" table has an auto-generated id field. Return the id from the last query: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $conn -> query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)"); // Print auto-generated id echo "New record has id: " . $conn -> insert_id; $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.

Syntax

Object oriented style:

$conn -> insert_id

Procedural style:

mysqli_insert_id(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:An integer that represents the value of the AUTO_INCREMENT field updated by the last query. Returns zero if there were no update or no AUTO_INCREMENT field
PHP Version:5+

Example - Procedural style

Assume that the "Persons" table has an auto-generated id field. Return the id from the last query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)"); // Print auto-generated id echo "New record has id: " . mysqli_insert_id($con); mysqli_close($con); ?>

kill() Function

Example - Object Oriented style

Return the thread ID for the current connection, then kill the connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Get thread id $t_id = $conn -> thread_id; // Kill connection $conn -> kill($t_id); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The kill() / mysqli_kill() function asks the server to kill a MySQL thread specified by the processid parameter.

Syntax

Object oriented style:

$conn -> kill(processid)

Procedural style:

mysqli_kill(connection, processid)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
processidRequired. The thread ID returned from thread_id()

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example

Return the thread ID for the current connection, then kill the connection: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Get thread id $t_id=mysqli_thread_id($con); // Kill connection mysqli_kill($con, $t_id); mysqli_close($con); ?>

more_results() Function

Example - Object Oriented style

Perform multiple queries against the database: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if ($conn -> multi_query($sql)) { do { // Store first result set if ($result = $conn -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($conn -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($conn -> next_result()); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The more_results() / mysqli_more_results() function checks if there are any more query results from a multi query.

Syntax

Object oriented style:

$conn -> more_results()

Procedural style:

mysqli_more_results(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:TRUE if there is one or more result sets available from multi_query(). FALSE otherwise
PHP Version:5+

Example - Procedural style

Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con)); } mysqli_close($con); ?>

multi_query() Function

Example - Object Oriented style

Perform multiple queries against the database: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if ($conn -> multi_query($sql)) { do { // Store first result set if ($result = $conn -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($conn -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($conn -> next_result()); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The multi_query() / mysqli_multi_query() function performs one or more queries against the database. The queries are separated with a semicolon.

Syntax

Object oriented style:

$conn -> multi_query(query)

Procedural style:

mysqli_multi_query(connection, query)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
queryRequired. Specifies one or more queries, separated with semicolon

Technical Details

Return Value:FALSE if the first query fails
PHP Version:5+

Example - Procedural style

Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con)); } mysqli_close($con); ?>

next_result() Function

Example - Object Oriented style

Perform multiple queries against the database: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if ($conn -> multi_query($sql)) { do { // Store first result set if ($result = $conn -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($conn -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($conn -> next_result()); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The next_result() / mysqli_next_result() function prepares the next result-set from multi_query().

Syntax

Object oriented style:

$conn -> next_result()

Procedural style:

mysqli_next_result(connection);

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con)); } mysqli_close($con); ?>

options() Function

Example - Object Oriented style

Set extra connect options: <?php $conn = mysqli_init(); if (!$conn) { die("mysqli_init failed"); } // Specify connection timeout $con -> options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); // Specify read options from named file instead of my.cnf $con -> options(MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); $con -> real_connect("localhost","my_user","my_password","my_db"); ?> Look at example of procedural style at the bottom.

Definition and Usage

The options() / mysqli_options() function is used to set extra connect options and affect behavior for a connection. Note: This function should be called after init() and before real_connect().

Syntax

Object oriented style:

$conn -> options(option, value)

Procedural style:

mysqli_options(connection, option, value)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
optionRequired. Specifies the option to set. Can be one of the following values:
  • MYSQLI_OPT_CONNECT_TIMEOUT - Set connection timeout in seconds
  • MYSQLI_OPT_LOCAL_INFILE - Enable/Disable use of LOAD LOCAL INFILE
  • MYSQLI_INIT_COMMAND - Set a command to execute after connecting to MySQL server
  • MYSQLI_READ_DEFAULT_FILE - Set read options from named file instead of my.cnf
  • MYSQLI_READ_DEFAULT_GROUP - Set read options from named group from my.cnf or the file specified in MYSQLI_READ_DEFAULT_FILE
  • MYSQLI_SERVER_PUBLIC_KEY - Set RSA public key file used with SHA-256 based authentication
  • MYSQLI_OPT_NET_CMD_BUFFER_SIZE - only for mysqlnd
  • MYSQLI_OPT_NET_READ_BUFFER_SIZE - only for mysqlnd
  • MYSQLI_OPT_INT_AND_FLOAT_NATIVE - only for mysqlnd
  • MYSQLI_OPT_SSL_VERIFY_SERVER_CERT - only for mysqlnd
valueRequired. Specifies the value for the option

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+
PHP Changelog:PHP 5.5: Added MYSQLI_SERVER_PUBLIC_KEY option PHP 5.3: Added MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options

Example - Procedural style

Set extra connect options: <?php $con = mysqli_init(); if (!$con) { die("mysqli_init failed"); } // Specify connection timeout mysqli_options($con, MYSQLI_OPT_CONNECT_TIMEOUT, 10); // Specify read options from named file instead of my.cnf mysqli_options($con, MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); mysqli_real_connect($con,"localhost","my_user","my_password","my_db"); ?>

ping() Function

Example - Object Oriented style

Ping a server connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Check if server is alive if ($conn -> ping()) { echo "Connection is ok!"; } else { echo "Error: ". $conn -> error); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The ping() / mysqli_ping() function pings a server connection, to check if the server is alive. It also tries to reconnect - if the connection has gone down.

Syntax

Object oriented style:

$conn -> ping()

Procedural style:

mysqli_ping(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Ping a server connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Check if server is alive if (mysqli_ping($con)) { echo "Connection is ok!"; } else { echo "Error: ". mysqli_error($con); } mysqli_close($con); ?>

poll() Function

Definition and Usage

The poll() / mysqli_poll() function is used to poll connections.

Syntax

Object oriented style:

$conn -> poll(read, error, reject, seconds, microseconds)

Procedural style:

mysqli_poll(read, error, reject, seconds, microseconds)

Parameter Values

ParameterDescription
readRequired. Specifies a list of connections to check for outstanding results that can be read
errorRequired. Specifies a list of connections on which an error occurred, like query failure or lost connection
rejectRequired. Specifies a list of connections rejected because no asynchronous query has been run on for which the function could poll results
secondsRequired. Specifies the maximum number of seconds to wait
microsecondsOptional. Specifies the maximum number of microseconds to wait. Default is 0

Technical Details

Return Value:The number of ready connections on success. FALSE on failure
PHP Version:5.3+

prepare() Function

Example - Object Oriented style

Prepare an SQL statement for execution: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // prepare and bind $stmt = $conn -> prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt -> bind_param("sss", $firstname, $lastname, $email); // set parameters and execute $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt -> execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt -> execute(); echo "New records created successfully"; $stmt -> close(); $conn -> close(); ?>

Definition and Usage

The prepare() / mysqli_prepare() function is used to prepare an SQL statement for execution.

Syntax

Object oriented style:

$conn -> prepare(query)

Procedural style:

mysqli_prepare(connection, query)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
queryRequired. Specifies an SQL query. Note: Do not add semicolon to the end of the query!

Technical Details

Return Value:A statement object on success. FALSE on failure
PHP Version:5+

query() Function

Example - Object Oriented style

Perform query against a database: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Perform query if ($result = $conn -> query("SELECT * FROM Persons")) { echo "Returned rows are: " . $result -> num_rows; // Free result set $result -> free_result(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The query() / mysqli_query() function performs a query against a database.

Syntax

Object oriented style:

$conn -> query(query, resultmode)

Procedural style:

mysqli_query(connection, query, resultmode)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
queryRequired. Specifies the SQL query string
resultmode Optional. A constant. Can be one of the following:
  • MYSQLI_USE_RESULT (Use this to retrieve large amount of data)
  • MYSQLI_STORE_RESULT (This is default)

Technical Details

Return Value:For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure
PHP Version:5+
PHP Changelog:PHP 5.3.0 added the ability for async queries

Example - Procedural style

Perform query against a database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform query if ($result = mysqli_query($con, "SELECT * FROM Persons")) { echo "Returned rows are: " . mysqli_num_rows($result); // Free result set mysqli_free_result($result); } mysqli_close($con); ?>

real_connect() Function

Example - Object Oriented style

Open a new connection to the MySQL server, with extra connect options: <?php $conn = mysqli_init(); if (!$conn) { die("mysqli_init failed"); } // Specify connection timeout $con -> options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); // Specify read options from named file instead of my.cnf $con -> options(MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); $con -> real_connect("localhost","my_user","my_password","my_db"); ?> Look at example of procedural style at the bottom.

Definition and Usage

The real_connect() / mysqli_real_connect() function opens a new connection to the MySQL server. This function differs from connect() in the following ways:

Syntax

Object oriented style:

$conn -> real_connect(host, username, password, dbname, port, socket, flag)

Procedural style:

mysqli_real_connect(connection, host, username, password, dbname, port, socket, flag)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
hostOptional. Specifies a host name or an IP address
usernameOptional. Specifies the MySQL username
passwordOptional. Specifies the MySQL password
dbnameOptional. Specifies the default database to be used
portOptional. Specifies the port number to attempt to connect to the MySQL server
socketOptional. Specifies the socket or named pipe to be used
flagOptional. Specifies different connection options. Possible values:
  • MYSQLI_CLIENT_COMPRESS - Use compression protocol
  • MYSQLI_CLIENT_FOUND_ROWS - Return number of matched rows (not affected rows)
  • MYSQLI_CLIENT_IGNORE_SPACE - Allow spaces after function names. Make function names reserved words
  • MYSQLI_CLIENT_INTERACTIVE - Allow interactive_timeout seconds of inactivity before closing connection
  • MYSQLI_CLIENT_SSL - Use SSL encryption
  • MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+
PHP Changelog:PHP 5.6: Added MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag

Example - Procedural style

Open a new connection to the MySQL server, with extra connect options: <?php $con = mysqli_init(); if (!$con) { die("mysqli_init failed"); } // Specify connection timeout mysqli_options($con, MYSQLI_OPT_CONNECT_TIMEOUT, 10); // Specify read options from named file instead of my.cnf mysqli_options($con, MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); mysqli_real_connect($con,"localhost","my_user","my_password","my_db"); ?>

real_escape_string() Function

Example - Object Oriented style

Escape special characters in strings: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Escape special characters, if any $firstname = $conn -> real_escape_string($_POST['firstname']); $lastname = $conn -> real_escape_string($_POST['lastname']); $age = $conn -> real_escape_string($_POST['age']); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')"; if (!$conn -> query($sql)) { printf("%d Row inserted.\n", $conn->affected_rows); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement. Assume we have the following code: <?php $lastname = "D'Ore"; $sql="INSERT INTO Persons (LastName) VALUES ('$lastname')"; // This query will fail, cause we didn't escape $lastname if (!$conn -> query($sql)) { printf("%d Row inserted.\n", $conn->affected_rows); } ?>

Syntax

Object oriented style:

$conn -> real_escape_string(escapestring)

Procedural style:

mysqli_real_escape_string(connection, escapestring)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
escapestringRequired. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Technical Details

Return Value:Returns the escaped string
PHP Version:5+

Example - Procedural style

Escape special characters in strings: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Escape special characters, if any $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']); $age = mysqli_real_escape_string($con, $_POST['age']); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')"; if (!mysqli_query($con, $sql)) { printf("%d Row inserted.\n", mysqli_affected_rows($con)); } mysqli_close($con); ?>

real_query() Function

Example - Object Oriented style

Execute a single SQL query. Store the result with store_result(): <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $conn -> real_query("SELECT * FROM Persons"); if ($conn -> field_count) { $result = $conn -> store_result(); $row = $result -> fetch_row(); // Free result set $result -> free_result(); } $conn -> close(); ?>

Definition and Usage

The real_query() / mysqli_real_query() function executes a single SQL query. The result can be retrieved or stored with the store_result() or use_result() functions.

Syntax

Object oriented style:

$conn -> real_query(query)

Procedural style:

mysqli_real_query(connection, query)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
queryRequired. The query to be executed

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

reap_async_query() Function

Definition and Usage

The reap_async_query() / mysqli_reap_async_query() function returns result from an async SQL query.

Syntax

Object oriented style:

$conn -> reap_async_query()

Procedural style:

mysqli_reap_async_query(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:mysqli_result on success. FALSE on failure
PHP Version:5.3+

refresh() Function

❮ PHP mysqli Reference

Definition and Usage

The refresh() / mysqli_refresh() function refreshes/flushes tables or caches, or resets the replication server information.

Syntax

Object oriented style:

$conn -> refresh(options)

Procedural style:

mysqli_refresh(connection, options)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
optionsThe options to refresh. Can be one of more of the following (separated by OR):
  • MYSQLI_REFRESH_GRANT - Refreshes the grant tables
  • MYSQLI_REFRESH_LOG - Flushes the logs
  • MYSQLI_REFRESH_TABLES - Flushes the table cache
  • MYSQLI_REFRESH_HOSTS - Flushes the host cache
  • MYSQLI_REFRESH_STATUS - Resets the status variables
  • MYSQLI_REFRESH_THREADS - Flushes the thread cache
  • MYSQLI_REFRESH_SLAVE - Resets the master server info, and restarts the slave
  • MYSQLI_REFRESH_MASTER - Removes the binary log files in the binary log index, and truncates the index file

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5.3+

rollback() Function

❮ PHP mysqli Reference

Example - Object Oriented style

Turn off auto-committing, make some queries, commit the queries, then roll back the current transaction: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Turn autocommit off $conn -> autocommit(FALSE); // Insert some values $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $conn -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn -> commit()) { echo "Commit transaction failed"; exit(); } // Rollback transaction $conn -> rollback(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The rollback() / mysqli_rollback() function rolls back the current transaction for the specified database connection. Tip: Also look at the commit() function, which commits the current transaction, and the autocommit() function, which turns on or off auto-committing database modifications.

Syntax

Object oriented style:

$conn -> rollback(flags, name)

Procedural style:

mysqli_rollback(connection, flags, name)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
flagsOptional. A constant:
  • MYSQLI_TRANS_COR_AND_CHAIN - Appends "AND CHAIN"
  • MYSQLI_TRANS_COR_AND_NO_CHAIN - Appends "AND NO CHAIN"
  • MYSQLI_TRANS_COR_RELEASE - Appends "RELEASE"
  • MYSQLI_TRANS_COR_NO_RELEASE - Appends "NO RELEASE"
nameOptional. ROLLBACK/*name*/ is executed if this parameter is specified

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+
PHP Changelog:PHP 5.5: Added the flags and name parameters

Example - Procedural style

Turn off auto-committing, make some queries, commit the queries, then roll back the current transaction: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Turn autocommit off mysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transaction if (!$conn_commit($con)) { echo "Commit transaction failed"; exit(); } // Rollback transaction mysqli_rollback($con); // Close connection mysqli_close($con); ?>

select_db() Function

Example - Object Oriented style

Change the default database for the connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Return name of current default database if ($result = $conn -> query("SELECT DATABASE()")) { $row = $result -> fetch_row(); echo "Default database is " . $row[0]; $result -> close(); } // Change db to "test" db $conn -> select_db("test"); // Return name of current default database if ($result = $conn -> query("SELECT DATABASE()")) { $row = $result -> fetch_row(); echo "Default database is " . $row[0]; $result -> close(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The select_db() / mysqli_select_db() function is used to change the default database for the connection.

Syntax

Object oriented style:

$conn -> select_db(name)

Procedural style:

mysqli_select_db(connection, name)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
nameRequired. Specifies the database name

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

Example - Procedural style

Change the default database for the connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Return name of current default database if ($result = mysqli_query($con, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); echo "Default database is " . $row[0]; mysqli_free_result($result); } // Change db to "test" db mysqli_select_db($con, "test"); // Return name of current default database if ($result = mysqli_query($con, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); echo "Default database is " . $row[0]; mysqli_free_result($result); } // Close connection mysqli_close($con); ?>

set_charset() Function

Example - Object Oriented style

Change the default client character set: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo "Initial character set is: " . $conn -> character_set_name(); // Change character set to utf8 $conn -> set_charset("utf8"); echo "Current character set is: " . $conn -> character_set_name(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The set_charset() / mysqli_set_charset() function specifies the default character set to be used when sending data to and from the database server. Note: For this function to work on a Windows platform, you need MySQL client library 4.1.11 or above (for MySQL 5.0, you need 5.0.6 or above).

Syntax

Object oriented style:

$conn -> set_charset(charset)

Procedural style:

mysqli_set_charset(connection, charset)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
charsetRequired. Specifies the default character set

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5.0.5+

Example - Procedural style

Change the default client character set: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } echo "Initial character set is: " . mysqli_character_set_name($con); // Change character set to utf8 mysqli_set_charset($con,"utf8"); echo "Current character set is: " . mysqli_character_set_name($con); mysqli_close($con); ?>

set_local_infile_handler() Function

Definition and Usage

The set_local_infile_handler() / mysqli_set_local_infile_handler() function sets a callback function for LOAD DATA LOCAL INFILE command. The callback functions tasks are to read input from the file specified in LOAD DATA LOCAL INFILE, and to reformat it into the format understood by LOAD DATA INFILE. The returned data must match the format specified in the LOAD DATA.

Syntax

Object oriented style:

$conn -> set_local_infile_handler(read_file)

Procedural style:

mysqli_set_local_infile_handler(read_file)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
read_funcRequired. Specifies a callback function or objext that can take the following params: 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 &erromsg - If an error occurs you can store an error message in here

Technical Details

Return Value:TRUE on success. FALSE on failure
PHP Version:5+

sqlstate() Function

❮ PHP mysqli Reference

Example - Object Oriented style

Return the SQLSTATE error code for the last error: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Table Persons already exists, so we should get an error $sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)" if (!$conn -> query($sql)) { echo "SQLSTATE error: ". $conn -> sqlstate; } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The sqlstate / mysqli_sqlstate() function returns the SQLSTATE error code for the last error. The error code consists of five characters. "00000" indicates no error. The values are specified by ANSI SQL and ODBC.

Syntax

Object oriented style:

$conn -> sqlstate

Procedural style:

mysqli_sqlstate(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:A string containing the SQLSTATE error code for the last error
PHP Version:5+

Example - Procedural state

Return the SQLSTATE error code for the last error: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Table Persons already exists, so we should get an error $sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)" if (!mysqli_query($con, $sql)) { echo "SQLSTATE error: ". mysqli_sqlstate($con); } // Close connection mysqli_close($con); ?>

ssl_set() Function

Example - Object Oriented style

Create an SSL connection: <?php $conn = mysqli_init(); if (!$conn) { die("mysqli_init failed"); } $conn -> ssl_set("key.pem", "cert.pem", "cacert.pem", NULL, NULL); if (!$conn -> real_connect("localhost","my_user","my_password","my_db")) { die("Connect Error: " . mysqli_connect_error()); } // Some queries... $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The ssl_set() / mysqli_ssl_set() function is used to establish secure connections using SSL. However, this function does nothing unless OpenSSL support is enabled. Note: This function must be called before real_connect(). Note: MySQL Native Driver does not support SSL before PHP 5.3.3. MySQL Native Driver is enabled by default on Microsoft Windows from PHP 5.3+.

Syntax

Object oriented style:

$conn -> ssl_set(key, cert, ca, capath, cipher)

Procedural style:

mysqli_ssl_set(connection, key, cert, ca, capath, cipher)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use
keyRequired. Specifies the path name to the key file
certRequired. Specifies the path name to the certificate file
caRequired. Specifies the path name to the certificate authority file
capathRequired. Specifies the pathname to a directory that contains trusted SSL CA certificates in PEM format
cipherRequired. Specifies a list of allowable ciphers to use for SSL encryption

Technical Details

Return Value:Always TRUE. If SSL setup is incorrect, real_connect() will return an error when you try to connect
PHP Version:5+

Example - Procedural style

Create an SSL connection: <?php $con = mysqli_init(); if (!$con) { die("mysqli_init failed"); } mysqli_ssl_set($con, "key.pem", "cert.pem", "cacert.pem", NULL, NULL); if (!mysqli_real_connect($con, "localhost", "my_user", "my_password", "my_db")) { die("Connect Error: " . mysqli_connect_error()); } // Some queries... mysqli_close($con); ?>

stat() Function

Example - Object Oriented style

Return the current system status: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } echo "System status: ". $conn -> stat(); $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The stat() / mysqli_stat() function returns the current system status.

Syntax

Object oriented style:

$conn -> stat()

Procedural style:

mysqli_stat(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:A string that describes the server status. FALSE on error
PHP Version:5+

Example - Procedural style

Return the current system status: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } echo "System status: ". mysqli_stat($con); mysqli_close($con); ?>

stmt_init() Function

Example - Object Oriented style

Initialize a statement and return an object to use with stmt_prepare(): <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $city="Sandnes"; // Create a prepared statement $stmt = $conn -> stmt_init(); if ($stmt -> prepare("SELECT District FROM City WHERE Name=?")) { // Bind parameters $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", $city, $district); // Close statement $stmt -> close(); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The stmt_init() / mysqli_stmt_init() function initializes a statement and returns an object suitable for mysqli_stmt_prepare().

Syntax

Object oriented style:

$conn -> stmt_init()

Procedural style:

mysqli_stmt_init(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an object
PHP Version:5+

Example - Procedural style

Initialize a statement and return an object to use with mysqli_stmt_prepare(): <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } $city="Sandnes"; // Create a prepared statement $stmt = mysqli_stmt_init($con); if (mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?")) { // Bind parameters 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", $city, $district); // Close statement mysqli_stmt_close($stmt); } mysqli_close($con); ?>

mysqli_thread_id() Function

Example - Object Oriented style

Return the thread ID for the current connection, then kill the connection: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } // Get thread id $thread_id = $conn -> thread_id; // Kill connection $conn -> kill($thread_id); ?> Look at example of procedural style at the bottom.

Definition and Usage

The thread_id() / mysqli_thread_id() function returns the thread ID for the current connection. The connection can then be killed with the kill() function. Note: If the connection is broken and you reconnect, the thread ID will be changed. Therefore; get the thread ID only when you need it.

Syntax

Object oriented style:

$conn -> thread_id()

Procedural style:

mysqli_thread_id(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns the thread ID for the current connection
PHP Version:5+

Example - Procedural style

Return the thread ID for the current connection, then kill the connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // Get thread id $thread_id = mysqli_thread_id($con); // Kill connection mysqli_kill($con, $thread_id); ?>

mysqli_thread_safe() Function

Definition and Usage

The mysqli_thread_safe() function returns whether the client library is compiled as thread-safe.

Syntax

mysqli_thread_safe()

Technical Details

Return Value:TRUE if the client library is thread-safe. FALSE otherwise
PHP Version:5+

use_result() Function

Example - Object Oriented style

Initiates the retrieval of a result-set from the last query executed: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if ($conn -> multi_query($sql)) { do { // Store first result set if ($result = $conn -> use_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> close(); } // if there are more result-sets, the print a divider if ($conn -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($conn -> next_result()); } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The use_result() / mysqli_use_result() function initiates the retrieval of a result-set from the last query executed.

Syntax

Object oriented style:

$conn -> use_result()

Procedural style:

mysqli_use_result(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:Returns an unbuffered result object. FALSE on error
PHP Version:5+

Example - Procedural style

Initiates the retrieval of a result-set from the last query executed: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_use_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con)); } mysqli_close($con); ?>

warning_count() Function

Example - Object Oriented style

Return the number of warnings from the last query: <?php $conn = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($conn -> connect_errno) { echo "Failed to connect to MySQL: " . $conn -> connect_error; exit(); } $conn -> query("CREATE TABLE myPersons LIKE Persons"); $sql = "INSERT INTO myPersons (FirstName) VALUES( 'Hdghfhjgjtjyjn.,,øæløjkghfjbmbngfgffdhfhjgjgkjhlkhlkjljljlkjkljlkjkljkljlkj')"; $conn -> query($sql); if ($conn -> warning_count) { if ($result = $conn -> query("SHOW WARNINGS")) { $row = $result -> fetch_row(); printf("%s (%d): %s\n", $row[0], $row[1], $row[2]); $result -> close(); } } $conn -> close(); ?> Look at example of procedural style at the bottom.

Definition and Usage

The warning_count / mysqli_warning_count() function returns the number of warnings from the last query.

Syntax

Object oriented style:

$conn -> warning_count

Procedural style:

mysqli_warning_count(connection)

Parameter Values

ParameterDescription
connectionRequired. Specifies the MySQL connection to use

Technical Details

Return Value:The number of warnings from the last query. 0 if no warnings
PHP Version:5+

Example - Procedural style

Return the number of warnings from the last query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } mysqli_query($con, "CREATE TABLE myPersons LIKE Persons"); $sql = "INSERT INTO myPersons (FirstName) VALUES( 'Hdghfhjgjtjyjn.,,øæløjkghfjbmbngfgffdhfhjgjgkjhlkhlkjljljlkjkljlkjkljkljlkj')"; mysqli_query($con, $sql); if (mysqli_warning_count($con)) { if ($result = mysqli_query($con, "SHOW WARNINGS")) { $row = mysql_fetch_row($result); printf("%s (%d): %s\n", $row[0], $row[1], $row[2]); mysqli_free_result($result); } } mysqli_close($con); ?>