[英]PHP loop through multiple database tables
假設我有一個如下所示的數據庫結構:
學生們
+--------------+--------------------+-------------------+
| student_id | student_firstname | student_lastname |
+--------------+--------------------+-------------------+
| 1 | John | Doe |
+--------------+--------------------+-------------------+
| 2 | Lisa | Doe |
+--------------+--------------------+-------------------+
| 3 | Derp | Doe |
+--------------+--------------------+-------------------+
缺席
+--------------+--------------------+-------------------+---------------+
| absence_id | absence_student_id | absence_date | absence_note |
+--------------+--------------------+-------------------+---------------+
| 1 | 2 | 2012-06-10 | A note... |
+--------------+--------------------+-------------------+---------------+
| 2 | 3 | 2012-06-30 | Another note. |
+--------------+--------------------+-------------------+---------------+
與列之間的關系students.student_id
和absence.absence_student_id
在PHP中,我想循環遍歷上面的表並獲得students
行的完整輸出,如果absence
匹配該學生的記錄,則對該行執行某些操作然后繼續循環。
我想要的HTML輸出是這樣的:
<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>
我用這樣循環:
<?php
while ($row = mysql_fetch_array($students_sql_query)) {
echo "<tr><td>".$row['student_firstname']."</td></tr>";
}
?>
是否可以為此添加某種if
語句? 我需要兩個不同的MySQL
查詢和某種foreach
循環嗎? 我對網絡編程比較陌生......提前謝謝,很抱歉很長的帖子。
您需要在查詢中加入表,然后從查詢中獲取結果。
SELECT Students.student_firstname
, Students.student_lastname
, Absence.absence_date
, Absence.absence_note
FROM Students
LEFT JOIN Absence ON Students.id = Absence.absence_student_id
然后你應該能夠循環遍歷它,類似於:
<?php
while ($row = mysql_fetch_array($students_sql_query))
{
?>
<tr>
<td>$row['student_firstname']</td>
<td>$row['student_lastname']</td>
<td>$row['absence_date']</td>
<td>$row['absence_note']</td>
</tr>
<?
}
?>
左連接將告訴數據庫拉入所有學生,如果他們缺席,它也會填充。 如果學生沒有缺席,那么將從數據庫返回null。 當它顯示在循環中的表行中時,如果該學生的缺席表中沒有任何內容,則它應顯示為空列。
唯一的缺點是如果學生有多次缺席,它將在顯示表中復制行。 在這種情況下,您必須在代碼或顯示中進行一些預處理以處理該情況。
使用pdo如下:
$sql = $dbh->prepare('
SELECT student_firstname, student_lastname, absense_date, absense_note
FROM students s inner join absense a
ON s.student_id=a.absense_student_id
');
$sql->execute();
$result = $sql->fetchAll(); <----- fetch All the data
return $result;
foreach($result as $row)
{
echo '<tr>';
echo '<td>'.$row['student_firstname'].' '.$row['student_lastname'].'</td>';
echo '<td>'.$row['absense_date'].'</td>';
echo '<td>'.$row['absense_note'].'</td>';
echo '</tr>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.