2013-02-25 94 views
0

我試圖顯示公司名稱從公司名稱,然後從另一個表循環出新聞。兩張桌子結合在一起。這意味着:我想從連接中的一個表中選出一行,並從連接中的另一個表中循環輸出數據。這可能嗎?我的代碼只在我的循環中的新聞表中顯示三個帖子中的兩個。PHP - 循環和不循環在同一時間從加入

謝謝!內部while循環,並嘗試

$sql = "SELECT 
      newID, newTitle, newSummary, newDate, 
      comID, comName, comImageThumb 
     FROM 
      tblNews a RIGHT JOIN tblCompanies b 
     ON a.newCompanyID = b.comID 
     ORDER BY newDate DESC"; 

// Get company name and display 
$companyData = mysql_fetch_assoc($result); 
$comName = $companyData['comName']; 

echo "<a href='#' class='name'>$comName</a>"; 

// Looping news 
while($news = mysql_fetch_assoc($result)) { 
    // Display news posts 
    $newTitle = $news['newTitle']; 

    echo $newTitle; 
} 
+0

題外話,但很重要:請注意,'mysql_xxx()'函數廢棄,不再維持。強烈建議儘快切換到'mysqli'或'PDO'庫。 – SDC 2013-02-25 12:19:47

回答

0

把一切:

while($news = mysql_fetch_assoc($result)) { 
// Get company name and display 

$comName = $news ['comName']; 

echo "<a href='#' class='name'>$comName</a>"; 

// Looping news 

    // Display news posts 
    $newTitle[] = $news['newTitle']; 

    echo $newTitle; 
} 
0

你應該看看MySQL的GROUP_CONCAT瞭解更多詳情。

0

最簡單的解決方案可能會保留你是否是在第一次迭代軌跡:

// query company name and news entries here 

$firstRow = true; 
while($news = mysql_fetch_assoc($result)) { 
    if ($firstRow) { echo $news['comName']; } 
    $firstRow = false; 

    echo $news['newTitle']; 
} 

你也可以保留當前的代碼,並使用mysql_data_seek(0)第一提取的公司名稱後,光標復位。

並在旁註:不要再使用mysql_*函數了!改爲使用PDO

+0

不幸的是,這並沒有工作,我仍然只從新聞表中的三個帖子中得到兩個... – David 2013-02-25 12:33:05

+0

你確定你在'while'裏面的新聞標題有'echo'嗎?我在上面的代碼中澄清了這一點。 – 2013-02-25 12:35:46

+0

是的:/我跳過了連接並分開了兩個表,但是感謝您的建議! – David 2013-02-25 12:59:00

0

移動提取操作循環的結束:

$companyData = mysql_fetch_assoc($result); 
$comName = $companyData['comName']; 

echo "<a href='#' class='name'>$comName</a>"; 

    // you've already fetched a news item.... 

$news=$companyData; 
do { 
    $newTitle = $news['newTitle']; 
    echo $newTitle; 
} while ($news=mysql_fetch_assoc($result));