Search code examples
phpvariablessessionsuperglobals

A session variable doesn't get passed properly?


So, I am trying to set a $_SESSION variable and pass it to another page, but the variable on the other page is different than the one it must be.

In petitionlist.php the $_SESSION['petitionNameT'] = $petitionName1; is being set. The contest of $petitionName1 is different depending on which page you choose to click and it shows properly in the url id.


while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
    $petitionName1 = $row['petitionName'];
    $_SESSION['petitionNameT'] = $petitionName1;
    echo "<tr><td><a href='petition.php?id=$petitionName1'>";
    echo $row['petitionName'];
    echo "</a></td><td>";
    echo $row['petitionTheme'];
    echo "</td></tr>";
}

But when we go on petition.php the result displayed is very different than the one that should be and it's the exact same for every page, no matter on which one you clicked.


    <?php
    $petitionNameT = $_SESSION['petitionNameT'];
    ?>
    
    <div id="wrapper">
    
        <div id="contents">
    
            <h1 class="headers"><?php echo $petitionNameT?></h1>
            
            <p>
            
            </p>
    
        </div>
    
    </div>

FOR AN EXAMPLE:

On the first page clicked it should be petitionTest, but it is petitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetiti

On the second page clicked it should be petitionTest2, but it is petitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetiti

And so on and so on

P.S. petitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetitionNameTestpetiti is the name of one of the pages that can be clicked.

P.S.(2) I just found out that it takes the name of the last page possible to be clicked from the database.


Solution

  • Given your code $_SESSION['petitionNameT'] is overwritten each iteration of the loop so it will always be petitionName from the LAST row in the query.

    You probably don't want a session. Just use the id that you are including in the query string of the links:

    while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
        echo "<tr><td><a href='petition.php?id={$row['petitionName']}'>";
        echo $row['petitionName'];
        echo "</a></td><td>";
        echo $row['petitionTheme'];
        echo "</td></tr>";
    }
    

    Then in petition.php:

    $petitionNameT = $_GET['id'];