Php sql 左连接表回显表 1 中的列

标签 php mysql

我有两个表 blog 和 tbl_users。博客包含列“blogid”、“消息”、“标题”、“名称”、“创建”和“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>

最佳答案

您可以使用此代码来获取与消息和用户图片一起创建的字段标题、名称:

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

关于Php sql 左连接表回显表 1 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833480/

相关文章:

php - 在条件 (if) 语句中使用 CodeCeption 断言

php - 如何获取当前用户在MYSQL中的第一个进程号?

mysql - 每周和日内数据汇总

mysql - 如何在 MySQL 中按字段值中的最后一项进行分组?

mysql - 选择不同的 ID

php - 使用查询绑定(bind) Fuelphp

php - CSS 类未反射(reflect)在表中

php - 在 PHP 中替换文件内容

php - 流明共享 Controller

php - 选择列表菜单回显