Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Saving a value in a session variable for use nex time round 1

Status
Not open for further replies.

Mike Lewis

Programmer
Jan 10, 2003
17,485
9
38
Scotland
www.ml-consult.co.uk
I have just got back to PHP after an absence of several years, and am having a little difficulty.

This is what I want to do:

1. Display a form, which includes a text box. Have the user fill in the text box with a value, and hit Submit.

2. The form calls a routine that processes the entered value in some way.

3. The procedure displays its results, on the same page as the form.

This is what I have got so far (highly simplified, with all extraneous code eliminated). (The page is named postcode.php.)

PHP:
<?php session_start(); ?>
..
..
<?php

// display the form
$lookup_form = 
  '<form action = "postcode.php" method="post">
    <input type = "text" name = "postcode" />
    <input type = "submit" name = "submit_button" value = "Submit" />
  </form>' ;
  
  echo $lookup_form ;
  
if(isset($_POST['submit_button']))
  {	
  if (isset($_POST['postcode']))
    {
    // beautify the value that the user entered
    $postcode = trim(strtoupper($_POST['postcode']));
	
    // code goes here to process the value; stores the result in $result
    // ...
    // ...

    // display the result
    echo $result;
      }
    else
     {
      echo '<p>Please enter your postcode.</p>';
     }
   }
?>

That works perfectly ...

... except for one small detail. When the user clicks the Submit button, the page is redisplayed. The input box is now empty. That's what you would expect. But I'd really like it to continue to show the value that the user entered, so that the user can edit it if he made a mistake when typing it.

So I thought I would simply store the value in a session variable, and use that value as the value attribute of the input box the next time round. I amended the code as follows:

PHP:
<?php session_start(); ?>
..
..
<?php

// display the form
$lookup_form = 
  '<form action = "postcode.php" method="post">
    <input type = "text" name = "postcode" value = "' [b]. $_SESSION['prev_postcode'] .[/b] '" />
    <input type = "submit" name = "submit_button" value = "Submit" />
  </form>' ;
  
  echo $lookup_form ;
  
if(isset($_POST['submit_button']))
  {	
  if (isset($_POST['postcode']))
    {
    // beautify the value that the user entered
    $postcode = trim(strtoupper($_POST['postcode']));
	
[b]    // store it in a session variable for next time
    $_SESSION['prev_postcode'] = $postcode ;[/b]
    
    // code goes here to process the value; stores the result in $result
	// ...
	// ...

    // display the results
    echo $result;
      }
    else
     {
      echo '<p>Please enter your postcode.</p>';
     }
   }
?>

But that doesn't quite work.

This is what I am seeing:

1. The user enters A and hits Submit.

2. The page displays the results for A, but the input box is now empty.

3. The use enters B and hits Submit.

4. The page displays the results for B, but the input box now contains A.

In other words, the input box always shows the value from the last query but one, not the immediately previous query. I can't understand why that is happening or what I can do to fix it. Any help would be appreciated.

For what it's worth, I'm using PHP 5.2.6, under a local Apache server on a Windows PC.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads
 
Well, you do need to capture and set the new values of the variable before you can display them.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
When you submit the form the page reloads. The fist thing that happens is you attempt to display the value from your session. Then you run your other PHP code and store the value you got in the session. However your form section has already been parsed.

You are storing the variable after you try to display it. So the first time around it has no value, the second time around it has the previous value until you change it a little further down.

Move your session storing code to before the form. OR use the value from the $_POST directly instead. Either way you need to get it before you display the form.


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I'm adding to the advice above, not contradicting it.

if you're just starting out again, consider starting with some solid profiling techniques that will speed your development and help you make much better code.

by profiling I mean
1. break your application down into entities and map each entity to a product.
2. typically an entity might map closely to a mysql table. but it is also likely that an entity will be a superset of a table. for example a user entity might map to a user table, an address table, an email table, a login table etc and then there will (or may) be join tables between the two as well (if you imagine that an address might be a many to many relationship with users).

in the example below I am treating the form as an entity; and that's ok too but not my preference as modelling a form is closer to the presentation layer than entity models (imo) should typically be. However, a form's data (and thus default data) should be obtainable from an entity class.

Confused? sorry - maybe this code will help

Code:
<?php
/*	instantiate the session */
if(session_id() == '') session_start();  //good practice to check whether a session exists before starting it


/* create a class that maps to your form */
/*
it is a good idea to have a base class that you can extend from
then you can have lots of forms that can use the same base
you can also use the loader/base class to automate the save/update
actions
*/
class loader{
	
	public function __construct(){
		$this->load();
	}
	
	public function load($data = array()){
		foreach($this->fields as $field):
			if(isset($data[$field])):
				$this->$field = $data[$field];
			else:
				$this->$field = '';
			endif;
		endforeach;
	}
}
class myForm extends loader{
	
	public $fields = array('postcode');
	
}

/* function to display form */
function displayForm($myForm){
?>
<!DOCTYPE HTML>
<html>
<head><title>My Form</title></head>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="post">
    <input type = "text" name = "postcode" value = "<?php echo $myForm->postcode;?>" />
    <input type = "submit" name = "submit_button" value = "Submit" />
    <input type="hidden" name="action" value="save" />
</form>
</html>
<?php
}
$action = isset($_POST['action']) ? strtolower(trim($_POST['action'])) : '';


switch($action):
	case 'save':
		$myForm = new myForm;
		$myForm->load($_POST);
		//do something with myForm, like save to a database
		
		/* save form to the session store */
		$_SESSION['myForm'] = $myForm;
		
		session_write_close(); //good idea to do this when debugging
		displayForm( $myForm );
		break;
	
	default:
		if(isset($_SESSION['myForm'])):
			$myForm = $_SESSION['myForm'];
		else:
			$myForm = new myForm;
		endif;
		session_write_close(); //good idea to do this when debugging
		displayForm( $myForm );
		break;
endswitch;
?>
 
Thank you all for your replies.

Vacunita, your explanation is crystal clear. I moved the code as you suggested, and it now works perfectly.

Jpadie, what you are saying makes good sense. I'm familiar (from other development tools) with the concepts you describe. At present, I am only dabbling in PHP, but when I'm ready for a major project, I'll take it all on board.



__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top