在 Null 上调用成员函数 query() [英] Call to member function query() on Null

查看:58
本文介绍了在 Null 上调用成员函数 query()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以只是想制作一个我以前做过的简单的注册/登录表格,但不是地狱,我能弄清楚为什么会发生这种情况.我的代码如下所示.

So just trying to make a simple register/login form which i have done before, but not for hell can i figure out why this is happening. my code looks like the below.

我已经注释掉了上面说它正在发生的错误.

Ive commented out the error above the line that it says its occurring.

<?php 

class connection{

    private $hostname = "localhost";
    private $username = "root";
    private $password = "";
    private $database = "test";
    private $conn;

    public function __construct(){
        $conn = new mysqli($this->hostname, $this->username, $this->password, $this->database)or die("MySQL Connection Error");
    }
    public function getConn(){
        return $this->conn;
    }
}
class queries{

    private $conn;

    public function __construct($conn){
        $this->conn = $conn;
    } 

    public function checkUser($username, $email){
        $query = "SELECT * FROM users WHERE username = '$username' OR email = '$email'";

//Call to  a member function query() on null in C:\xampp\htdocs\i\functions.php on line 28

        $result = $this->conn->query("$query");
        return $result;
    }

    public function insertUser($activated, $activation_code, $firstname, $lastname, $username, $password, $email){
        $query = "INSERT INTO users (activated, activation_code, firstname, lastname, username, password, email)
                  VALUES ('$activated', '$activation_code', '$firstname', '$lastname', '$username', '$password', '$email')";
        $result = $this->conn->query("$query");
    }
}

看起来很简单吧..现在是我正在使用的页面上的 php 代码 (register.php).

Seems Simple enough right.. now heres my php code on the page thats being used (register.php).

if (isset($_POST['register'])) {

    include 'functions.php';

    $connection = new connection();
    $query = new queries($connection->getConn());

    $firstname = mysql_real_escape_string($_POST['firstname']);
    $lastname  = mysql_real_escape_string($_POST['lastname']);
    $username  = mysql_real_escape_string($_POST['username']);
    $email     = mysql_real_escape_string($_POST['email']);
    $password  = sha1($_POST['password']);

    $user = $query->checkUser($username, $email);

    if ($user->num_rows > 0) {
        echo "User Exists";
    }else{
        echo "User Does not Exist";
    }
}

推荐答案

您的代码似乎是正确的,除了在您的 connection 类的构造函数中,您忘记使用 $this,将其更改为如下所示:

Your code seems correct, except in the constructor of your connection class, you've forgot to use the $this, change it to something like the following:

public function __construct() {
    $this->conn = new mysqli($this->hostname, $this->username, $this->password, $this->database)or die("MySQL Connection Error");
}

这篇关于在 Null 上调用成员函数 query()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆