MySQLi: Handling MySQL databases in PHP

MySQLi (MySQL Improved) is the new driver which is used to connect to MySQL databases exclusively in PHP. This improved extension has a lot of advantages over the old mysql_query statements. You can take advantages of the new functionality when you upgrade from mysql to mysqli. One of the major advantage you can get is the ability to use the object oriented style to handle databases. It makes the coding simpler to maintain.

Connecting to a MySql database using MySQLi

You just use the new mysqli statement to make a database connection. Here’s how you do it:

The above code is good for a simple connection. But if you want to display errors when they occur, add some additional lines as:

Query Database

To perform a simple query on the database just try the following:

$result = $db->query(“SELECT * FROM table”) or die($db->error);

If the queries take in input from users, then it should be secured. We do it my using $db->real_escape_string or the prepare statements. After preparing the statements, you will have to bind it.

Here’s how you use the prepare statement for MySQLi

Using the Query Results

You can, of course, add additional lines to the query to make sure to see whether or not you get results and to output the results using a while or a for each loop.


Instead of fetch_assoc() you can also use:
fetch_row(): To get the query results in a numbered array.
fetch_object(): To get the results of the query in the form of an object.
fetch_array(): Can get the results in numbered as well as associative arrays.

Freeing Resoures at The End

At the end, you can free the resources by using:

Preparing, Binding and Querying Example

Database Table

Database Table

You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers