Migrating mysql functions to mysqli functions in PHP

Cover Image for Migrating mysql functions to mysqli functions in PHP

Hello developers, In the journey of PHP Developer, we encounter projects developed in the old PHP version and are needed to migrate to the latest version. But Migrating from any project which contains an implementation of deprecated functions, we need to rewrite the code to use the latest functions supported/replaced by PHP.

If the project is small, it is not a significant issue. But, when you are handling a big project, where the old deprecated functions are used at thousands of places in code, It isn't easy to edit each and every code usage in the project.

A quick solution to this problem is to define the deprecated functions by yourself and make sure that the file is included across all the files in the project.

<?php

if(!function_exists('mysql_query')){
  function mysql_query($sql){
    $connection = mysqli_connect('127.0.0.1','root','password','my_database');
    return mysqli_query($connection,$sql);
  }
}

?>

As illustrated in the example above mysql_query() function is deprecated, but we have created the function with the same name and added compatibility code. A new mysqli_query() function required $connection to be passed whereas In mysql_query() it was not required. We have opened the connection and passed it to mysqli_query() the method.

This methodology can be used to handle any type of deprecated function. We can use two simple steps.

  1. Create deprecated function

  2. Implement the newly introduced function

Hope you liked the article, Feedback is welcomed.