2013-04-17 116 views
0

我想從一個表中選擇多個行,具體取決於從另一個表給出的ID。PHP/MySQL多表選擇

我已經把它與下面的代碼一起工作了,但是它會根據有多少不同的標籤被分配給它來多次回顯每個博客,我將如何去做,以便它在一個副本上顯示多個標籤博客文章?

$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC"; 
    $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 
$blogDisplay = ''; 
     while ($row = mysqli_fetch_array($query)) { 
     $blogid = $row["blogid"]; 
     $blogtitle = $row["blogtitle"]; 
     $content = $row["content"]; 
     $blogtime = $row["blogtime"]; 
     $category = $row["category"]; 
     $blogseourl = $row["blogseourl"]; 
     $author = $row["author"]; 
     $contentshort = substr($content, 0, 250); 
    $sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'"; 
    $query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());   
     while ($row = mysqli_fetch_array($query2)) { 
     $tag = $row['tag']; 

$blogDisplay .= '<h1><a href="/blog/'. $blogseourl .'"> ' . $blogtitle . ' </a></h1> ' . $contentshort . '... <a href="/blog/'. $blogseourl .'">Read More...</a><br /><br /> ' . $author . ' posted on ' . $blogtime . ' &#124; Category: ' . $category . ' &#124; Tags: ' . $tag . ' &#124; <a href="/blog/'. $blogseourl .'#disqus_thread"></a>'; 
     } 
     } 
mysqli_free_result($query); 

所以一切工作正常,除了它回顯多個$ blogDisplay的每個標籤。

任何人有任何想法?

+0

這是不執行內部循環查詢最佳途徑。所以你必須使用連接。 –

回答

0

您必須將blogDisplay分成兩部分,並列出其間的選項卡。 或者你有緩衝了標記列表,並插入其作爲參數傳遞到$ blogDisplay

第一種是最容易:

$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC"; 
    $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 
$blogDisplay = ''; 
     while ($row = mysqli_fetch_array($query)) { 
     $blogid = $row["blogid"]; 
     $blogtitle = $row["blogtitle"]; 
     $content = $row["content"]; 
     $blogtime = $row["blogtime"]; 
     $category = $row["category"]; 
     $blogseourl = $row["blogseourl"]; 
     $author = $row["author"]; 
     $contentshort = substr($content, 0, 250); 
    $sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'"; 
    $query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());   

/*first part, all the html before the taglist */ 
$blogDisplay .= '<h1><a href="/blog/'. $blogseourl .'"> ' . $blogtitle . ' </a></h1> ' . $contentshort . '... <a href="/blog/'. $blogseourl .'">Read More...</a><br /><br /> ' . $author . ' posted on ' . $blogtime . ' &#124; Category: ' . $category . ' &#124; Tags: '; 

     while ($row = mysqli_fetch_array($query2)) { 
     $tag = $row['tag']; 
/**add the taglist*/ 
$blogDisplay .= $tag.' '; 
     } 

/**last part, all the html after the taglist*/ 
$blogDisplay .= ' &#124; <a href="/blog/'. $blogseourl .'#disqus_thread"></a>'; 

     } 
mysqli_free_result($query);