2014-06-25 133 views
-3

这是我用来连接到一个数据库类,它有一个查询方法通过成果循环,但它给了我这个错误:错误使用的mysqli取assoc命令获取的mysqli结果()

致命错误:Call to undefined method mysqli::fetch_assoc()用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() {} 

    } 
?> 
+1

请[使用RTFM mysqli_result :: fetch_assoc'如何'应该](http://php.net/manual/en/mysqli-result.fetch-assoc.php)。是的,它是'mysqli_result :: fetch_assoc',而不是'mysqli :: fetch_assoc'。 – deceze

回答

2

MySQLi对象没有方法fetch_assoc。您必须使用查询结果。例如:

public function query($query) { 
    $result = $this->mysqli->query($query); 

    $rows = array(); 
    while ($item = $result->fetch_assoc()) { 
     $rows[] = $item; 
    } 

    return $items; 
} 
+0

但是现在它给了我一个错误:致命错误:在第30行的C:\ Apache24 \ htdocs \ classes \ DB.php中耗尽了134217728个字节的内存大小(试图分配2176个字节)。 'while = $ result-> fetch_assoc())' – rexhin

+2

您查询返回的数据太多。尝试修改您的查询或扩展内存限制。 –

+0

该表中只有5行。 – rexhin