What you need to know about updating to mysqli

PHP functions starting with mysql_ are deprecated -- they are currently supported, but they will eventually be phased out.  mysqli_ functions (the i is for "improved") take advantage of various features of MySQL from Version 4.1.3 and later (we're up to 5.5 at time of writing).  We won't be covering those features, but it's good to know what you're learning won't be deprecated, or not soon.

Logging in to the database

Connection is done by one command:  $mysqli_link = new mysqli (...); with the "..." replaced by relevant logging in information, as shown below.  On a FALSE result, we get an error-report string with mysqli_connect_error () and kill PHP.

This should be put into a PHP file and loaded at the start of any PHP file that uses the database.

//These will be used throughout -- at least $mysqli_link will
$db_hostname='localhost';
$db_database='<your database name here>';
$db_username='root';
$db_password='<your password here>';

//Database connection
$mysqli_link = new mysqli ($db_hostname, $db_username, $db_password, $db_database);
if (! $mysqli_link)
    die ("Database connection failed: ".mysqli_connect_error()."<br>");

How the function calls differ

At our level, here's what you need to know to go from Nixon's mysql calls to mysqli calls.

  1. Replace mysql_ with mysqli_ throughout.  (!)
  2. mysqli_query, mysqli_insert_id, mysqli_error, and mysqli_real_escape_string now take the $mysql_link you created above as the first argument.  In addition, mysql_query had an optional second argument, which was the database connection, used if we might be changing that; that is no longer needed.
  3. mysqli_num_rows and mysqli_fetch_row, however, do not change their arguments.
  4. mysqli_query -- like mysql_query -- returns a resource containing useful (we hope) information if the query is a SELECT, SHOW, DESCRIBE, or EXPLAIN and is successful.*  The difference is that if it's a resource, we're now expected to delete the resource thus:

    mysqli_free_result ($queryResult);

    So normally, this rule will apply:

How common PHP MySQL function calls change from mysql to mysqli:  a short guide

mysql_query ($query [, $dbName]) mysqli_query($mysqli_link, $query)
mysql_insert_id () mysqli_insert_id ($mysqli_link)
mysql_num_rows ($queryResult) mysqli_num_rows ($queryResult)
mysql_fetch_row ($queryResult) mysqli_fetch_row ($queryResult)
mysql_error() mysqli_error($mysqli_link)
mysql_real_escape_string ($string) mysqli_real_escape_string ($mysqli_link, $string)

*It returns FALSE for unsuccessful queries and TRUE for successful queries of other types.