Accessing a variable outside of an if statement [closed]

I am creating a forum and people can create a topic(e.g. movies) and a subtopic under the topic(e.g. Avengers). In the topic.php page when someone clicks on the subtopic they want to view the get sent to that page and the subtopic name gets sent also like this:

<a href='subtopic.php?sub_name=$sub_topic_name'>" . $sub_topic_name . "</a>

and this is how I get the value of the subtopic:

$sub_name = isset($_GET['sub_name']) ? $_GET['sub_name'] : $sub_name = 0;

When I’m on the page of the subtopic and I do a var_dump and echo of the topic and subtopic everything comes back good. But when I enter a value into the text area and click the add comment button, the name of the subtopic doesn’t get uploaded to the database. Instead the value of 0 goes into the DB instead of the subtopic name.

For some reason the variable $sub_name doesn’t work inside of the if statement. Can someone help me figure out the problem here ?

<form action="subtopic.php" method="POST">

        <textarea id="add_comment" required rows="8" cols="70" name="add_comment" 
        placeholder="Add comment about topic"></textarea><br><br>

        <button type="submit" id="add_button" name="add_button">Add Comment</button>


And the php code:


include 'includes/bootstrap.php';

$userLoggedIn = $_SESSION['user_session'];

$sub_name = isset($_GET['sub_name']) ? $_GET['sub_name'] : $sub_name = 0;

global $sub_name;

$display_sub_topics = $con->prepare('SELECT topic, created_by FROM subtopic WHERE sub_topic = ?');
$display_sub_topics->bind_param("s", $sub_name);
$num_of_rows = $display_sub_topics->num_rows;
$display_sub_topics->bind_result($topic, $created_by);

if (isset($_POST['add_button'])) {

    $comment_add = $con->prepare("INSERT INTO subtopic_replies (reply, added_by, subtopic) 
        VALUES (?, ?, ?)");
    $comment_add->bind_param("sss", $_POST['add_comment'], $userLoggedIn, $sub_name);
    header('Location: ' . $_SERVER['HTTP_REFERER']);



When you submit the form you’re restarting the script, and variables from the previous invocation do not persist (except for session variables).

You can add the subtopic name to the action URL:

<form action="subtopic.php?sub_name=<?php echo urlencode($sub_name); ?>" method="POST">

Leave a Reply

Your email address will not be published. Required fields are marked *