When the form is submitted values are inserted into a mysql database. I am using a foreach
loop for fetching the results but I am getting unnecessary duplicate results displayed. The results are being displayed from three tables: academy
, courses_by_academy
and person
. They all share a foreign key academy_id
. How can I display the information just once without having to show up twice?
Please check this working DEMO for better understanding. Make sure to choose more than two courses and two contact/instructor person to see this specific behavor.
$db_select = $db_con->prepare("
SELECT a.name,
a.academy_id,
ca.course_name,
ca.course_start_date,
ca.course_end_date,
p.contact_role,
p.instructor_role,
p.first_name,
p.last_name,
p.person_email,
p.person_phone,
p.person_fax
FROM academy a
INNER JOIN courses_by_academy ca ON a.academy_id = ca.academy_id
INNER JOIN person p ON a.academy_id = p.academy_id
WHERE a.academy_id = :acad_id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':acad_id' => $acad_id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) return false;
$final_result = '';
$first = true;
foreach ($results as $value){
if($first){
$first = false;
$final_result .= "<b>Academy Name: </b>".$value['name']."<b> ID: </b>".$value['academy_id']."</br>";
}
$final_result .= "-------------------COURSES_OFFERED------------------</br>";
$final_result .= "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['course_start_date']."</br><b>End Date: </b>".$value['course_end_date']."</br>";
$final_result .= "---------------------PERSONEL-----------------------</br>";
$final_result .= "<b>First Name: </b>".$value['first_name']."</br><b>Last Name: </b>".$value['last_name']."</br><b>Email: </b>".$value['person_email']."</br>";
$final_result .= "<b>This person has the role of an instructor: </b>".$value['instructor_role']."</br><b>This person has the role of a contact: </b>".$value['contact']."</br>";
$final_result .= "<b>Phone: </b>".$value['person_phone']."</br><b>Fax: </b>".$value['person_fax']."</br>";
}
}
I had a quick run through your demo, I could only select up to two courses, not more than.
From what I can see the select statement is all processing logically as set out in your code.
As a matter of fact, your if statement already answers this requirement. EG:
if($first){
$first = false;
$final_result .= "<b>Academy Name: </b>".$value['name']."<b> ID: </b>".$value['academy_id']."</br>";
}
This works perfectly in your demo only showing the academy name once. Why not use this wherever you need it?
The only thing I think you don't really need is to display the second personell entry. You could use the same concept to hide that after the first record.