dongyang9813 2015-10-23 08:19
浏览 85

MySQL - 尝试使用for循环检索数据库中的最新帖子 - 仅显示第一篇文章

  • I'm am trying to retrieve top 3 recent posts in MySQL database and post them in separate DIV using for loop.

  • Each post should show only show first 300 characters.

  • However it shows only the first post (300 characters) in all three
    DIV.

Here is the code:

   <!--- HTML CODE HERE --!> 
   <?php
    for($i = 1; $i<=3; $i++) {
    ?>
      <div id="outer-box">
        <div id="postImage-wrapper">
          image
        </div>
        <div id="postContent-wrapper">
          <h3> This is an Example post </h3>
          <span id="postInfo-wrapper">Author | 22/10/2015 | Xbox | 3 Comments</span><br />
          <?php
          $result = doSql("SELECT `gamereviews`.`reviewContent` FROM `gamereviews` ORDER BY `gamereviews`.`dateOfReview` DESC LIMIT 3");
          $row = mysqli_fetch_row($result);
          echo '<div onclick="alert(\''.$row[0].'\');">'.substr($row[0], 0, 300).'</div>';
          ?>
          <!-- <p class="post-snippet">Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of
            type and scrambled it to make a type specimen book. It has survived not only five centuries five centuries.</p> -->
        </div>

        <div id="postRating-wrapper">
          7.7
        </div>
      </div>


  <?php
    }
    ?>

Here is the result: https://gyazo.com/5593b4a4ccd82b61e88e8af90dedbe2f

I realize that the problem is probably with my for loop, that is, it simply prints out the first post 3 times.

But what is the way around this, how can I retrieve 3 posts from database and print them out in each div using a for loop or (if there is a better way)?

  • 写回答

1条回答 默认 最新

  • drxm5014 2015-10-23 08:37
    关注

    `Actually you are running the query inside the for loop , that's why you are getting the wrong result. first of all run the query outside the loop and then run a for each loop on the returned array.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100