简体   繁体   中英

nested query in php/mysql

I am new for PHP/mysql where I use them as backend for flutter app. I have 4 tables post,user,likes,comments and would like to filter the data of a post and the related likes and comments as well the post owner data(user) by a post property called category_name and its value is passed via a variable called "filter"

I have tried the nested query as following:

 <?php
$filter = "PMS";

if($filter=="All"){
   $sql= "SELECT users.*,post.*,COUNT(likes.user_id) as qty 
    ,COUNT(comments.Comment_owner_id) as comments FROM 
     likes JOIN post ON likes.post_id=post.id JOIN users ON 
     users.id=post.user_id JOIN comments ON 
     post.id=comments.post_id 
      GROUP BY post.id";

 }else{
   $sql= "SELECT test.* FROM (SELECT users.*,post.* 
    ,COUNT(likes.user_id) as qty ,COUNT(comments.Comment_owner_id) 
      as comments FROM post ->
    JOIN likes ON likes.post_id=post.id JOIN users ON 
    users.id=post.user_id JOIN comments ON post.id=comments.post_id   
    AS test GROUP BY post.id) WHERE test.category_name='$filter'";

   //execute the query

  $res= mysqli_query($conn,$sql);

   //convert it to an list

  $posts = mysqli_fetch_all($res,MYSQLI_ASSOC);
  if($posts){
    echo json_encode($posts);
  }else{
   echo "error";
  }


   ?>

but it does not work where I got the following message

 Fatal error: Uncaught TypeError: mysqli_fetch_all(): Argument #1 ($result) must be of type mysqli_result, bool given in C:\xampp2\htdocs\blog\data\postAll.php:32 Stack trace: #0 C:\xampp2\htdocs\blog\data\postAll.php(32): mysqli_fetch_all(false, 1) #1 {main} thrown in C:\xampp2\htdocs\blog\data\postAll.php on line 32

, have you any suggestions?

I figured out that the solution could be so simple

$sql="SELECT post.*,users.*,COUNT(likes.user_id) AS likes from post JOIN  users ON post.user_id=users.id LEFT JOIN likes ON post.id=likes.post_id WHERE post.category_name = '$filter' GROUP BY post.id";

It worked well for me.

if you are laravel developer you can use laravel package https://github.com/lazychaser/laravel-nestedset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM