tags:

views:

286

answers:

2

I am having a search text box. In that box, I want to store the previous search value when the page is loaded next time. For that i created session for the textbox value when the search button is clicked. But i dont know how to replace the session value in the textbox when the page is next loaded. Help me. Any help will be highly appreciated.

+3  A: 
<?php
  session_start(); // must be before any other output

  $search_term = '';
  if (!empty($_SESSION['last_search_term']))
  {
    // Check for last search term and update the search_term var
    // Escaped from @Eli's suggestion - Thanks!
    $search_term = htmlspecialchars($_SESSION['last_search_term'], ENT_QUOTES);
  }
?>

<form method="get" action="page.php">
  <input type="text" name="query" value="<?php print $search_term; ?>" />
  <input type="submit" value="Search" />
</form>

<?php
  if (!empty($_GET['query'])) 
  {
    // Form submitted
    // Any necessary search logic here

    $_SESSION['last_search_term'] = $_GET['query'];
  }
?>

As stated in the comments, session_start() must be placed before any other output or you will be presented an error. The last PHP block could be above the form. It's up to you and your particular workflow.

Mike B
thanks, its working. For combo boxes???? plz
Rajasekar
Oh come on. You should be able to work that out for yourself, shouldn't you?
Pekka
Don't forget to escape the value when you put it into the HTML field value, or you will end up with half a value if somebody enters a value with a quote mark, and open yourself up to a few other probelms as well.
Eli
pl help, i am a beginner
Rajasekar
@Eli Can't believe I missed that. Thanks for pointing it out.
Mike B
@ Mike, What for Combo boxes???
Rajasekar
@Rajesekar - Are you using stackoverflow to help you learn how to program or as a crowdsourcing tool? I'm inclined not to write (more) code for you.
Mike B
+1  A: 
<input type='text'  style='' name='' id='' class='' value='<?php echo(htmlspecialchars($_SESSION["Whatever"], ENT_QUOTES)); ?>' />
Eli