I have two while loops and two queries in the loops.
I must order posts as DESC by its IDs. But posts loop is under another query’s loop.
$follows=$db->prepare("SELECT * FROM follows WHERE follower=:login");
$follows->execute([':login'=>$login['id']]);
while($followed=$follows->fetch()) {
$posts=$db->prepare("SELECT * FROM posts WHERE user=:followed ORDER BY id DESC");
$posts->execute([':followed'=>$followed['following']]);
while($post=$posts->fetch()) {
?>
...
<?php }} ?>
This method is ordering posts depending on ID numbers of the follows table. I want to order posts as DESC for only IDs of posts. How can I fix this?
Advertisement
Answer
I think that you might be overcomplicating this. If you want a single dataset, then you should use a single, joined query. You can execute it once, and then loop over the results with php:
select ... from follows f inner join posts p on p.user = f.following where f.follower = :login order by p.id desc
Note that I left the select clause empty. You should really enumerate the columns that you want (and, if needed, alias them to avoid conflicts) rather than use *: this way, the structure of the resultset is explicit .