简体   繁体   English

PHP While循环在使用JOIN LEFT的SQL中不会检索多于一行

[英]PHP While loop not not retrieving more than one row in SQL that uses JOIN LEFT

I'm making a PHP SQL db to catalog short stories. 我正在制作一个PHP SQL数据库来分类短篇小说。 On my index page that shows little excerpts of the stories, I'm trying to display the sql rows from a table (stories) as an unordered list using the while looping function. 在显示一些故事摘录的索引页上,我试图使用while循环功能将表(故事)中的sql行显示为无序列表。 Ratings for the stories are held in another table and I'm linking it to the 'stories' table using LEFT JOIN and the unique column rows "id" and 'storyid'. 故事的评级保存在另一个表中,我使用LEFT JOIN以及唯一的列行“ id”和“ storyid”将其链接到“故事”表。

Upon loading, the data displays just fine, however only one SQL row is showing, and my limit is set to 50. The while loop script and sql(close) script flank the list item. 加载后,数据显示良好,但是仅显示一个SQL行,并且我的限制设置为50。while循环脚本和sql(close)脚本位于列表项的后侧。 No error messages are reporting. 没有错误消息正在报告。

can anyone suggest why only 1 item is showing? 谁能建议为什么只显示一项?

    <?php
            include("db.php");
            $query="SELECT s.*, AVG(r.rank) AS avrank
            FROM (SELECT *
                  FROM stories
                  WHERE id BETWEEN 1 AND 100
                  ORDER BY RAND()
                  LIMIT 50) AS s
            LEFT JOIN ratings AS r ON r.storyidr = s.id";
            $result=mysqli_query($connection,$query);
            ?>

    <ul id="tiles">
      <?php     
            while ($data = mysqli_fetch_assoc($result)):
            $id = $data['id'];
            $author = $data['author'];
            $page_path = $data['page_path'];
            $title = $data['title'];
            $avgrate = $data['avrank'];
            if(is_null($page_path)){$page_path = "#";}
            ?>
      <li>
        <div class="post-info">
          <h3><a href="create_page.php?id=<?php echo $id; ?>"><?php echo $title; ?></a></h3>
          <h3>rating is <?php echo $avgrate; ?>/5</h3>
          <span><a href="categories/<?php echo $category; ?>.php">
          <label> </label>
          </span> </div>
        <div class="post-info-rate-share">
          <form method="POST" action="rating.php?id=<?php echo $id; ?>">
            <fieldset class="rating">
              <legend> Rating: <?php echo $avgrate=round($avgrate,2); ?>/5</legend>
              <input type="radio" id="star5" name="starno" value="5" onclick="this.form.submit()"/>
            </fieldset>
          </form>
        </div>
      </li>
      <?php
            endwhile;
            mysqli_close($connection);
            ?>
    </ul>

You missed the GROUP BY : 您错过了GROUP BY

SELECT s.*, AVG(r.rank) AS avrank
FROM stories s                  
LEFT JOIN ratings AS r ON r.storyidr = s.id
WHERE id BETWEEN 1 AND 100
GROUP BY s.id
ORDER BY RAND()
LIMIT 50;

Demo: http://sqlfiddle.com/#!2/7a9fa/9 演示: http//sqlfiddle.com/#!2 / 7a9fa / 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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