2013-11-01 93 views
0

在Google上閱讀5個小時之後,我無法用MySQLI修復某些內容。遇到mysqli :: fetch_object();

我花了我所有的生活在MySQL編程,現在我試圖用mysqli更新我的知識,但我有一些麻煩。

我)喜歡這個叫news_Default(一個小功能:

<?php 
    Class Test extends DB{ 
    public function news_Default(){ 
     $query = $this->db->query('SELECT * FROM news'); 
     if($query->num_rows == 0) 
      return false; 
     else 
      return $query->fetch_object(); 
     } 
    } 
    ?> 

我以這種方式使用:

<?php 
    while($new = $panel->news_Default()){ 
     print_r($new); 
    } 
    ?> 

在MySQL中,當我返回對象,我可以用它與'while'或'foreach'循環沒有問題,但真正的問題在這裏,與mysqli。當我使用'while'(第二個codeblock)時,它循環6,000次(我使用$ counter ++來測試它),當我使用foreach時,它循環7次。在我的名爲'新聞'的表中,我只有兩條記錄。那麼,如何返回對象並在沒有這個問題的情況下在外部使用呢?因爲當我在類中使用它時,像$ new = $ query-> fetch_object()完美。

+0

什麼是您的PHP版本? – sectus

回答

0

您每次調用news_Default時都在進行sql查詢。

檢查修復它。

Class Test extends DB{ 
    private $_cached_news = null;     // let's store our query result 
    public function news_Default(){ 
     if ($this->_cached_news === null){   // not stored? 
      $this->_cached_news = $this->db->query('SELECT * FROM news');} // let's query 
     $return = $query->fetch_object();   // get next object 
     if (!$return)        // there is no objects anymore? 
      $this->_cached_news = null;    // let's clear our result 
     return $return; 
     } 
    }