我试图将多个表中的数据打印到一个html表中,但我似乎不明白为什么除了表标题之外什么都没有显示。
<?php
include('includes/db_connect.php');
$query_student="SELECT student.firstName, student.lastName, major.major, major.gradDate,
FROM student
JOIN major
ON student.studentID=major.studentID";
$result_student=mysqli_query($conn, $query_student);
echo '<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Graduate Year</th>
<th>Major</th>
<th>Activity After Graduation</th>
</tr>';
while($row = mysqli_fetch_array($result_student))
{
echo'<tr>'; // printing table row
echo '<td>' . $row['firstName'] . '</td>';
echo '<td>' . $row['lastName'] . '</td>';
echo '<td>' . $row['gradDate'] . '</td>';
echo '<td>' . $row['major'] . '</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
$conn->close();
?>
首先从查询中删除,
,在major.gradDate,
之后,因为后面没有其他字段。
您真的应该检查查询中的错误,以了解发生了什么。。。
更改:$result_student=mysqli_query($conn, $query_student);
收件人:
$result_student=mysqli_query($conn, $query_student) or die( mysqli_error($conn) );
您可以使用foreach语句和mysqli
对象的query
方法来实现这一点。
我还修复了您的SQL,在将两个表添加到一起时需要LEFT JOIN
。请首先检查此SQL语句是否在环境中工作,因为它尚未经过测试。
$query_student="SELECT t1.firstName, t1.lastName, t2.major, t2.gradDate
FROM student t1
LEFT JOIN SECOND_TABLE t2
ON t1.studentID = t2.studentID";
// Replace SECOND_TABLE with your table name you're joining on
?> <tr>
<?php
if($conn):
foreach ($conn->query($query_student) as $row): ?>
<!-- conditional statements allow HTML inside PHP loops -->
<td> <?php echo $row['firstName']; ?> </td>
// [...]
<?php endforeach;
else:
die('Connection Error: ' . $conn->error);
endif; ?>
</tr>
希望这能有所帮助。