在foreach结果中查询数据库

时间:2017-11-23 12:55:05

标签: php mysql loops foreach

我正在尝试使用简单的状态帖子构建网页。我创建了foreach循环来查询数据库并加载所有帖子:

 <?php
 $user_id = Check::isLoggedIn();
 $dbstories = DB::query('SELECT * FROM stories WHERE user_id=:user_id ORDER BY story_time DESC', array(':user_id'=>$user_id));
 $post_story = "";
 foreach($dbstories as $story) {

  ?>

  <div>
    <article>
        <div>
          <a href="profile.php">
            <?php
              // to pull user first name
              $user_first = DB::query('SELECT user_first FROM users WHERE user_id=:user_id', array(':user_id'=>$user_id))[0]['user_first'];
              echo $user_first;
             ?>
          </a>
          <div>
            <time>
              <?php
               // to pull post datetime
               $post_time = $story['story_time'];
               echo '<time class="timeago" datetime="' . $post_time . '"></time>';
              ?>
            </time>
          </div>
        </div>
      </div>
      <?php
      // to pull post contents
      $post_story = $story['story_body'];
      if (strlen($post_story) <= 25) {
        echo '<h3>' . $post_story . '</h3>';
      } else {
        echo '<p>' . $post_story . '</p>';
      }
      ?>
      <div>
        <div>
          <a href="#">
            <svg class="thunder-icon"><use xlink:href="icons/icons.svg#thunder-icon"></use></svg>
            <span>
              <?php
               // to pull number of likes
               $post_likes = $story['story_likes'];
               echo $post_likes;
              ?>
            </span>
          </a>
          <!-- the same for comments and shares number goes here -->
        </div>
      </div>
      <div>

        <!-- This form over here should pull the story_id which is the post ID from the database like the other queries up there and post it next to the url then that will allow me to use it in isset($_GET['story_id']) and trigger a query to increment likes -->


        <form action="stories.php?post_id=<?php $post_id = $story['story_id']; echo $post_id; ?>" method="post" id="like_story">
          <a href="#" class="btn btn-control" id="post_like">
          <svg class="like-post-icon"><use xlink:href="icons/icons.svg#thunder-icon"></use></svg>
          </a>
        </form>
        <!-- the same for comment and share goes here -->
      </div>
    </article>
  </div>
 <?php 
  }
   ?>

*请阅读代码中的注释

一切正常,但我仍然无法将每个帖子的ID链接到类似按钮(like_story)。它只能访问最新帖子的ID。

引用帖子ID(story_id)的任何解决方法?

0 个答案:

没有答案