在PHP mysqli PDO中对null调用成员函数query()

时间:2019-05-02 18:09:17

标签: php mysqli pdo

我正在处理有关注册的代码,但是我不知道为什么会有这个错误(我仍然是新手,要使用mysqli),我已经搜索了很多有关此错误的信息,但无法解决。这是我的代码:

 <?php
define('hostname', 'localhost');
define('username', 'root');
define('password', '');
define('dbname', 'web');


class DB
{

public $cn ;


public function connect()
{
$cn = new mysqli (hostname, username, password, dbname);
        if(mysqli_connect_errno()) {
        echo "Error: Could not connect to database.";
    exit;
    }       
}
public function register($username,$pass,$email,$name){
    //$sql = ;
    //if user has already existed in DB:
    $check = $this->cn->query("SELECT * FROM accounts WHERE username = '$username' OR email = '$email'");
    $count_row = $check->num_rows;
    //else insert new user: 
    if($count_row == 0){
        $sql1 = "INSERT INTO accounts
                 SET username = '$username', password = '$pass', email = '$email', display_name = '$name'";
        $result = mysqli_query($this->cn,$sql1) or die (mysqli_connect_errno()."cannot insert data"); 

        return $result;
    }else{
        return false;
    }
}

}

?>

打印出来的错误:

Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\Web4C\admin\classes\DB.php:120 Stack trace: #0 C:\xampp\htdocs\Web4C\register.php(14): DB->register('nhihaa', '12wde3', 'nhiha8@gmail.co...', 'Ha Nhi') #1 {main} thrown in C:\xampp\htdocs\Web4C\admin\classes\DB.php on line 120

0 个答案:

没有答案