PHP MySQL to MySQLi Changes

From Leo's Notes
Last edited on 13 January 2016, at 19:49.

With PHP 7 being released, the old MySQL functions such as mysql_connect have been removed. There are a couple ways to connect to MySQL with PHP 7 or higher: mysqli or the PDO driver.

The simplest way to fix old scripts is to make use of the mysqli alias/facade functions that provide a familiar procedural interface.

Function Name Changes

The procedural function wrappers provided by MySQLi is mostly the same as the deprecated functions. The parameters are also similar with the exception that the MySQL connection link must be passed as the first parameter and is not optional.

PHP 5 or lower PHP 7 or higher
mysql_affected_rows mysqli_affected_rows($link)
mysql_close mysqli_close($link)
mysql_data_seek mysqli_data_seek($result, $offset)
mysql_errno mysqli_errno($link)
mysql_error mysqli_error($link)
mysql_fetch_array mysqli_fetch_array($result, $type)
mysql_fetch_assoc mysqli_fetch_assoc($result)
mysql_fetch_lengths mysqli_fetch_lengths($result)
mysql_fetch_object mysqli_fetch_object($result, $class, $params)
mysql_fetch_row mysqli_fetch_row($result)
mysql_field_seek mysqli_field_seek($result, $number)
mysql_free_result mysqli_free_result(result)
mysql_get_client_info mysqli_get_client_info($link)
mysql_get_host_info mysqli_get_host_info($link)
mysql_get_proto_info mysqli_get_proto_info($link)
mysql_get_server_info mysqli_get_server_info($link)
mysql_info mysqli_info($link)
mysql_insert_id mysqli_insert_id($link)
mysql_num_rows mysqli_num_rows($result)
mysql_ping mysqli_ping($link)
mysql_query mysqli_query($link, $query)
mysql_real_escape_string mysqli_real_escape_string($link, $string)
mysql_select_db mysqli_select_db($link, $database)
mysql_set_charset mysqli_set_charset($link, $charset)
mysql_stat mysqli_stat($link)
mysql_thread_id mysqli_thread_id($link)

Example

PHP 5 or lower PHP 7 or higher
$db = mysql_connect('host', 'user', 'password') or die (mysql_error());
mysql_select_db('database', $db);

$result = mysql_query('SELECT * FROM table', $db);

while ($data = mysql_fetch_array($result)) {
  echo $data['field1'] . "\n";
}

mysql_close($db);
$db = mysqli_connect('host', 'user', 'password', 'database') or die (mysqli_connect_error($db));

$result = mysql_query($db, 'SELECT * FROM table');

while ($data = mysqli_fetch_array($result)) {
  echo $data['field1'] . "\n";
}

mysqli_close($db);