Php sql Left Join Tables表1中的Echo列

时间:2016-03-06 22:34:20

标签: php mysql

我有两个表博客和tbl_users。博客包含列'blogid','message','title','name','created'& 'image_ctgy'。 tbl_users包含列'userPic','image_ctgy','userId'。下面的代码显示了基于相同image_ctgy的博客消息以及与该博客消息相关联的图像。但是我对php的了解有限,而且我很难显示标题,名称和创建列以及博客消息。任何帮助将不胜感激。

$sql = "SELECT blog.message as blogmessage, tbl_users.userPic as tblPics
FROM blog
LEFT JOIN tbl_users ON(blog.image_ctgy = tbl_users.image_ctgy)
ORDER by blog.blogid DESC";
$stmt = $db->prepare($sql);
$stmt->execute();

$blogs = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$blogmessage = $row['blogmessage'];
$blogs[$blogmessage] [] = $row['tblPics'];
}
?>

<html>
<body>
<?php
    foreach ($blogs as $blogmessage => $tblPics)
    {
?>
    <h2><?php echo $blogmessage; ?></h2>

    <ul>
<?php
    foreach ($tblPics as $tblPic)
    {
 ?>
        <li> <img src="cms3/user_images/<?php echo $tblPic; ?>"width="50px" height="50px"/></li>

<?php
    }
 ?>
    </ul>
<?php
}
?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以使用此代码获取字段标题,名称,与消息和userPic一起创建:

<?php
$sql = "SELECT blog.message as blogmessage, blog.title, blog.name, blog.created,  tbl_users.userPic as tblPics
FROM blog
LEFT JOIN tbl_users ON(blog.image_ctgy = tbl_users.image_ctgy)
ORDER by blog.blogid DESC";
$stmt = $db->prepare($sql);
$stmt->execute();

$blogs = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
    // here you can get along with blogmessage another desired columns:
    // title, name, created
$blogmessage = $row['blogmessage'];
$blogs[$blogmessage] [] = $row['tblPics'];
}
?>

<html>
<body>
<?php
foreach ($blogs as $blogmessage => $tblPics)
{
    ?>
    <h2><?php echo $blogmessage; ?></h2>

    <ul>
        <?php
        foreach ($tblPics as $tblPic)
        {
            ?>
            <li> <img src="cms3/user_images/<?php echo $tblPic; ?>"width="50px" height="50px"/></li>

            <?php
        }
        ?>
    </ul>
    <?php
}
?>
</body>
</html>