-3

**Fatal Error : Call to undefined method Database::query()**在这部分的某个地方有一个错误(),我不知道这是从哪里来的。因为我刚刚改变了我的构造函数

Class Database{

public function __construct(){

    $this->getConn();
}
public function getConn(){
    return new mysqli("localhost", "root", "", "os_db");
}
public function select($query){
    $data = array();
    if($result = $this->query($query)){
        while($row = $result->fetch_assoc()){
            $data[] = $row;
        }
    }else{
        $data = array();
    }
return $data;
}
}

如果我将查询更改为此if($result = $this->getConn()->query($query)..它可以完美运行..无论如何我必须调用连接我会这样做$this->query($query)

4

1 回答 1

-2
Class Database {

  public function __construct() {

    $this->getConn(); 

  } 

  public function getConn() { 

    $db = new mysqli("localhost", "root", "", "os_db"); 
    $this->db = $db;

  } 

  public function select($query) { 

    $data = array(); 

    if($result = $this->db->query($query)){ 

      while($row = $result->fetch_assoc()){ 

        $data[] = $row; 

      } 

    } else { 

      $data = array(); 

    } 

    return $data;

  }

}

或者不是每次调用类时都连接,您可以执行以下操作:

Class Database {

  public function __construct() {

  } 

  public function getConn() { 

    $db = new mysqli("localhost", "root", "", "os_db"); 
    $this->db = $db;

  } 

  public function select($query) { 

    $this->getConn();

    $data = array(); 

    if($result = $this->db->query($query)){ 

      while($row = $result->fetch_assoc()){ 

        $data[] = $row; 

      } 

    } else { 

      $data = array(); 

    } 

    return $data;

  }

}
于 2013-09-01T07:00:10.270 回答