Can't get access to database in user access class

时间:2015-06-25 10:00:47

标签: php

I'm new in oop and I would like to get access to class db in user_access class. But I can't, I get an error and I can't figure out why do I get errors like that:

Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\brothers.traning\profiadmin\models\login_Class.php on line 20

Notice: Trying to get property of non-object in C:\xampp\htdocs\brothers.traning\profiadmin\models\login_Class.php on line 21
not

This is my database class:

    class db
{
    public function db()
    {
        $db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);


        if (mysqli_connect_errno()) {

            echo "Error: Could not connect to database.";

            exit;

        }

    }

}

And this im my user_access class:

class user_access{

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

    }
    public function check_login($login,$password){
        $password = sha1($password);
        $sql = "SELECT * FROM admins WHERE username = '$login' AND password = '$password'";
        $result = mysqli_query($this->db,$sql);
        if($result->num_rows > 1){
            echo 'ok';
        }else{
            echo "not";
        }
    }

}

Now when I use:

  $db = new db();

$userDB = new user_access($db);

    $userDB->check_login('artur','ol');

I get an error... Can anybody help me, and tell me what is wrong with this code..?

1 个答案:

答案 0 :(得分:1)

EDIT3:改变

$result = mysqli_query($this->db,$sql);

$result = $this->db->query($sql);

查看手册:http://php.net/manual/en/mysqli.query.php

您正在使用面向对象的样式,因此查询的方法有点不同。在第一行中,您使用了程序式,这是错误的。

EDIT2:您必须返回连接对象!

class db
{
public function db()
{
    $db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);


    if ($db->connect_errno()) {

        echo "Error: Could not connect to database.";

        exit;

    }
    else { return $db; }

}

}

现在改变你的称呼方式:

$userDB = new user_access($db->db());

编辑:

class user_access{

public $db; 

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

}
public function check_login($login,$password){
    $password = sha1($password);
    $sql = "SELECT * FROM admins WHERE username = '$login' AND password = '$password'";
    $result = mysqli_query($this->db,$sql);
    if($result->num_rows > 1){
        echo 'ok';
    }else{
        echo "not";
    }
}

}

问题:在你的user_access类中:

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

}

您希望通过$ this-> db。

访问您的$ db变量