MySQLi Procedural Functions
MySQL Improved Extension (MySQLi) provides a Procedural Interface as well as an Object Oriented Interface. In this chapter, we will look into some of the common MySQLi Procedural functions.
mysqli_connect()
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 anuj with password anuj123 needs to connect to a database called
company_db at localhost. User robin should have privileges to access company_db.
1 |
$link = mysqli_connect('localhost', 'anuj', 'anuj123', 'company_db'); |
If your MySQL port is different from the default one (3306), you need to give the port number as the fifth parameter.
1 |
$link = mysqli_connect('localhost', 'anuj', 'anuj123', 'company_db', '3800'); |
mysqli_connect_error()
mysqli_connect() throws an error at failure, and mysqli_connect_error() stores the error of the
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 mysqli_connect(). If you have
enabled PHP errors, you would see an error that includes information like below. mysqli_connect_-
error() would return 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 the 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.
1 2 3 4 5 6 7 8 9 |
<?php $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 ?> |
mysqli_select_db()
To change the database in use, you can use mysqli_select_db(). For example assume that user anuj
also has privileges for a database called company_new_db; then you can change the database as
below.
1 2 3 4 |
$link = @mysqli_connect('localhost', 'anuj', 'anuj123', '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.
mysqli_close()
You can use this function to close a MySQL connection. It returns TRUE on success and FALSE on
failure.
1 2 3 |
$link = @mysqli_connect('localhost', 'anuj', 'anuj123', 'company_db'); // MySQL operations goes here. mysqli_close($link); |
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.
mysqli_query()
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 other queries, like INSERT, UPDATE, and DELETE, it returns TRUE on success.
1 2 3 4 5 6 7 8 |
$link = @mysqli_connect('localhost', 'anuj', 'anuj123', 'company_db'); $query = "SELECT * FROM employee"; if (mysqli_query($link, $query)) { // Iterate and display result } else { // Show error } mysqli_close($link); |
mysqli_fetch_array()
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 the 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.
1 2 3 4 5 |
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 the following employee table is available in our company_db database.
id | first_name | last_name | age | joined_date | records |
1 | Anuj | Kumar | 25 | 2017-03-17 | 2 |
2 | John | Doe | 27 | 2018-01-11 | 1 |
Below is how we would fetch ID, First Name, and Last Name from this table.
1 2 3 4 5 6 7 8 9 10 11 |
<?php $link = @mysqli_connect('localhost', 'anuj', 'anuj123', '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 />'; } mysqli_free_result($result); mysqli_close($link); ?> |
When you run it, the code above will output the following content in the web browser.
1: Anuj kumar
2: John Doe
In addition to an Indexed array, mysqli_fetch_array() also returns an Associated array where keys
are the corresponding column names of the table. So, the following code segment will produce the
same output.
1 2 3 4 |
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.
1 2 3 4 |
// 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 the same results as you would get by passing constants to
mysqli_fetch_array().
1 2 3 4 |
// Same as mysqli_fetch_array($result, MYSQLI_NUM) mysqli_fetch_row($result); // Same as mysqli_fetch_array($result, MYSQLI_ASSOC) mysqli_fetch_assoc($result); |
mysqli_free_result()
Immediately after using a result set, you can free the memory used for it as below.
1 |
mysqli_free_result($result); |
mysqli_num_rows()
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.
1 2 3 4 5 |
if (mysqli_num_rows($result) > 0) { // Proceed with the $result } else { // Show an error message } |
mysqli_affected_rows()
This function provides information on the 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 example, the following is an UPDATE query to update the last name of Taylor in employee
table. Provided that the id field is unique, we know that only one row would be affected from this
query.
1 2 3 4 5 6 7 |
$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 } |
mysqli_error()
If there was an error in the last MySQL query, this function will return the error. If there was no
error, it would return an empty string.
1 2 3 4 5 |
if (!mysqli_query($link, $query)) { $logMessage = 'MySQL Error: ' . mysqli_error($link); // Call your logger here. die('There was an error in the query'); } |
mysqli_real_escape_string()
Some characters like single quote have special meanings in SQL statements. For example, the 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().
The following call to mysqli_query() returns FALSE, since the single quote in O’Neil hasn’t been
escaped.
1 2 |
$query = "SELECT `id` FROM `employee` WHERE `last_name` = 'O'Neil'"; mysqli_query($link, $query); |
The 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().
1 2 3 |
$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 those below, it’s always a good idea to use
this function, since user input may contain special characters.
1 2 3 |
$lastName = mysqli_real_escape_string($link, $_POST['lastName']); $query = "SELECT `id` FROM `employee` WHERE `last_name` = '$lastName'"; mysqli_query($link, $query); |
User inputs may contain attempts for security breaches by having special characters execute
malicious actions (SQL injection). Escaping user input will reduce the risk of SQL injection.