在非对象上调用成员函数real_escape_string()

时间:2013-07-01 13:41:58

标签: php mysql-real-escape-string

错误是: 未定义的变量:第24行的/var/www/index.php中的mysqli致命错误:在第24行的/var/www/index.php中的非对象上调用成员函数real_escape_string()

connect.php

<?php

/**
* Mysql Connect
*/

class MysqlConnect
{
    private $db_host;
    private $db_usermame;
    private $db_password;
    private $db_database;

    public function __construct($db_host,$db_usermame,$db_password,$db_database)
    {   
        $this->db_host = $db_host;
        $this->db_usermame = $db_usermame;
        $this->db_password = $db_password;
        $this->db_database = $db_database;

        $mysqli = mysqli_connect("$this->db_host", "$this->db_usermame", "$this->db_password", "$this->db_database") or die("Can't connect");
        $mysqli->select_db("$this->db_database") or die("Can't select database");
    }
}

$mysqli = new MysqlConnect('localhost','root','nistor','game');

?>

的index.php

<?php

require_once ('connect.php');

?>

Register

<?php 

/**
* Register
*/


class RegisterUser
{   

    public $username;
    public $password;
    public $email;
    function verify(){
        if (isset($_POST['register'])) {
        return $username = $mysqli->real_escape_string($username);
        var_dump($mysqli); exit;
    }else{
        echo "no";
    }
}

}

$obj = new RegisterUser();
$obj->verify();

?>
<form action="index.php" method="POST">
Username: <input type="text" name="username"><br />
Password: <input type="password" name="password"><br />
E-Mail: <input type="text" name="email"><br />
<input type="submit" name="register" value="Register">
</form>

1 个答案:

答案 0 :(得分:-1)

您的验证功能没有名为$mysqli的对象,它只存在于您的MysqlConnect班级constructor中。您可以按照以下步骤重新调整MysqlConnect课程。

class MysqlConnect
{
    private $db_host;
    private $db_usermame;
    private $db_password;
    private $db_database;
    private $mysqli;

    public function __construct($db_host,$db_usermame,$db_password,$db_database)
    {   
        $this->db_host = $db_host;
        $this->db_usermame = $db_usermame;
        $this->db_password = $db_password;
        $this->db_database = $db_database;

        $this->mysqli = mysqli_connect("$this->db_host", "$this->db_usermame", "$this->db_password", "$this->db_database") or die("Can't connect");
        $this->mysqli->select_db("$this->db_database") or die("Can't select database");
    }

    public function getMysqli()
    {
        return $this->mysqli;
    }
}

完成此操作后,您可以在驱动程序类中执行与registeruser类似的以下代码。

class RegisterUser
{   

    public $username;
    public $password;
    public $email;
    function verify(){
        $mysqlcon = new MysqlConnect('localhost','root','nistor','game');
        $mysqli = $mysqlcon->getMysqli();
        if (isset($_POST['register'])) {
        return $username = $mysqli->real_escape_string($username);
        var_dump($mysqli); exit;
    }else{
        echo "no";
    }
}

}