How to use MySQL in PHP 7 version

MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 version. For a large and old application, this is difficult to search and replace each function.

We can use MySQL functions by creating a wrapper function for each below is running code.

mysql_connect("localhost","user","password");
mysql_select_db("database");
 
function mysql_connect($host,$user,$pass){
    
}

function mysql_select_db($db){
     /* use global so that we can use this connection in other mysql functions */
     global $dbconn;
     $dbconn = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
     if ($dbconn->connect_error) {
          // trigger your error message
     }
}
 
function mysql_query($query){
     global $dbconn;
     $mysqli_row = mysqli_query($dbconn, $query);
     return $mysqli_row;
}

function mysql_insert_id(){
    global $dbconn;
    return mysqli_insert_id($dbconn);
}

function mysql_fetch_array($result){
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    /* MYSQLI_BOTH will return both associative and numeric array */
    return $row;
}   	
 
function mysql_num_rows($result){
    $row_cnt = mysqli_num_rows($result);
    return $row_cnt;
}   

function mysql_real_escape_string($val){
    global $dbconn;
    $rl = mysqli_real_escape_string($dbconn, $val);
    return $rl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *