【发布时间】:2019-07-24 05:50:03
【问题描述】:
我想显示我自己的帖子(默认),但如果Status = '1'也显示朋友的帖子
我只有这段代码,它显示所有带有相关图像和内容的帖子,因为我不知道如何创建我正在寻找的代码。
数据库结构
帖子:
| commentid | comment | imagesid | author |
---------------------------------------------
| 1 | fool | 5557 | test |
| 2 | fool2 | 5585 | devel |
---------------------------------------------
多个图像:
| id | image | imagesid | author |
------------------------------------
| 1 | name1 | 5557 | test |
| 2 | name2 | 5557 | test |
| 3 | name3 | 5585 | devel |
------------------------------------
连接:
| id | Friend | FriendReferee | Status |
-----------------------------------------
| 1 | test | devel | 1 |
-----------------------------------------
当前的抓取结构
获取图片的实际代码:
$sql = "SELECT * FROM multiple_image";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$imgs[$row['imagesid]][$row['id']]= "<img width='' src='../images/".$row['name']."' >"; // array of image id's, with arrays of images inside them.
}
}
获取相关文本
$sql = "SELECT * FROM posts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$commentsToImages[$row['commentid']] = $row['imagesid'];
$comments[$row['commentid']] = $row['comment'];
}
}
在分隔的 div 中显示结果
foreach($commentsToImages as $commentID =>$imagesID) {
?>
<div class='main'>
<div class='comments'>
<?php echo $comments[$commentID];?>
</div>
<div class='pics'>
<?php
foreach($imgs[$imagesID] as $img) {
echo $img;
}
?>
</div>
</div>
<?php
}
?>
我尝试使用 JOIN 和 if else 语句来实现,但并没有真正按照我的意愿工作。
【问题讨论】:
-
iamgesid上的posts表是否是问题或数据库中的拼写错误? -
@Quasimodo'sclone,是的,它已修复。 :)
-
对我来说,您的表结构实际上是什么还不够清楚。我希望表 posts 像 (id, user_id, comment, image_id) 和 connections 像 (user_id,friend_id, ... ),都引用 user 表 (id, user_name, ...)。然后你可以在用户 ID 上建立一个 JOIN。
-
您应该根据 id 而不是冗余名称来规范化数据库。应该有一个包含名称的主表。这是基于查询中的 id 连接的。 en.wikipedia.org/wiki/Database_normalization
-
是的,我只显示显示带有图像的 cmets 的代码,因为我不知道如何使用此代码显示自己和朋友的帖子。我想,有人可以使用我目前拥有的代码并制作我正在寻找的代码。
标签: php arrays loops mysqli foreach