2014-06-25 130 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