在我的表courses
中,我有几个共享相同academy_id
的条目。我正在使用foreach循环来检索结果集中的值。 for循环仅显示一个结果,而不是所有其他共享相同academy_id
的结果。如何显示共享相同academy_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 Result
+----+------------+-------------------+---------------+------------+
| 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 |
+----+------------+----------------------+---------------+------------+
答案 0 :(得分: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;
答案 1 :(得分:0)
(看到其他人的回答我知道我解决了你曾经或可能有过的另一个问题) 我不确定我是否完全理解您的要求,但您可以尝试
将您的代码分成两部分
1)第一部分将:
SELECT c.academy_id
FROM courses c
GROUP BY c.academy_id
这将是循环的主要结果
2)上一个循环中的第二部分将执行当前的SQL但不使用硬编码的123,它将使用上一个查询的结果作为值