I want to make a page “everything” on my website where will be all my users activity presented. So I need to make sql from two tables “images” and “user_favorites” and output all to this html design
My tables structure:
users
id
images
id
user_id
image
description
date
user_favorites
id
date
I have got this sql query
function users_everything($user_id)
{
$sql = "SELECT
i.description as text,
UNIX_TIMESTAMP(i.date) as image_date,
COALESCE ( imgcount.cnt, 0 ) as comments,
fav.id as favorite_id,
r.image as favorited_image,
u2.username as favorite_user,
t.image as favorite_user_image
FROM users u
LEFT JOIN images i ON i.user_id = u.id
LEFT JOIN images p ON p.id = (SELECT b.id FROM images AS b where u.id = b.user_id ORDER BY b.id DESC LIMIT 1)
LEFT JOIN (SELECT image_id, COUNT(*) as cnt FROM commentaries GROUP BY image_id ) imgcount ON i.id = imgcount.image_id
LEFT JOIN user_favorites fav ON fav.user_id = u.id
LEFT JOIN images r ON r.id = fav.image_id
LEFT JOIN users u2 ON u2.id = r.user_id
LEFT JOIN images t ON t.id = (SELECT b.id FROM images AS b where u2.id = b.user_id ORDER BY b.id DESC LIMIT 1)
WHERE i.user_id = ?
";
$query = $this->db->query($sql, $user_id);
return $query->result_array();
}
My “images” table have 1 record and “user_follow” 2 records but if I do foreach it returns two favorites and two images (image) was duplicated.
I do not make such things like everything page before where will be presented data from different pages to different html structure. I suppose you have experience with it and helps me
You need to convert your array of flat records into a tree structure in which each image contains a list of favorites. Something like: