MySQL deprecated error

All MySQL related extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. If you are still using MySQL extensions like mysql_​connect, mysql_​affected_​rows, mysql_​fetch_​array, mysql_​fetch_​assoc, mysql_​num_​rows etc etc now it is the time to change your code from mylsq to mysqli otherwise it will show deprecated error in PHP 5.5 onwards.

The following functions show how to connect to MySQL database and retrieve data from database using MySQLi.

Database connection using MySQLi

<?php
$host   = "Your Host Name";
$user   = "Your Username";
$pass   = "Your Password";
$dbname = "Your Database Name"

function db_connect() {
   static $connection;
   if(!isset($connection)) {
       $connection = mysqli_connect($host,$user,$pass,$dbname);
   }

   if($connection === false) {
       return mysqli_connect_error(); 
   }
   return $connection;
}
?>

Now we will write a function to run MySQL queries. You can use this function in place of mysql_query.
<?php
function db_query($query) {
  $connection = db_connect();
  $result = mysqli_query($connection,$query);
  return $result;
}
?>

Complete Code

Now we will create connection.php file with Mysqli and replace it with our old connection file.
connection.php
<?php
$host   = "Your Host Name";
$user   = "Your Username";
$pass   = "Your Password";
$dbname = "Your Database Name"

function db_connect() {
   static $connection;
   if(!isset($connection)) {
       $connection = mysqli_connect($host,$user,$pass,$dbname);
   }

   if($connection === false) {
       return mysqli_connect_error(); 
   }
   return $connection;
}

function db_query($query) {
   $connection = db_connect();
   $result = mysqli_query($connection,$query);
   return $result;
}

function db_error() {
   $connection = db_connect();
   return mysqli_error($connection);
}
$connect = db_connect();
?>

Now use the above connection file in place of the old one and find for the old MySQL query and replace with the new as suggested below. You need to replace all your MySQL functions with MySQLi functions. Few of them are given below.
 
Find Replace With
mysql_query() db_query()
mysql_fetch_array mysqli_fetch_array
mysql_fetch_assoc mysqli_fetch_assoc
mysql_num_rows mysqli_num_rows
mysql_fetch_row mysqli_fetch_row
mysql_insert_id mysqli_insert_id(db_connect())
mysql_real_escape_string() $connect->real_escape_string()



Other Related Posts

MySQL Error Handling
All deprecated functions and extensions in php 5.5

Comments
comments powered by Disqus