我有两个表“类别”和“帖子”,我正在尝试创建一个category.php页面,该页面显示带有帖子标题的不同类别作为原始帖子的链接。我尝试了不同的循环变体,但似乎无法做到正确。我希望有人能指出我正确的方向。
$query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a></h2>
<p>
Posted on <?php echo date('d-m-y h:i:s',strtotime($post['date_posted'])); ?>
In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
echo "<hr />";
}
感谢您提供任何意见
答案 0 :(得分:1)
您在while循环中使用了一个名为$post
的变量,但是您正在将while循环中的每一行检索到一个名为$ row的变量中。
解决这个问题,你的许多问题都会消失。
如果您想以此处的方式输出HTML,还需要停止并启动PHP解释器,请注意我添加的?>
和<?php
$query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
// change this to use a variable called $post
while ($post = mysqli_fetch_array($result)){
?>
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a>
<!-- Dont think this should be here -->
</h2>
<p>Posted on <?php echo date('d-m-y h:i:s',strtotime( $post['date_posted'] ) );?>In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
<?php
echo "<hr />";
}
?>
答案 1 :(得分:0)
原谅我的语法(可能稍微偏离),但这应该给你一个好主意:
$categories = array(
'sports' => array(
post1,
post2,
),
'weather' => array(
post1,
post2,
),
);
首先获取所有类别,然后遍历每个类别并获取与该类别相关的所有帖子。然后你可以正常循环遍历数组:
foreach($categories as $category){
//display category title
foreach($category['posts'] as $post){
//display post info
}
}
答案 2 :(得分:0)
您的代码中存在一些问题。
修改后的代码:
Toast
<强>的问题:强>
答案 3 :(得分:-1)
<?php ?>
内有HTML代码试试这个:
<?php $query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){ ?>
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a></h2>
<p>
Posted on <?php echo date('d-m-y h:i:s',strtotime($post['date_posted'])); ?>
In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
echo "<hr />";
<?php } ?>