循环(行)查询中的另一个SQL查询

问题描述 投票:0回答:1

我正在为我的代码而苦苦挣扎。我尝试制作新闻提要。新闻提要运行良好,但现在我想在每个新闻行上添加头像图片,以提供作者的图片。头像图片路径位于其他表(用户)中。这意味着我需要循环获取特定的用户ID($ row ['uid']),并使用该uid从用户表中的用户头像获取相关的路径。如果我尝试在循环中使用查询,则只会显示一个结果,而不是查询中指定的6个结果。

您有任何建议或建议我如何解决该问题?

非常感谢您的支持!

这是我目前的尝试:

            <div class="timeline p-4 block mb-4">

                <?php

                // Getting the user id and the feedmessage from Table "activity_feed"
                $statement = $pdo->prepare("SELECT feed_message, uid FROM activity_feed WHERE cid = :cid ORDER BY id DESC LIMIT 6");
                $result = $statement->execute(array('cid' => $cid));
                $count = 1;
                while($row = $statement->fetch()) 
                
                { 
                // Starting the News feed Loop
                ?>
                
                <?php

                // This will repeat now X times as defined in the query above by = LIMIT ?

                    // Getting the avatar path from the user table 
                    $statement = $pdo->prepare("SELECT avatar FROM users WHERE id = :id");
                    $result = $statement->execute(array('id' => $row['uid']));
                    $user_avatar = $statement->fetch(); 
                    ?>

                        <style>
                            #circle_feed {
                            height:50px;
                            width:50px;
                            border-radius:50%;
                            /* Including the avatar path from qurey above*/ 
                            background-image: url("<?php echo $user_avatar['avatar']; ?>");
                            background-position:center;
                            background-size:cover;
                                        }
                        </style>
                                

                    <div class="tl-item ">
                        <div class="tl-dot"><a class="tl-author" href="#" data-abc="true">
                        <!-- Including the Avatar circle here-->
                            <span class="w-40 avatar circle gd-warning border" id="circle_feed"></span></a>
                        </div>
                        <div class="tl-content">
                            <div class=""><?php echo $row['feed_message']; ?></div>
                            <div class="tl-date text-muted mt-1">DATE</div>
                        </div>
                    </div>                    

                  <?php 
                  // News Feed Loop is ending here
                    }       
                  ?>                   
                    
                </div>
            </div>
php jquery html sql loops
1个回答
0
投票

没有必要循环。 SQL是一种基于集合的语言,可以使用join语法在单个查询中提供所需的结果:

SELECT 
    af.feed_message, 
    af.uid,
    u.avatar
FROM activity_feed af
INNER JOIN users u ON u.id = af.uid
WHERE af.cid = :cid 
ORDER BY af.id DESC 
LIMIT 6

然后您可以从应用程序中一一读取结果集的行。

© www.soinside.com 2019 - 2024. All rights reserved.