列出PHP MySQL中类别的帖子

时间:2016-10-09 13:34:26

标签: php mysql

我正在尝试获取与其关联的类别和帖子,但我只能从数据库中检索类别名称,并且无法将它们链接到相关帖子,这是我的代码:

    <?php

    //Create DB object
    $db = new Database();

  //Check url got Category
    if(isset($_GET['categories'])){
      $category = $_GET['categories'];

      // Create Query
      $query = "SELECT * FROM post WHERE category =". $category."ORDER BY id DESC";
      //Run query
      $posts = $db->select($query);
    }

    else{
        // Create Query
        $query = "SELECT * FROM post ORDER BY id DESC";
        //Run query
        $posts = $db->select($query);
    }

  // Create Query
  $query = "SELECT * FROM categories";
  //Run query
  $categories = $db->select($query);

 ?>

      <div class="row">

        <div class="col-sm-8 blog-main" style="width: 100%;">
        <?php if ($categories) : ?>
          <?php while($row = $categories->fetch_assoc()) : ?>

          <div class="blog-post">
            <h2 class="blog-post-title"><?php echo $row["name"]; ?></h2>

          </div>

        <?php endwhile; ?>

        <?php else : ?>
          <p>There are no posts.</p>
        <?php endif; ?>

和我的数据库表:

CREATE TABLE `post` (
  `id` int(11) NOT NULL,
  `category` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `author` varchar(255) NOT NULL,
  `tags` varchar(255) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `categories` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

提前谢谢

0 个答案:

没有答案