2015-01-15 116 views
3

我希望我可以解釋這一點......我有一個名爲$ departments_ids = array(1,2,3)的數組。雖然循環內的if語句是在foreach循環內......運行不正常

對於數組中的每個部門我需要顯示存儲在數據庫中的註釋列表。我想出了這樣的事情:

foreach ($departments_ids as $department_id) { 

$query = "SELECT page_posts.post_id, page_posts.post, page_posts.post_date_time, 
users.profile_type_id, users.first_name, users.last_name, users.picture ". 
"FROM page_posts ". 
"INNER JOIN users ". 
"USING (user_id) ". 
"WHERE dep_id = $department_id ". 
"ORDER BY post_date_time ASC"; 

$data = mysqli_query($dbc, $query); 

    if(mysqli_num_rows($data) != 0) { 
     while ($row = mysqli_fetch_array($data)){ 
     Here goes the code to print each comment 
     } 
    } 
    else { 
     <p> Sorry, there are no comments yet. Don\'t 
     be shy, be the first one to post!</p> 
     } 
} 

(注:我忽略,則代碼的一部分,爲了簡化說明)

代碼效果很好,問題是,它僅僅是印刷用的第一個註釋每個部門而不是存儲在數據庫中的所有評論。 這就像每個部門的代碼只讀一次,然後它移動到下一個部門。 如果我明白這一點,我相信一旦它碰到if語句並且看到有多條評論,它應該繼續閱讀while語句,while語句應該處理所有的評論,但由於某種原因,它是不工作。我閱讀了有關類似問題的人,但仍然無法弄清楚爲什麼它不起作用。

+0

我們可以做 - 在哪裏(「.implode(',',$ department_id)。」); – 2015-01-15 16:54:47

+0

您使用了連接。定義如何加入這些表的命令在哪裏? – 2015-01-15 16:55:21

+1

'這裏是打印每個評論的代碼 - 你不能顯示這個代碼嗎? – raina77ow 2015-01-15 16:55:21

回答

1

你可以試試這個:

$query = "SELECT page_posts.post_id, page_posts.post, page_posts.post_date_time, users.profile_type_id, users.first_name, users.last_name, users.picture "; 
$query .= "FROM page_posts INNER JOIN users USING (user_id) WHERE 1=1 AND"; 
$query .= "("; 
foreach ($departments_ids as $department_id) { 
    $query .= " dep_id=$department_id OR "; 
} 
$query .= ")"; 
$query .= " ORDER BY post_date_time ASC"; 

$data = mysqli_query($dbc, $query); 
if(mysqli_num_rows($data) > 0) { 
    while ($row = mysqli_fetch_array($data)){ 
     /*** Here goes the code to print each comment */ 
    } 
} else { 
    echo "<p> Sorry, there are no comments yet. Don\'t be shy, be the first one to post!</p>"; 
} 

編輯:

$query .= " dep_id=$department_id OR ";

是1或2或3

0

我終於想通了這個問題...這是一個菜鳥的錯誤:

我有2 $查詢是衝突wi彼此之間......我有1個查詢來查找註釋,然後另一個查詢來查詢這些查詢的響應......當我刪除第二個查詢來測試代碼時,我在我的問題中提供的代碼工作得很好;因此,我將第二個查詢改爲$ query2 ...問題解決了。

感謝您的幫助!