2013-11-21 147 views
3

在我的表courses中,有幾個條目共享相同的​​。我正在使用foreach循環來檢索結果集中的值。 for循環只顯示一個結果,而不顯示共享​​的所有其他結果。如何顯示共享相同​​的所有行?Foreach循環顯示具有相同ID的所有記錄

表值

+----+------------+----------------------+---------------+------------+ 
| id | academy_id |  course_name  | start_date | end_date | 
+----+------------+----------------------+---------------+------------+ 
| 1 |  123 | Biology - Basic  | 2013-11-30 | 2013-12-25 | 
| 2 |  123 | Biology - Nutrition | 2013-11-30 | 2013-12-25 | 
| 3 |  345 | Chemistry   | 2013-11-30 | 2013-12-25 | 
| 4 |  678 | Calculus    | 2013-11-30 | 2013-12-25 | 
+----+------------+----------------------+---------------+------------+ 

PHP

$academy_id = '123'; 

$db_select = $db_con->prepare(" 
SELECT c.course_name, 
     c.course_start_date, 
     c.course_end_date 
FROM courses c 
WHERE c.academy_id = 123 
"); 
if (!$db_select) return false; 
    if (!$db_select->execute(array(':academy_id' => $academy_id))) return false; 
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC); 
    if (empty($results)) return false; 
    foreach ($results as $value){ 
    $final_result = "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['start_date']."</br><b>End Date: </b>".$value['end_date']."</br>"; 
    } 
print_r($_POST); 
} 

CURENT結果

+----+------------+-------------------+---------------+------------+ 
| id | academy_id | course_name  | start_date | end_date | 
+----+------------+-------------------+---------------+------------+ 
| 1 |  123 | Biology - Basic | 2013-11-30 | 2013-12-25 | 
+----+------------+-------------------+---------------+------------+ 

通緝的結果都academy_id = 123顯示

+----+------------+----------------------+---------------+------------+ 
| id | academy_id |  course_name  | start_date | end_date | 
+----+------------+----------------------+---------------+------------+ 
| 1 |  123 | Biology - Basic  | 2013-11-30 | 2013-12-25 | 
| 2 |  123 | Biology - Nutrition | 2013-11-30 | 2013-12-25 | 
+----+------------+----------------------+---------------+------------+ 

回答

3

變化

$academy_id = '123'; 

.... 

foreach ($results as $value){ 
    $final_result = "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['start_date']."</br><b>End Date: </b>".$value['end_date']."</br>"; 
} 

$academy_id = 123; 

..... 

$final_result = ''; 
foreach ($results as $value){ 
    $final_result .= "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['start_date']."</br><b>End Date: </b>".$value['end_date']."</br>"; 
} 

echo $final_result; 
+0

它不起作用。檢查[鏈接](http://webprolearner.ueuo.com/test/courses.php)只顯示一個結果 –

+0

這並沒有改變任何東西。選擇回聲'$ final_result'只顯示一個結果'$ academy_id = 123',而不是第二個結果 –

0

(看到別人的答案,我知道我可以解決你有不同的問題或可能有) 我不確定我是否完全理解您的要求,但您可以嘗試以下方法

拆分代碼分爲兩個部分

1)部分人會做:

SELECT c.academy_id 
FROM courses c 
GROUP BY c.academy_id 

這將是你的循環

2)第二部分的前面的循環中會做初步結果您當前的SQL,而不是硬編碼123,它將使用上一個查詢的結果作爲值

相關問題