简体   繁体   中英

MySQL query handle undefined

I have the following code, which works fine. Queries are executed, everything is OK. BUT I am getting a error from PHP: Notice: Undefined variable: handle in..../class.database.php on line 43 .

I can not figure out why that is happening.

(Line 43 points to the line of code marked below)

function __construct($hostname, $user, $pass, $databasename)
{
    $this->$handle = mysqli_connect($hostname, $user, $pass);
    if(!$this->$handle)
    {
        $this->seterror();
        return false;
    }
    $handle = mysqli_select_db($this->$handle, $databasename);
    if(!$handle)
    {
        $this->seterror();
        return false;
    }
    return true;
}

function query($text)
{
    $result = mysqli_query($this->$handle,$text); // LINE 43
    if(!$result)
    {
        $this->seterror();
        $this->geterror(); // temp
        return false;
    }
    return $result;
}

Using dollar sign for class property is unnecessary, You can change $this->$handle to $this->handle

function __construct($hostname, $user, $pass, $databasename)
{
    $this->handle = mysqli_connect($hostname, $user, $pass);
    if(!$this->handle)
    {
        $this->seterror();
        return false;
    }
    $handle = mysqli_select_db($this->handle, $databasename);
    if(!$handle)
    {
        $this->seterror();
        return false;
    }
    return true;
}

function query($text)
{
    $result = mysqli_query($this->handle,$text); // LINE 43
    if(!$result)
    {
        $this->seterror();
        $this->geterror(); // temp
        return false;
    }
    return $result;
}

handle should be a property of your class declared with "public", "private" or "protected" keyword. You should not use "var" to declare property specially if you are using recent version of PHP.

Like it was said before. If you declare the property properly, you will have to change

$this->$handle to $this->handle

to make it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM