O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Procedural Interface

The procedural interface to mysqli is largely identical to the older mysql extension. Except, of course, all the function names begin with mysqli instead of mysql:

$db = mysqli_connect($server, $user, $password) or 
    die("Could not connect: " . mysqli_error( ));
mysqli_select_db($db, "users");

$result = mysqli_query($db, "SELECT username FROM users");

while ($row = mysqli_fetch_assoc($result)) {
    print $row['username'] . "\n";
}

mysqli_free_result($result);
mysqli_close($db);

This code connects to a MySQL database, selects the users table, makes a query, and then fetches each row as an associative array. These functions all behave the same as their mysql counterparts, except that the mysqli functions require a database handle as their first argument instead of optionally allowing one as the final argument. Section 3.10 covers all the API changes in detail.

There is also a minor change in mysqli_fetch_array( ). When there are no additional rows, it returns NULL. The original extension returns false. This difference won’t affect code like that shown here, where it only assigns the result to a variable, but if you use != = to do a strict check against false, you must now check against NULL.

Alternative Fetch Methods

If you prefer different MySQL fetch methods, they’re also in mysqli. Given the same query of SELECT username FROM users, these example functions all print the same results:

// Fetch numeric arrays: while ($row = mysqli_fetch_row($result)) { print ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required