user1035927
user1035927

Reputation: 1753

PHP Store values

I have a php application getting x and y position constantly from the server. Based on the value of x and y, it places an image on screen. The page is constantly refreshed every 10 seconds. I want to save the previously obtained x and y value (before refresh) in to x1 and y1 and then store the currently obtained value in x and y (after refresh), so that I can calculate x1-x and y1-y.

<?php
session_start();  
if(isset($_SESSION['x1']))
    $_SESSION['x1'] = $x;
else
    $_SESSION['x1'] = 0;

$x = //Some method of fetching the x position from server
?>

Problem with the above code is, that during every refresh the value of x1 is replaced with current x, i.e. x1 becomes equal to x. How do I make x1 to retain its value.

Upvotes: 0

Views: 146

Answers (3)

Blind Fish
Blind Fish

Reputation: 998

You need to post a bit more of your code. Based on what you have I don't see how this could accomplish what you want. Let's say the value of $x is 4. You run your query and $x is now 7. You then set the value of $_SESSION['$x1'] to 7 and save it. But after the refresh you are pulling that value of $x1, which is 7, and immediately resetting to $x. Why? It already has the value you wanted, 7, which is the previous value of $x. You are then going to set $x, which is now 7, to whatever number you pull from the server and the previous value is lost forever.

Upvotes: 0

QuantumRob
QuantumRob

Reputation: 2924

x1 should be retaining it's value from each call in the session. You're overwriting it though immediately with $x from what I see here.

If you're posting your $x variable across compare $x to $_SESSION and look at the two values before you overwrite it. Output the $_SESSION['x1'] before you write to it. You should see the previous value in there before you overwrite it.

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131841

The most obvious solution: Put the values into the session at the end of the request.

session_start();  
if(!isset($_SESSION['x1']))
    $_SESSION['x1'] = 0;

// your code here

$_SESSION['x1'] = $x;
exit; // Not really, just to clarify, that the script should end here
      // or at least its not that important, what comes next

Upvotes: 4

Related Questions