2011-08-27 78 views
0

上午試圖通過數據庫結果集的循環,問題是,我知道我有數據只有一行,但環路返回5行 這是我的方法來自我的模型環路返回意想不到的結果

function get_latest_pheeds() { 
    $data = $this->user_keywords($this->ion_auth->user_id); 
    $keyword = $data; 
    $user_id = $this->ion_auth->user_id; 
      foreach($keyword as $key => $word) { 

       $q = "SELECT *,COUNT(pheed_comments.comment_id) as comments 
       FROM pheeds 
       LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id 
       WHERE pheed LIKE '%$word%' OR user_id='$user_id' 
       GROUP BY pheeds.pheed_id 
       ORDER BY datetime DESC"; 
       $result = $this->db->query($q); 
       $rows[] = $result->result(); 

      } 
      return $rows; 
    } 

我在做什麼wroing

+1

返回哪些行?同一排5次?或行,你不知道他們來自哪裏? –

+0

它返回5次的同一行 – MrFoh

+0

因爲在上面的代碼中沒有實際的mysql調用,所以我們需要查看你的db類。你知道如果foreach循環執行多次? –

回答

1

這是因爲你的查詢有一個OR它應該可能有一個AND - 每個查詢總是匹配的user_id='$user_id'

這個循環是非常低效的,無論如何,我想你想要做的事更是這樣的:

function get_latest_pheeds() { 
    $keywords = $this->user_keywords($this->ion_auth->user_id); 
    $q = "SELECT *,COUNT(pheed_comments.comment_id) as comments 
      FROM pheeds 
      LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id 
      WHERE (pheed LIKE '%".implode("%' OR pheed LIKE '%",$keywords)."%') AND user_id='".$this->ion_auth->user_id."' 
      GROUP BY pheeds.pheed_id 
      ORDER BY datetime DESC"; 
    return $this->db->query($q); 
} 

如果你想要像他們以前在返回結果爲數組,你會在需要循環結果並將它們中的每一個讀取到另一個數組的數組鍵中。我不能這樣做是因爲我看不到你的DB類...

編輯:輕微修正在上面的代碼...

ANOTHER編輯:另一修復...

+0

功能user_keywords($ user_ID的){ \t \t //獲取所有用戶的關鍵字 \t \t $ Q = $這個 - > DB->選擇( '關鍵字') \t \t \t \t \t \t - >從('關鍵字') \t \t \t \t \t \t - > where('U_id',$ user_id); \t \t \t \t \t $ words = $ q-> get() - > result(); \t \t \t \t \t $ keywords = explode(「,」,$ words [0] - > keywords); \t \t \t \t \t return $ keywords; \t} – MrFoh

+0

多數民衆贊成在方法,返回單詞來檢查pheed字段與 – MrFoh

+0

@MrFoh對不起,我不太明白爲什麼你告訴我/我們... – DaveRandom