简体   繁体   中英

Php sql Left Join Tables Echo columns from table 1

I have two tables blog and tbl_users. blog contains columns 'blogid','message','title','name','created' & 'image_ctgy'. tbl_users contains columns 'userPic', 'image_ctgy', 'userId'. The code below displays the blog message and the associated images with that blog messsage based on the same image_ctgy. However my knowledge of php is limited and I am having difficulty in displaying the title, name & created columns along with the blog message. Any help would be appreciated.

$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>

You can use this code to get fields title, name, created along with message and 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM