mercredi 5 août 2015

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


Goodmorning

I'm planning to migrate a whole application I made from mysql extension to mysqli, due to next PHP version will not support mysql anymore and I don't want to go fool in the last minutes.

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

I'd like to mantain the procedural style also using mysqli extension, but I read that all mysqli functions must receive the connection link as a parameter.

I'm asking for suggestion on the best way (i.e. the most painless solution) to migrate without going mad and without radically rewrite 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'");

Most 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, the question now is how to migrate:

1) Should i pass the db connection as a function parameter? I.e. something like:

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

?

2) Should I, instead, define the db connection (defined into included dbdata.inc.php at page start) as GLOBAL variable, inside the function? I.e. something like:

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

?

3) Should I (it sounds terrific) explicitly declare a new connection inside any custom function? I.e. 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) Other suggestions?

Thanks in advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire