Here is what I'm trying to do:
$username = 'john';
$_SESSION['data'] = "Hello ".$username;
$username = 'mike';
$new = $_SESSION['data']; // trying make it like: $new = "Hello ".$username;
echo $new // should output: "Hello Mike"
I'm trying to save a phrase with a dynamic variable into a $_SESSION variable, so the phrase can later be change on a different page depending on the dynamic variable.
Is this possible, and how can it be done?
4 Answers 4
You could use string formatting for that. Take a look:
$username = 'John'; // not really needed for this test
$_SESSION['data'] = "Hello %s";
$username = 'Mike';
$text = sprintf($_SESSION['data'], $username);
echo $text
Output:
Hello mike
See the code in action here.
1 Comment
It will not work the way you have it written, because the value you have stored in the session is a completely new value made using the value of the $username variable. As soon as it has been created, the value in the session is not associated with the $username variable whatsoever.
You can store the name and the phrase in the session separately, so they can be modified independently, and then combine them together later at the time you need to use them together.
For the specific case in your comment, storing the SQL string for a prepared statement with placeholders should work.
$_SESSION['statement'] = "SELECT some_columns FROM some_table LIMIT ?, ?";
$_SESSION['limit'] = $limit;
$_SESSION['offset'] = $offset;
You can't store the prepared statement itself, but you can store the SQL string, and then prepare and execute it in subsequent pages.
$stmt = $pdo->prepare($_SESSION['statement']);
$stmt->execute([ $_SESSION['limit'], $_SESSION['offset'] ]);
Just remember when you are ready to bind values to it on your next page before executing it that you need to specify that they should be bound as integers or disable emulated prepared statements.
Comments
If you want to add new element in the session array then you can push new element in the session array as follows:
array_push($_SESSION['data'],$element)
Comments
You could do something like this:
$username = 'john';
$_SESSION['data'] = 'echo "Hello $username";';
$username = 'mike';
eval($_SESSION['data']);
But I don't know why you'd want to, there are millions of ways you could achieve the results you want, an approach like this probably isn't the best.
$_SESSION['data'], and then passing all relevant variables to the template engine. Again, not at all trivial, but there's really no other way to solve the exact problem you posed. So: what is the problem you're trying to solve?