我有一个表posts
,其中包含以下行:
post_id
post_title
post_image
post_body
category
存储类别的第二表category
cat_id
cat_name
当我点击帖子1时,它在新页面post.php?post_id=1
中打开。。我现在想做的是在新页面上只发布来自同一类别的类似帖子。这是我在单页上的代码
function truncate–s($text, $chars = 80) {
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text." ...";
return $text;
}
if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
$post_id = $_GET['post_id'];
$query = $pdo->query("SELECT * FROM posts WHERE post_id = $post_id");
foreach ($query as $row) {
echo '<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
<div class="portfolio-slider-wrapper">
<ul id="portfolio-slider">
<h4>'.$row['post_title'].'</h4>
<hr>
<li><img src="'.$row['post_image'].'" alt="" class="img-responsive"/> </li>
</ul>
</div>
<div class="blog-desc">
<ul class="post-meta-links list-inline">
<li><a href="#"><span> <i class="fa fa-calendar"></i></span>'.$row['post_date'].'</a></li>
</ul>
<p>
'.$row['post_body'].'
</p>
</div>
}
echo ' <div class="clearfix"></div>
<div class="related-post">
<h4>Related</h4>
<hr>';
$query1 = $pdo->query("SELECT * FROM posts INNER JOIN category ON posts.category=category.cat_id LIMIT 3");
foreach ($query1 as $post) {
echo '<div class="col-md-4 col-sm-4">
<div class="rel-post">
<a href="#">
<img src="'.$post['post_image'].'" alt="" lass="img-responsive">
<div class="caption">
<h4>'.$post['post_title'].'</h4>
<p>'.truncate–s($post['post_body']).'</p>
</div>
</a>
</div>
</div>';
}
目前,当我打开一些帖子时,不管ID是什么,它总是从数据库表中加载前3个帖子。
如何加载相同类别的帖子?
只需尝试该查询即可。
"SELECT * FROM posts INNER JOIN category ON posts.category=category.cat_id WHERE posts.category = '".$row['category']."' LIMIT 3"
请确保$query中只有一个元素。