How to Convert mysqli Functions to mysql Functions

By Steve Suehring, Janet Valade

You’re probably using PHP 5 or later with the mysqli functions to interact with MySQL 5.0 or 5.1. If you’re using PHP 4, the mysqli functions aren’t available. Instead, you use the mysql functions, even with later versions of MySQL.

The mysql functions can communicate with the later versions of MySQL, but they can’t access some of the new features added in the later versions of MySQL. The mysql functions are activated automatically in PHP 4.

The PHP functions for use with MySQL 5.0 have the following general format:


The i in the function name stands for improved (MySQL Improved). The second part of the function name is specific to the function, usually a word that describes what the function does. In addition, the function usually requires one or more values to be passed, specifying details such as the database connection or the data location. Here are two of the mysqli functions:

mysqli_connect(connection information);
mysqli_query($cxn,"SQL statement");

The corresponding mysql functions are

mysql_connect(connection information);
mysql_query("SQL statement",$cxn);

The functionality and syntax of the functions are similar, but not identical, for all functions. In particular, mysqli functions use a different process for connecting to the MySQL server than mysql functions do. The format of the mysqli function is


The connection process for mysql functions requires two function calls:


If you need to use the mysql functions, rather than the mysqli functions, you need to edit scripts, replacing the mysqli functions with mysql functions. The table shows mysqli function syntax and their equivalent mysql function syntax.

Syntax for mysql and mysqli Functions
mysqli Function mysql Function
mysqli_connect($host,$user,$passwd,$dbname) mysql_connect($host,$user,$passwd) followed by
mysqli_errno($cxn) mysql_errno() or mysql_errno($cxn)
mysqli_error($cxn) mysql_error() or mysql_error($cxn)
mysqli_fetch_array($result) mysql_fetch_array($result)
mysqli_fetch_assoc($result) mysql_fetch_assoc($result)
mysqli_fetch_row($result) mysql_fetch_row($result)
mysqli_insert_id($cxn) mysql_insert_id($cxn)
mysqli_num_rows($result) mysql_num_rows($result)
mysqli_query($cxn,$sql) mysql_query($sql) or
mysqli_select_db($cxn,$dbname) mysql_select_db($dbname)
mysqli_real_escape_string($cxn,$data) mysql_real_escape_string($data)