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

I'm trying to create a simple topic and posting system and I have two tables in a MySQL database; a topics table and a posts table. In my posts table I have a post_parentID field that links to a topic_id field in my topics table.

Here is how I start my query selecting (and displaying) all the topics that are in the topic table. I then save the topic_id field into a variable:

<?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;?>

Right after I display the html for each topic, I start a new while loop to display each post within each topic:

<?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()) { ?>

Right after this, I display the html for each post and then I display the form-control to enter a post, which is directed to a send_post.php file:

 <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>

When I call $topic_id in my send_post.php file like this:

$topic_id = $_SESSION['topicid'];

It only returns the very last topic_id in my topics table instead of the current topic_id in the while loop. Is my logic about this right or should I be doing something different?

By doing this in your loop:

$_SESSION['topicid'] = $topic_id;

you're overwriting the value of topicid everytime you loop. I don't know how exactly you want your topicid to look like but a possible way to avoid this would be:

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

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