Skip to Main Content
Upgrading to PHP 5
book

Upgrading to PHP 5

by Adam Trachtenberg
July 2004
Intermediate to advanced content levelIntermediate to advanced
350 pages
10h 9m
English
O'Reilly Media, Inc.
Content preview from Upgrading to PHP 5

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith
Pro PHP Programming

Pro PHP Programming

Peter MacIntyre, Brian Danchilla, Mladen Gogala
Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596006365Supplemental ContentCatalog PageErrata