这是我连接到数据库的类它有一个查询方法来循环结果但它给了我这个错误:
致命错误:Call to undefined method mysqli::fetch_assoc()
in C:'Apache24'htdocs'classes'DB.php on line 30
我知道问题是在我的query()方法,我已经尝试使用非静态属性,但错误继续。
<?php
class DB {
private static $db_name = "data_db";
private static $db_user = "root";
private static $db_pass = "root";
private static $db_host = "localhost";
private static $row;
private static $instance = null;
public static function get_instance() {
if(!isset(self::$instance))
self::$instance = new self;
return self::$instance;
}
//returns mysqli object.
private function __construct() {
$this->mysqli = new mysqli(self::$db_host, self::$db_user, self::$db_pass, self::$db_name);
}
public function __destruct() {
$this->mysqli->close();
}
public function query($query) {
if ($result = $this->mysqli->query($query)) {
if($result->num_rows > 1) {
$rows = array();
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
} else {
$rows = $result->fetch_assoc();
}
return $rows;
}
}
/**
* Private clone method to prevent cloning of the instance of the
* *Singleton* instance.
*
* @return void
*/
private function __clone() {}
/**
* Private unserialize method to prevent unserializing of the *Singleton*
* instance.
*
* @return void
*/
private function __wakeup() {}
}
?>
MySQLi对象没有fetch_assoc方法。必须使用查询结果。例子:
public function query($query) {
$result = $this->mysqli->query($query);
$rows = array();
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
return $items;
}