Articles in MySQL Category

MySQLi Procedural Functions

MySQL Improved Extension (MySQLi) provides a Procedural Interface as well as an Object Oriented Interface. In this article we will look into some of the common MySQLi Procedural functions.


This function is used for connecting to MySQL. Before doing any database operation, you need to connect to MySQL. On success, this function returns a link identifier that you can use in other MySQLi functions. On failure, it will throw an error.

Following is how a user named robin with password robin123 need to connect to a database called company_db at localhost. User robin should have privileges to access company_db.

$link = mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

If your MySQL port is different from default one (3308), you need to give the port number as the fifth parameter.

$link = mysqli_connect('localhost', 'robin', 'robin123', 'company_db', '3800');


mysqli_connect() throws an error at failure and mysqli_connect_error() stores the error in last call to mysqli_connect(). If there is no error, it returns NULL.

To try out a mysqli_connect() error, stop MySQL server and call to mysqli_connect(). If you have enabled PHP errors, you would see an error that includes information like below. mysqli_connect_error() would returns the same message.

Can’t connect to MySQL server on ‘localhost’

In practice, it’s not good to show error messages like these to the users of your PHP application (They may contain sensitive data and they can look too technical).

Therefore you can use error suspension operator in front of mysqli_connect() to stop it throwing errors and use mysqli_connect_error() to log the error for troubleshooting like below.


$link = @mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

if (mysqli_connect_error()) {
	$logMessage = 'MySQL Error: ' . mysqli_connect_error();
	// Call your logger here.
	die('Could not connect to the database');

// Rest of the code goes here



To change the database in use, you can use mysqli_select_db(). For an example think that user robin also has privileges for a database called company_new_db then you can change the database like below.

$link = @mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

// Operations on 'company_db'

mysqli_select_db($link, 'company_new_db');

// Operations on 'company_new_db'

You will only need this function if your PHP application deals with more than one database.


You can use this function to close a MySQL connection. It returns TRUE on success and FALSE on failure.

$link = @mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

// MySQL operations goes here.


PHP will close open connections and release resources at the end of your PHP script. But it’s a good practice to explicitly use mysqli_close() at the end of MySQL operations to release resources immediately.


This is the function used for executing MySQL queries. It returns FALSE on failure. For SELECT, SHOW, DESCRIBE and EXPLAIN queries (where there is an output), it returns a MySQL result set (resource) which can be used in functions like mysqli_fetch_array().

For all other queries like INSERT, UPDATE and DELETE, it returns TRUE on success.

$link = @mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

$query = "SELECT * FROM employee";

if (mysqli_query($link, $query)) {
    // Iterate and display result
} else {
    // Show error



This function is used for reading data from a MySQL result set (returned by a mysqli_query()). It reads and returns one row of data as an array and then moves the pointer to next row. When there are no more rows to return, it returns NULL. Because of this behavior, it’s often used with a While Loop as below.

while ($row = mysqli_fetch_array($result)) {
/* Till there is data, $row will be an array.
 * At the end, $row becomes NULL ending the loop.

Let’s assume following employee table is available in our company_db database.

employee MySQL Table

Below is how we would fetch ID, First Name and Last Name from this table.


$link = @mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

$query = "SELECT `id`, `first_name`, `last_name` FROM `employee`";

$result = mysqli_query($link, $query);

while ($row = mysqli_fetch_array($result)) {
    echo $row[0] . ': ' . $row[1] . ' ' . $row[2];
    echo '<br />';




When you run, above code will output following content in the web browser.

1: Robin Jackman
2: Taylor Edward

In addition to an Indexed array, mysqli_fetch_array() also returns an Associated array where keys are corresponding column names of the table. So, following code segment will produce same output.

while ($row = mysqli_fetch_array($result)) {
    echo $row['id'] . ': ' . $row['first_name'] . ' ' . $row['last_name'];
    echo '<br />';

You can limit which array to return as below.

// Returns only an Indexed array
mysqli_fetch_array($result, MYSQLI_NUM);

// Returns only an Associated array
mysqli_fetch_array($result, MYSQLI_ASSOC);

PHP provides two functions that produce same results as you get by passing constants to mysqli_fetch_array().

// Same as mysqli_fetch_array($result, MYSQLI_NUM)

// Same as mysqli_fetch_array($result, MYSQLI_ASSOC)


Immediately after using a result set, you can free the memory used for it as below.



mysqli_num_rows() returns the number of rows in a result set. Using it, you can take a different action when the result set is empty.

if (mysqli_num_rows($result) > 0) {
    // Proceed with the $result
} else {
    // Show an error message


This function provides information on last MySQL query executed. For INSERT, UPDATE, REPLACE and DELETE, it provides number of rows affected. For SELECT, it returns number of rows in the result set as mysqli_num_rows().

For an example, following is an UPDATE query to update the last name of Taylor in employee table. Provided that id field is unique we know that only one row should be affected from this query.

$query = "UPDATE `employee` SET `last_name` = 'Adams' WHERE `id` = 2";

mysqli_query($link, $query);

if (mysqli_affected_rows($link) == 1) {
    // Rest of the code
} else {
    // Show an error message


If there was an error in last MySQL query, this function will return the error. If there was no error, it would return an empty string.

if (!mysqli_query($link, $query)) {
	$logMessage = 'MySQL Error: ' . mysqli_error($link);
	// Call your logger here.
    die('There was an error in the query');


Some characters like single quote has special meaning in SQL statements. For an example, single quote is used for wrapping strings. So, if your SQL statement contains these special characters, you need to escape them via mysqli_real_escape_string() before sending the query to mysqli_query().

Following call to mysqli_query() returns FALSE since the single quote in O’Neil hasn’t been escaped.

$query = "SELECT `id` FROM `employee` WHERE `last_name` = 'O'Neil'";
mysqli_query($link, $query);

Following call to mysqli_query() would return a proper result set (provided that an employee exists with last name O’Neil) since the name is first escaped via mysqli_real_escape_string().

$name = mysqli_real_escape_string($link, "O'Neil");
$query = "SELECT `id` FROM `employee` WHERE `last_name` = '$name'";
mysqli_query($link, $query);

If your SQL statements are built based on user inputs like below, it’s always a good idea to use this function since user input may contain special characters.

$lastName = mysqli_real_escape_string($link, $_POST['lastName']);
$query = "SELECT `id` FROM `employee` WHERE `last_name` = '$lastName'";
mysqli_query($link, $query);

Another fact is user inputs may contain attempts for security breaches by having special characters to execute malicious actions (SQL injection). Escaping user input will reduce the risk of SQL injection.

Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.