PHP mysql for mysqli migration issues (custom functions, procedural style)

Goodmorning

I am planning to migrate the whole application I made from mysql extension to mysqli, due to the next PHP version it will no longer support mysql and I don't want to go stupid in the last minutes.

At the moment, the page has 2 main inclusions: 1) dbdata.inc.php, which contains the database connection data 2) function.inc.php, which contains the most frequently used functions

I would like to use a procedural style using the mysqli extension as well, but I read that all mysqli functions should receive a connection reference as a parameter.

I am asking you to offer the best solution (i.e. the most painless solution) for migration without going crazy and without radically rewriting all my php pages.

Actual content of dbdata.inc.php :

$yare_db = mysql_connect($yaredb_host,$yaredb_user,$yaredb_pass) or die("some error warning<br>"); 
mysql_select_db($yaredb_conn); 
mysql_query("SET NAMES 'utf8'");

      

The most commonly used functions, defined in functions.inc.php:

function YQUERY($query) {
    $res = mysql_query($query) or die(mysql_error());
    return $res;
}

function FETCHA($res) {
    $rs = mysql_fetch_array($res);
    return $rs;
}

function NUMROWS($res) {
    $num = mysql_num_rows($res);
    return $num;
}

function AFFROWS() {
    $num = mysql_affected_rows();
    return $num;
}

/* an important function filtering user input texts before passing them to queries */

function msg_safe($string) {
    // some regex and \n to "<br>" substitutions...
    $string = mysql_real_escape($string);
    return $string;
}

      

Well, now the question is how to migrate:

1) Should I pass the db connection as a function parameter? That is, something like:

function YQUERY($link,$query) {
    $res = mysqli_query($link,$query);
    return $res;
}

      

?

2) Should I instead define the db connection (defined in include dbdata.inc.php when the page starts) as a GLOBAL variable inside the function? That is, something like:

function YQUERY($query) {
     global $link;
     $res = mysqli_query($link,$query);
     return $res;
}

      

?

3) Do I have to (this sounds awesome) explicitly declare a new connection inside any custom function? That is, something like:

function YQUERY($query) {
     $link = mysqli_connect("host","user","pass","db") or die("Error " . mysqli_error($link)); 
     $res = mysqli_query($link,$query);
     return $res;
}

      

?

4) Any other suggestions?

Thank you in advance

+3


source to share


1 answer


If you don't have many connections in your application, the GLOBAL $ link option is best. If you have so many connections, I think you should make a function to open the connection and other functions that close the connection, and when you do something in the DB, open the connection, do whatever you need to do, and close the connection.



+1


source







All Articles