The cart is empty

application developers may encounter the error message "Fatal error: Call to undefined function mysql_query()", indicating an attempt to use the deprecated mysql_query() function. This error signifies that your application is trying to utilize a function for MySQL database operations no longer supported in newer PHP versions. The MySQL extension was deprecated as of PHP 5.5.0 and removed entirely in PHP 7.0.0. This article explores how to address this error and best practices for updating your code.

Identifying the Issue

The error message "Fatal error: Call to undefined function mysql_query()" suggests that your application attempts to call the mysql_query() function, which is unavailable in your PHP version. The first step towards resolution is identifying all instances in your code where mysql_* functions are used.

Migrating to MySQLi or PDO

To update your application and eliminate this error, it is recommended to migrate to either the MySQL Improved (MySQLi) extension or PHP Data Objects (PDO). Both alternatives offer enhanced functionalities, including support for prepared statements, which increase application security by helping prevent SQL injection attacks.

Migrating to MySQLi

MySQLi is an extension providing MySQL-specific functionalities. Migrating from mysql to mysqli typically requires several code adjustments, including changes in connection functions, query execution, and result handling. Here's an example of migrating to mysqli:

// Old connection method using mysql
$link = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database_name', $link);

// New connection method using mysqli
$link = new mysqli('localhost', 'username', 'password', 'database_name');

// Old query execution method
$result = mysql_query('SELECT * FROM table_name');

// New query execution method using mysqli
$result = $link->query('SELECT * FROM table_name');

Migrating to PDO

PDO provides a uniform interface for accessing various database systems. Migrating to PDO may require more substantial code revisions but offers greater flexibility and security. Here's an example of migrating to PDO:

// Old connection method using mysql
$link = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database_name', $link);

// New connection method using PDO
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Old query execution method
$result = mysql_query('SELECT * FROM table_name');

// New query execution method using PDO
$stmt = $pdo->query('SELECT * FROM table_name');

 

 

Migrating from the deprecated mysql extension to mysqli or PDO is not just about eliminating the "Fatal error: Call to undefined function mysql_query()". It's also about improving the security and efficiency of your application. Updating your code will enable you to utilize the latest PHP features while ensuring better compatibility with future PHP versions.