bonny
bonny

Reputation: 3247

how to change value of a session?

I would like to know how I can change a value in a session key.

I have two pages:

Page 1 to change the settings:

<?php       
session_start();

if (isset($_POST['one']) ){
    $_SESSION['pref_lang'] = 'one';
}
if (isset($_POST['two']) ){
    $_SESSION['pref_lang'] = 'two';
}
?>

The HTML:

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">     
    <input type="submit" id='one' name='one' value="one"/>
    <input type="submit" id='two' name='two' value="two"/>
</form>

Page 2 will be just to display the session:

<?php
session_start();
print_r($_SESSION);
?>

and even a third to destroy the session.

The problem is when I call the first page to change the session value it will not change it. If there is someone who could tell what's wrong with this I really would appreciate.

UPDATE:

okay, it seems like i do something wrong on page 2. when echo out print_r Session on page 1, that page where i have placed the forms- everything works fine. but when calling page 2, which should usually tell me whats in the session, it just will display the content of the session. strange about that is, that i when calling page 3 for destroying the session, on page 1 it will be displayed that the session is empty but on page 2 it wont change anything. even when i will change the values on page 1, it wont change it on page 2, but it will display the change on page1????

Upvotes: 0

Views: 238

Answers (2)

PhearOfRayne
PhearOfRayne

Reputation: 5050

Forms will post all fields they contain. So basically your overriding the session. If you were to try something like this:

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">     
    <input type="submit" id='one' name='one' value="one"/>
</form>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">     
    <input type="submit" id='two' name='two' value="two"/>
</form>

You will see how your second form will override the session variable.

Upvotes: 1

Darius
Darius

Reputation: 612

In your form, you're sending both values ($_POST['one'] and $_POST['two']).

Change it to what I have below:

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">     
    <input type="submit" id='one' name='one' value="one"/>
</form>    

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">     
   <input type="submit" id='two' name='two' value="two"/>
</form>  

The above just separates the forms into two, and sends the values individually. Consider revising your program or using radio buttons to discern between each selection. http://www.w3schools.com/html/html_forms.asp

Upvotes: 0

Related Questions