【发布时间】:2021-12-22 06:25:47
【问题描述】:
我在 PHP 中有一个循环并没有真正像我想要的那样结束,因为我没有使用 PHP 并且无法弄清楚。我想重复一个循环来显示每个类别的每个帖子,这些帖子都有名为“tblcategories”和“tblposts”的表格。我想每行做 2 个类别,每个类别有 2 个帖子,但我什至没有设法做超过一个类别。这是更新后的代码:
<?php
$no_of_records_per_page = 2;
$selectcat = "SELECT * FROM tblcategory"; //get all categories
$stmt = $con->prepare($selectcat);
$stmt->execute();
$result = $stmt->get_result();
$counter = 0;
while ($row = mysqli_fetch_array($result)) { //loop all category. here row is single category
$query="select tblposts.id as pid,tblposts.PostTitle as posttitle,tblposts.PostImage,tblcategory.CategoryName as category,tblcategory.id as cid,tblsubcategory.Subcategory as subcategory,tblposts.PostDetails as postdetails,tblposts.PostingDate as postingdate,tblposts.PostUrl as url from tblposts left join tblcategory on tblcategory.id=tblposts.CategoryId left join tblsubcategory on tblsubcategory.SubCategoryId=tblposts.SubCategoryId where tblposts.Is_Active=1 and tblposts.CategoryId=? order by tblposts.id desc LIMIT ?";
$stmt = $con->prepare($query);
$stmt->bind_param("ii", $row['id'], $no_of_records_per_page);
$stmt->execute();
$resultt = $stmt->get_result();
if ($counter % 2 == 0) echo "<div class='row'>"; //here we open row for each even category, so 0, 2, 4,...
else $counter++;
echo "<div class='col-md-5'>";
while ($row1 = mysqli_fetch_array($resultt)) {
echo "<div class='col-md-12'>"; ?>
<h2 style="text-align:center;" ><a href="category.php?catid=<?php echo htmlentities($row1['cid'])?>"><?php echo htmlentities($row1['category']);?></a></h2>
<hr>
<div class="post-preview"><a href="news-details.php?nid=<?php echo htmlentities($row1['pid'])?>">
<img class="post-title" src="admin/postimages/<?php echo htmlentities($row1['PostImage']);?>" alt="<?php echo htmlentities($row1['posttitle']);?>" style="width:250px; height:auto; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);">
<h2 style="font-size:20pt;" class="post-title"><?php echo htmlentities($row1['posttitle']);?></h2>
</a>
<p class="post-meta"><b>Category : </b> <a href="category.php?catid=<?php echo htmlentities($row1['cid'])?>"><?php echo htmlentities($row1['category']);?></a> <br><?php echo htmlentities($row1['postingdate']);?></a></p>
</div>
<hr>
<?php
// show here post from $row1
echo "</div>";
}
echo "</div>";
if ($counter % 2 == 1) echo "</div>"; //here we close row for category so, 1, 3, 5,...
}
?>
【问题讨论】:
-
这个答案可能对你有帮助stackoverflow.com/questions/2398402/…
-
您能详细解释一下您的问题吗?您想在每个类别中显示每行 2 个帖子吗?
-
@FarhodNematov 所以表“tblcategory”中的每一行都是类别所在的位置。 “tblposts”包含进入存储在 tblcategory 中的不同类别的帖子。正如您在代码中看到的那样,有行和列(行在我的代码中不起作用),我想每列列出一个类别,每个类别在其下方列出两个帖子。显示 2 列类别后,下一个类别应为下一行
标签: php