在OO PHP mysqli select方法中访问$ dbconnect的问题

时间:2016-06-19 22:15:23

标签: php mysqli

我正在尝试创建一个OO PHP数据库类,但是在解决如何将$ dbconnect变量传递到' select'方法。这是我的代码:

class Database {

private $db_host = "host";
private $db_user = "user";
private $db_pass = "password";
private $db_name = "dbname";
private $result = array();
private $myQuery = "";
private $numResults = "";

public function connect() {

    $dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
    if(mysqli_connect_errno()) {

        array_push($this->result, mysqli_connect_error());
        return false;

    } else {

        $this->con = true;
        return true;

    }

}

public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null) {

    $sql = 'SELECT '.$rows;
    if($table) {
        $sql .= ' FROM '.$table;
    }
    if($join != null) {
        $sql .= ' JOIN '.$join;
    }
    if($where != null) {
        $sql .= ' WHERE '.$where;
    }
    if($order != null) {
        $sql .= ' ORDER BY '.$order;
    }
    if($limit != null) {
        $sql .= ' LIMIT '.$limit;
    }

    $query = $dbconnect->query($sql);
    $this->myQuery = $sql;

    if($query->num_rows > 0) {

        $this->numResults = $query->num_rows;

        for($i = 0; $i < $this->numResults; $i++) {

            $r = mysqli_fetch_array($query);
            $key = array_keys($r);
            for($x = 0; $x < count($key); $x++) {

                if(!is_int($key[$x])) {
                    if(mysqli_num_rows($query) >= 1) {
                        $this->result[$i][$key[$x]] = $r[$key[$x]];
                    } else {
                        $this->result = null;
                    }
                }

            }

        }
        return true;

    } else {

        //array_push($this->selectresult, 'No rows returned');
        return false;

    }

}

所以我有一个创建数据库连接的方法,它将它分配给$ dbconnect变量。我的问题是,我需要能够在我的select方法中获取此变量,因为我使用的是mysqli ...但不能使用我的上述代码。我收到以下错误:

注意:未定义的变量:dbconnect

任何帮助指出我出错的地方都会很棒。

2 个答案:

答案 0 :(得分:2)

将其声明为类属性

private $dbconnect;

然后在构造函数中初始化它

$this->dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);

现在,您可以在课程的其他部分以$this->dbconnect

的形式引用它

答案 1 :(得分:2)

您可以创建此类的属性

protected $dbconnect;

然后创建一个设置$dbconnect

的值的构造函数
public function __construct()
{
     $this->dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}

然后在你的select()函数中使用

$query = $this->dbconnect->query($sql);代替$query = $dbconnect->query($sql);

希望这有帮助。