使用foreach查询PHP

时间:2016-04-13 17:39:11

标签: php html

如何从我关注的用户那里获得帖子?我有这个代码

<?php
    $query=$con->query("SELECT Following FROM followers WHERE Follower='$Name'");

    while ($row=$query->fetch_row()){
        $Follower=$row[0];
        $query2=$con->query("SELECT Image,`Text` FROM uploads WHERE Username='$Follower'");
    } 

    while ($row2=$query2->fetch_row()) {
        $Image=$row2[0];
        $Text=$row2[1];
        $Likes=$row2[2];
        $Comments=$row2[3];
        $Reposts=$row2[4];
?>
        <div class="PF">  
            <img src="../users/<?php echo $roww[0] ?>" class="FollowerPic">
            <span><?php echo $Follower?></span>
        </div>
<?php
    }
?>

但它不起作用它只给我最后一个用户的帖子

3 个答案:

答案 0 :(得分:2)

试试这样。将第二个“while”放入第一个。

<?php
            $query=$con->query("SELECT Following FROM followers WHERE Follower='$Name'");

                    while ($row=$query->fetch_row()){
                        $Follower=$row[0];
                        $query2=$con->query("SELECT Image,`Text` FROM uploads WHERE Username='$Follower'");


                       while ($row2=$query2->fetch_row()) {
                           $Image=$row2[0];
                           $Text=$row2[1];
                           $Likes=$row2[2];
                           $Comments=$row2[3];
                           $Reposts=$row2[4];


                           ?>
                           <div class="PF">
                               <img src="../users/<?php echo $roww[0] ?>" class="FollowerPic">
                               <span><?php echo $Follower?></span>
                           </div>

                           <?php
                       }
                    }
?>

但无论如何最好在1个查询(LEFT JOIN)

中使用它

LEFT JOIN示例;

<?php

            $sql = "SELECT * FROM followers AS f LEFT JOIN uploads AS u ON  f.Following = u.Username WHERE f.Follower='$Name' ORDER BY u.date LIMIT 0,250";
            $query=$con->query($sql);
            echo '<pre>';
            while ($row=$query->fetch_row()){
                print_r($row);
            }
            echo '</pre>';
?>

答案 1 :(得分:1)

试试这个,第二个循环应放在第一个循环中。

map :: (a -> b) -> [a] -> [b]

答案 2 :(得分:0)

<?php
        $query=$con->query("SELECT Following FROM followers WHERE Follower='$Name'");

                while ($row=$query->fetch_row()){
                  $Follower=$row[0];
                  $query2=$con->query("SELECT Image,`Text` FROM uploads WHERE Username='$Follower'");

               while ($row2=$query2->fetch_row()) {
                 $Image=$row2[0];
                 $Text=$row2[1];
                 $Likes=$row2[2];
                 $Comments=$row2[3];
                 $Reposts=$row2[4];


  ?>
    <div class="PF">  
                  <img src="../users/<?php echo $Image ?>" class="FollowerPic">
                  <span><?php echo $Follower?></span>
                </div>

    <?php
                    }
   }
  ?>

试试这个