我想创建一个简单的主题和张贴系统,我在MySQL数据库中有两个表;一个主题表和一个帖子表。在我的帖子表中,我有一个post_parentID字段,链接到我的主题表中的topic_id字段。
下面是我如何开始查询,选择(并显示)主题表中的所有主题。然后将topic_id字段保存为一个变量:
<?php
$sql = "SELECT * FROM topics INNER JOIN members ON topics.topic_by = members.id";
$topics = $mysqli->query($sql);
if ($topics->num_rows > 0) {
// output data of each topic
while($row = $topics->fetch_assoc()) {
//Saving TopicID into variable
$topic_id = $row["topic_id"];
$_SESSION['topicid'] = $topic_id;?>
在显示每个主题的html之后,我开始一个新的while循环来显示每个主题中的每个帖子:
<?php
$sql = "SELECT * FROM posts INNER JOIN members ON posts.post_by = members.id WHERE post_parentID = $topic_id";
$posts = $mysqli->query($sql);
if ($posts->num_rows > 0) {
// output data of each post
while($row = $posts->fetch_assoc()) { ?>
在此之后,我显示每个帖子的html,然后我显示表单控件来输入一个帖子,它被定向到send_post.php文件:
<div class="chat-message-form">
<div class="form-group">
<form action="includes/send_post.php" method="post">
<textarea class="form-control message-input" name="post_content" placeholder="Enter message text"></textarea>
<input type="submit">
</form>
</div>
</div>
当我在send_post.php文件中像这样调用$topic_id时:
$topic_id = $_SESSION['topicid'];
它只返回我的主题表中的最后一个topic_id,而不是while循环中的当前topic_id。我的逻辑是正确的还是我应该做一些不同的事情?
通过在循环中这样做:
$_SESSION['topicid'] = $topic_id;
每次循环都会覆盖topicid的值。我不知道你到底想让你的主题是什么样子的,但一个可能的避免方法是:
$_SESSION['topicid'] = array();
while($row = $topics->fetch_assoc()) {
$_SESSION['topicid'][] = $topic_id;
...
另一种简单的方法是://这将在循环期间为每个链接附加特定的id
之后,转到下一页,并使用$_GET方法获取通过url发送的id…然后把它应用到你的查询中
$topic_id= 0
//将此设置在循环前
while(){...
.....
$topic_id++;
//每个循环增加一个id
echo $topic_id
//打印id的值<a href="nextpage.php?id='".$$topic_id."'">to your next page</a>
//将特定的id连接到选定的链接
}
//关闭while循环
在你的nextpage.php
$variable_name=$_GET['$topic_id'];
//这样你就得到了特定的id连接到特定的链接点击