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
2009-10-27 17:58:31
thanks, its working. For combo boxes???? plz
Rajasekar
2009-10-27 18:01:02
Oh come on. You should be able to work that out for yourself, shouldn't you?
Pekka
2009-10-27 18:03:44
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
2009-10-27 18:04:10
pl help, i am a beginner
Rajasekar
2009-10-27 18:04:41
@Eli Can't believe I missed that. Thanks for pointing it out.
Mike B
2009-10-27 18:10:01
@ Mike, What for Combo boxes???
Rajasekar
2009-10-27 18:11:57
@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
2009-10-27 18:22:08
+1
A:
<input type='text' style='' name='' id='' class='' value='<?php echo(htmlspecialchars($_SESSION["Whatever"], ENT_QUOTES)); ?>' />
Eli
2009-10-27 18:02:25