2016-12-01 94 views
1

我得到了2個表,每個cursus都有一個與外鍵連接的cursussoort。 我試圖從cursussoort表中獲取數據以顯示在while循環中。 cursussoort_ID顯示的是顯而易見的id,但是如何從cursussoort表中獲得'naam'?從外鍵獲取其他表中的數據

tables

<?php 
$result = mysqli_query($con, "SELECT * FROM cursus WHERE cursussoort_ID = 1 ORDER BY begindatum ASC"); 
while ($cursus = mysqli_fetch_array($result)) { 
?> 
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> 
    <div class="post-preview"> 
     <h2 class="post-title"> 
     <?php echo $cursus['cursussoort_ID'];?> 
     <?php echo $cursus['begindatum'] . "<br />";?> 

     </h2> 
     <h3 class="post-subtitle"> 
     <?php echo $cursus['beschrijving'] . "<br />";?> 
     </h3> 
    </div> 
</div> 
<?php } ?> 
+1

你應該看一看爲「SQL連接」,將幫助您解決問題。 http://www.w3schools.com/sql/sql_join.asp如果你願意,我可以爲你寫SQL語句,如果你沒有得到它。 – Twinfriends

回答

1

你在你的SQL語句,從2個表連接的數據應該JOIN

SELECT c.*, cs.* FROM cursus c 
INNER JOIN cs.cursussoort ON c.cursussoort_ID = cs.ID 
WHERE c.cursussoort_ID = 1 
ORDER BY begindatum ASC 

然後你就可以在HTML顯示出來:

<?php 
$result = mysqli_query($con, "SELECT c.*, cs.* FROM cursus c INNER JOIN cs.cursussoort ON c.cursussoort_ID = cs.ID WHERE c.cursussoort_ID = 1 ORDER BY begindatum ASC"); 
while ($cursus = mysqli_fetch_array($result)) { 
?> 
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> 
    <div class="post-preview"> 
     <h2 class="post-title"> 
     <?php echo $cursus['cursussoort_ID']; ?> 
     <?php echo $cursus['naam']; ?><br /> 
     <?php echo $cursus['begindatum']; ?><br /> 
     </h2> 
     <h3 class="post-subtitle"> 
     <?php echo $cursus['beschrijving']; ?><br /> 
     </h3> 
    </div> 
</div> 
<?php } ?> 
1

執行JOIN之間的表像

SELECT c.* 
FROM cursus c 
JOIN cursussoort cr ON c.ID = cr.cursussoort_ID 
WHERE c.cursussoort_ID = 1 
ORDER BY c.begindatum 
1

嘗試左外連接

主要的查詢是

`SELECT * FROM cursus c LEFT OUTER JOIN cursussoort cr ON (c.cursussoort_ID = cr.id) WHERE cursussoort_ID = 1 ORDER BY c.begindatum ASC`