2016-04-14 42 views
0

我試圖打印多個表中的數據到一個HTML表格,但我似乎無法找出原因無非是表格標題都出現了。爲什麼我的mySQL表數據不會回顯?

<?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(); 
?> 
+0

你在其他環境運行查詢,像phpMyAdmin,看它是否返回結果? –

+0

運行查詢後添加錯誤檢查 – Jens

回答

0

開始從查詢移除,major.gradDate,後,你有沒有其他字段跟隨。

你真的應該在你的查詢中檢查錯誤知道發生了什麼......

變化:$result_student=mysqli_query($conn, $query_student);

要:

$result_student=mysqli_query($conn, $query_student) or die(mysqli_error($conn));

0

您可以使用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> 

希望這對我有所幫助。

相關問題