我正在為我的代碼苦苦掙扎。我嘗試制作新聞提要。新聞提要運行良好,但現(xiàn)在我想在每個新聞行中添加頭像圖片以獲取作者的圖片。頭像圖片路徑在不同的表中(users)。這意味著我需要獲取特定用戶 ID ( $row['uid']) 的循環(huán),并且使用該 uid 我需要從user表中的用戶頭像獲取相關路徑。如果我嘗試在循環(huán)中使用查詢,它只會顯示一個結果,而不是查詢中指定的 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 query above*/ background-image: url("<?php echo $user_avatar['avatar']; ?>"); background-position:center; background-size:cover; } </style>
1 回答

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
沒有必要循環(huán)。joinSQL 是一種基于集合的語言,可以使用以下語法在單個查詢中為您提供所需的結果:
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
這比運行 7 個查詢(一個用于活動提要,然后一個用于 PHP 循環(huán)中第一個查詢返回的每一行)要高效得多。
然后您可以獲取結果集的行并直接在您的應用程序中使用它。
- 1 回答
- 0 關注
- 84 瀏覽
添加回答
舉報
0/150
提交
取消