let’s say I have a database structure like below:
Students
+--------------+--------------------+-------------------+
| student_id | student_firstname | student_lastname |
+--------------+--------------------+-------------------+
| 1 | John | Doe |
+--------------+--------------------+-------------------+
| 2 | Lisa | Doe |
+--------------+--------------------+-------------------+
| 3 | Derp | Doe |
+--------------+--------------------+-------------------+
Absence
+--------------+--------------------+-------------------+---------------+
| absence_id | absence_student_id | absence_date | absence_note |
+--------------+--------------------+-------------------+---------------+
| 1 | 2 | 2012-06-10 | A note... |
+--------------+--------------------+-------------------+---------------+
| 2 | 3 | 2012-06-30 | Another note. |
+--------------+--------------------+-------------------+---------------+
And a relationship between column students.student_id and absence.absence_student_id
In PHP I would like to loop through the above tables and get a complete output of the rows in students and if there is a record in absence matching that student, do something to that row and then continue the loop.
My desired HTML output would be something like this:
<table>
<thead>
<tr>
<td>Name:</td>
<td>Absence date:</td>
<td>Absence note:</td>
</tr>
</thead>
<tr>
<td>John Doe</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Lisa Doe</td>
<td>2012-06-10</td>
<td>A note...</td>
</tr>
<tr>
<td>Derp Doe</td>
<td>2012-06-30</td>
<td>Another note.</td>
</tr>
</table>
I use to loop like this:
<?php
while ($row = mysql_fetch_array($students_sql_query)) {
echo "<tr><td>".$row['student_firstname']."</td></tr>";
}
?>
Is it possible to add some kind of if statement to this? Would I need two different MySQL querys and some kind of foreach loop instead? I’m relatively new to web programming… Thank’s in advance and sorry for a long post.
You’ll need to join the tables in a query and then get the results from the query.
You should then be able to loop through it similar to this:
The left join will tell the database to pull in all the students and if they have absences it will populate those too. If the student doesn’t have an absence, that will return as null from the database. When it is displayed in the table row in the loop, it should display as an empty column if there is nothing in the absence table for that student.
The only downside is if a student has multiple absences it will duplicate rows in the display table. In that case, you’ll have to do some pre-processing either in the code or in the display to handle that condition.