0

i would like to pass a variable through a for loop into a link such that the loaded page passes information about the correct link. right now my code seems to be storing the last variable in the for loop and passing that onto the link. it means that the generated table in the link always references the final piece.

the code is:

    <?php foreach($result as $key => $result) :?>
    <?php session_regenerate_id(); $_SESSION['id'] = $result['id']; ?>
    <tr>
    <td><?php echo $result['id'] ?></td>
    <td><?php echo $result['date'] ?></td>
    <td><?php echo $result['name'] ?></td>
    <td><div class="btn-group" data-toggle="buttons"><a href="cpt.php?id=$_SESSION['id']" target="_blank" class="btn btn-warning btn-xs" rel="noopener">More details</a></div></td>
    </tr>
    <?php endforeach;?>

The point is the link should display more information about the id that the user clicks on. However it only ever shows data of the last id. I think this is because the $_session['id'] is just storing the final loop.

1
  • Why you have to use session here? Couldn't be a normal variable to store the id value? Commented Feb 11, 2022 at 15:38

1 Answer 1

2

You are overwriting the $result variable in your loop:

<?php foreach($result as $key => $result) :?>

Do something like this instead:

<?php foreach($result as $key => $value) :?>

Then in your link you should be able to do:

<a href="cpt.php?id=<?php echo $value['id'] ?>"

I don't see any reason to be using session in this loop, I would advise removing that. You certainly don't want to be regenerating the session ID inside of a loop that displays chunks of html.

Sign up to request clarification or add additional context in comments.

1 Comment

wow thanks a lot! For others with a similar question, then use $_GET to call the variable in the other php script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.