我在这部分的某处出现了错误(**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)
答案 0 :(得分:-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;
}
}