I have a listing page (mysite.com/listing) in PHP that uses a foreach loop. It outputs a user ID e.g. user1, user2 and a link to a detail page eg: mysite.com/detail
Output:
1. User ID = user1 <a href="mysite.com/detail">Detail Page</a>
2. User ID = user2 <a href="mysite.com/detail">Detail Page</a>
...
10. User ID = user10 <a href="mysite.com/detail">Detail Page</a>
The detail page (mysite.com/detail) needs to receive the corresponding user ID from the listing page e.g if user clicks item 1 "user1" is set in a Session variable and passed from the listings page to the detail page. In the detail page then I want to just output "The users id is user1". I am wondering how Session variable work in a foreach loop or is there a better solution? If I use something like:
$_SESSION['user_id'] = (string)$user->primary_id;
echo $_SESSION['user_id'];
..in a foreach loop in the listings page it will capture the last User ID in the loop e.g. user10
and
echo $_SESSION['user_id'];
...in the detail page will output 'user10' instead of 'user1'.
Is it ok to even use session variables in a foreach loop?
Thanks
CodePudding user response:
"user1" is set in a Session variable and passed from the listings page to the detail page
...there is no need to do that. Sessions are not the best way to achieve this (not least because that model of transferring data breaks if you have the site open in more than one tab in your browser).
Just put a query parameter in the hyperlink URL and retrieve it using $_GET
.
e.g.
User 1 <a href="mysite.com/detail?user=1">Detail Page</a>
User 2 <a href="mysite.com/detail?user=2">Detail Page</a>
...etc.
and in the "detail" page:
$userID = $_GET["user"];