mysql and mysqli

These are two alternative ways by which you can access a mySQL database from PHP. The mysql functions have been available in PHP for a long time and provide a procedural style interface. The mysqli class (and functions) are a more recent and far more powerful interface as it not only provides an object oriented way to interface with databases but it also provides other additional functionality that makes it the more flexible and more secure alternative.

Let's start by considering how to connect to a database from PHP using each of these two interfaces. First, heres the code necessary to connect to a database called 'foo' using the mysql interface. Note that the connect call in mysql makes no provision for specifying a default database and so we need to connect to the database server first and then specify the database as a separate call.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());

The mysqli interface uses much simpler code to connect to the database as it allows the default database to be specified in the same command that connects to the database server.

$mysqli = new mysqli("localhost", "mysql_user", "mysql_password", "foo");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());

With both of these the connection to the database server remains open until either the cuurrent script finishes running or the appropriate close function is called. Since in most cases the script will run relatively quickly and will end very soon after all of the database accesses are completed there will seldom be a situation where it is worth explicitly specifying the close function.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow