将多个表连接在一起

时间:2015-08-09 02:41:05

标签: php mysql

我正在尝试将两张桌子连在一起。在帖子表中,我有两列post_id和post_message。

在另一个表名中, post_attach 包含row_id,postid(与post_id相同)和file_name(与ms.jpg类似)。

帖子可能有多个附件。但我不知道将要查询哪些内容以显示包含多个附件的帖子。这是我的询问......

$ s =“来自帖子的SELECT posts.post_id,post_message,post_attach.file_name在post_id = row_id上加入post_attach;

<?php

$conn = mysqli_connect('localhost', 'root', 'root', 'blog') or die();


?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <h3>Allo post with their attahcment</h3>
        <?php 
            $s = " SELECT posts.post_id,post_message, post_attach.file_name from posts join post_attach on post_id=row_id;
";
            $q = mysqli_query($conn,$s);


            while ($row = mysqli_fetch_array($q)) {?>
                <p>Post No: <?php echo $row['post_id'] ?></p>
                <p>Post text: <?php echo $row['post_message'] ?></p>
                <p>Post attach: <?php echo $row['file_name'] ?></p>
            <?php } ?>
    </body>
</html>

我想要类似的东西:

发布号码:1,发表文字:你好php,附件:ms.jpg,ms.jpeetc。

最后一句话是每个帖子都会显示其相关附件。

1 个答案:

答案 0 :(得分:0)

我不会直接加入这些表格。我将遍历主帖子表并显示帖子ID和帖子消息,然后遍历附件。类似的东西:

<?php 
$s = "SELECT posts.post_id,post_message FROM posts";
$q = mysqli_query($conn,$s);

while($row = mysqli_fetch_array($q))
{
    ?>
    <p>Post No: <?php echo $row['post_id'] ?></p>
    <p>Post text: <?php echo $row['post_message'] ?></p>
    <p>
        Post attach:
        <?php
        $att = "SELECT post_attach.file_name FROM post_attach WHERE post_id = $row[post_id]";
        $files = mysqli_query($conn,$att);
        while($row_files = mysqli_fetch_array($files))
        {
            echo $row_files['file_name'] . "<br>";
        }
        ?>
    </p>
    <?php
}
?>