How to change mysql to mysqli?

前端 未结 11 1953
余生分开走
余生分开走 2020-11-21 04:55

Based on this code below I use for regular mysql, how could I convert it to use mysqli?

Is it as simple as changing mysql_query($sql); to

11条回答
  •  猫巷女王i
    2020-11-21 05:24

    Here is a complete tutorial how to make it quickly if you need to make worgking again a website after PHP upgrade. I used it after upgrading hosting for my customers from 5.4 (OMG!!!) to 7.x PHP version.

    This is a workaround and it is better to rewrite all code using PDO or mysqli Class.

    1. Connection definition

    First of all, you need to put the connection to a new variable $link or $con, or whatever you want.

    Example

    Change the connection from :

    @mysql_connect($host, $username, $password) or die("Error message...");
    @mysql_select_db($db);
    

    or

    @mysql_connect($host, $username, $password, $db) or die("Error message...");
    

    to:

    $con = mysqli_connect($host, $username, $password, $db) or die("Error message...");
    

    2. mysql_* modification

    With Notepad++ I use "Find in files" (Ctrl + Shift + f) :

    in the following order I choose "Replace in Files" :

    1. mysql_query( -> mysqli_query($con,

    2. mysql_error() -> mysqli_error($con)

    3. mysql_close() -> mysqli_close($con)

    4. mysql_insert_id() -> mysqli_insert_id($con)

    5. mysql_real_escape_string( -> mysqli_real_escape_string($con,

    6. mysql_ -> mysqli_

    3. adjustments

    if you get errors it is maybe because your $con is not accessible from your functions.

    You need to add a global $con; in all your functions, for example :

    function my_function(...) {
        global $con;
        ...
    }
    

    In SQL class, you will put connection to $this->con instead of $con. and replace it in each functions call (for example : mysqli_query($con, $query);)

提交回复
热议问题