如何从mysqli_connect()函数获取最后使用的mysqli $ link?

问题描述 投票:0回答:2

我被迫将为PHP 5编写的网站转换为7.3。说出以下(旧)函数:

function logMySQLError($err_line)
{
    $err_no = @mysql_errno();
    $err_desc = @mysql_error();
    $err_time = date("n/j/Y, G:i:s", getLocalDateTimw());

    postError("$err_time - MySQL #$err_no '$err_desc', line:$err_line");
}

可以在整个网站中这样称呼:

if(!$result)
{
    logMySQLError(__LINE__);
}

现在在7.3版中,我必须添加'i'才能使此工作有效;),然后还需要requires $link parameter

$link

如何从上一个function logMySQLError($err_line) { $err_no = mysqli_errno(/* $link */); $err_desc = mysqli_error(/* $link */); $err_time = date("n/j/Y, G:i:s", getLocalDateTimw()); postError("$err_time - MySQL #$err_no '$err_desc', line:$err_line"); } ()调用中获取最后使用的$link,而不将其显式传递给此函数? (就像以前一样。)

php php-7
2个回答
0
投票

您可以使用类方法,据我所知,您只有似乎在使用基本过程编程的函数,对于这种方法,最好还是使用OOP方法。

我给一个例子课:

mysqli_connect

0
投票

使用类+构造。

class DB {

    protected $db_name = 'databasename';
    protected $db_user = 'databaseuser';
    protected $db_pass = 'databasepassword';
    protected $db_host = 'databasehost';
    protected $connect_db = null;

    // Open a connection to the database.
    // Make sure this is called on every page that needs to use the database.

    public function connect() {

        $this->connect_db = new mysqli( $this->db_host, $this->db_user, $this->db_pass, $this->db_name );

        if ( mysqli_connect_errno() ) {
            printf("Connection failed: %s\
", mysqli_connect_error());
            exit();
        }
        return true;

    }

    /** Here's your new function **/
    public function logMySQLError($err_line)
    {
        $err_no = mysqli_errno($this->connect_db);
        $err_desc = mysqli_error($this->connect_db);
        $err_time = date("n/j/Y, G:i:s", getLocalDateTimw());

        postError("$err_time - MySQL #$err_no '$err_desc', line:$err_line");
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.