繁体   English   中英

while循环中的SESSION变量未正确发送到第二个.php文件

[英]SESSION variable in while loop not being sent correctly to second .php file

我正在尝试创建一个简单的主题并发布系统,并且在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的值。 我不知道您希望您的topicid看起来如何,但是可以避免这种情况的一种可能方法是:

$_SESSION['topicid'] = array();

while($row = $topics->fetch_assoc()) {
$_SESSION['topicid'][] = $topic_id;
...

另一个简单的方法是:“>到您的下一页//将在循环过程中将特定的ID附加到每个链接

然后,转到您的下一页,并使用$ _GET方法获取通过url发送的ID ...然后将其应用于您的查询

$topic_id= 0 //在循环前设置

while(){...
.....

$topic_id++; //每个循环将ID递增1

echo $topic_id //如果您想将id的值<a href="nextpage.php?id='".$$topic_id."'">to your next page</a>打印<a href="nextpage.php?id='".$$topic_id."'">to your next page</a> //连接特定的id到选定的链接

} //关闭while循环

在您的nextpage.php中

$variable_name=$_GET['$topic_id']; //通过这种方式,您可以将特定ID链接到所单击的特定链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM