Page 1 of 1

Basic session question

Posted: Sun Jan 14, 2007 5:13 pm
by psurrena

Code: Select all

if (isset($_POST['add'])) {				
	$fname = $_POST['fname'];
	$_SESSION['fname'] = $fname;
	header ('location:test2.php');
}

Everything works, I was just wondering why

Code: Select all

$_SESSION['fname'] = $fname;
works but

Code: Select all

$fname=$_SESSION['fname'];
does not...

Posted: Sun Jan 14, 2007 5:16 pm
by decipher

Code: Select all

$fname=$_SESSION['fname'];
will not work if $_SESSION['fname'] has not been set

you can use the following to set $fname to the value of the session if it exists, else set a default value.

Code: Select all

$fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : "nothing";

Posted: Sun Jan 14, 2007 6:31 pm
by Ollie Saunders
session_start() ?

Posted: Sun Jan 14, 2007 6:42 pm
by iknownothing
by looking at your example, you want the contents of $fname in your session variable. The way that it is in your example works because $fname has been given a value, then is passing it on to the session variable, the other way will not work because there is no data within the session variable at the time to give its data to $fname.

If you wanted to get the session variable data on a separate page, after the first example has been run, then you could use the second example to put your session data into the $fname variable

Posted: Sun Jan 14, 2007 7:17 pm
by psurrena
Makes sense - thanks a lot!