< Day Day Up > |
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 . 3.2.1 Alternative Fetch MethodsIf 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 $row[0] . "\n"; } // Alternative syntax: while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) { print $row[0] . "\n"; } // Alternative associative array syntax: while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { print $row['username'] . "\n"; } // Both numeric and associative: while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) { print $row[0] . "\n"; print $row['username'] . "\n"; } // Fetch as "object" while ($row = mysqli_fetch_object($result)) { print $row->username . "\n"; } |
< Day Day Up > |