gpt4 book ai didi

php - PHP/Mysql 从多个表中选择数据

转载 作者:行者123 更新时间:2023-11-29 19:04:44 25 4
gpt4 key购买 nike

我正在尝试从多个表获取数据来构建通知源。

我有 3 个表:usersuser_notificationuser_comments

当我点击图标检查通知时,我想仅将新通知显示为下拉列表,因此在user_notification表中我有行“status”id_fromid_owner 可以是"new"“旧”,这样我就知道什么检索,但是当我需要从这些通知中获取有关是谁的信息并能够显示例如个人资料图片、用户名、comment_id 等时,我的问题就来了。

这是我想要获取的 HTML:

while ($row_notification = $result_load_notifications->fetch_assoc()) {

echo '<li class="dropdown-item">
<img src="'.$row_notification["avatar"].'" class="avatar-feed" alt="'.$row_notification["name"].'" /><p><strong>'.$row_notification["name"].'</strong> new <a href="https://sample.com/user/'.$_SESSION['alias'].'/#comment-'.$row_notification["id_comment"].'">comment</a> notification.<br>
<time class="date-post" datetime="'.$row_notification["date"].'"></time></p>
</li>';
echo '<li class="dropdown-divider"></li>';

}

这是我认为可以工作但没有工作的 PHP/Mysqli:

SELECT
*
FROM
user_notification n,
users u,
user_comments c
WHERE
n.status='new'
AND
n.id_owner=$session_id
AND
u.id_user=n.id_from
AND
c.id_owner=n.id_owner

在 PHP 中:

$load_notifications = mysqli_query($conn, "SELECT * user_notification n, users u, user_comments c WHERE n.status='new' AND n.id_owner=$session_id AND u.id_user=n.id_from AND c.id_owner=n.id_owner");

该代码不起作用,我做错了什么吗? (我不是专家)我是否缺少表之间的关系?

任何提示将不胜感激,谢谢。

最佳答案

我终于可以解决我的问题,逐步检索数据以了解其工作原理并最终得到此代码(不确定这是否是一个好的做法,但它有效):

SELECT 
u.name, u.avatar, c.id_comment, c.date
FROM user_notification n, users u, user_comments c
WHERE n.id_owner = ?
AND n.notification_status = ?
AND u.id_user = n.id_from
AND c.id_user= n.id_from
AND c.id_owner = n.id_owner

关于php - PHP/Mysql 从多个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com