PHP / MySQL多表选择

时间:2013-04-17 13:11:03

标签: php mysql multiple-tables

我正在尝试从一个表中选择多行,具体取决于从另一个表中提供的ID。

我已经使用了下面的代码一半,但是根据分配了多少个不同的标签,它会多次回显每个博客,我将如何进行,以便在博客的一个副本上显示多个标签张贴?

$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之外,一切都正常工作。

有人有任何想法吗?

1 个答案:

答案 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);