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 ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.