How can I retain the selected option in a dropdown list even after refreshing the page in PHP?
When a page is refreshed, the selected option in a dropdown list is reset to its default value. To retain the selected option even after refreshing the page in PHP, you can store the selected value in a session variable and set the selected attribute in the dropdown list based on this stored value.
<?php
session_start();
$selectedOption = isset($_POST['dropdown']) ? $_POST['dropdown'] : (isset($_SESSION['selectedOption']) ? $_SESSION['selectedOption'] : '');
if(isset($_POST['submit'])){
$_SESSION['selectedOption'] = $_POST['dropdown'];
}
?>
<form method="post">
<select name="dropdown">
<option value="option1" <?php if($selectedOption == 'option1') echo 'selected'; ?>>Option 1</option>
<option value="option2" <?php if($selectedOption == 'option2') echo 'selected'; ?>>Option 2</option>
<option value="option3" <?php if($selectedOption == 'option3') echo 'selected'; ?>>Option 3</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
Keywords
Related Questions
- What are the best practices for handling session variables in PHP, especially when dealing with multi-dimensional arrays?
- What are the benefits of combining arrays into multidimensional arrays in PHP, and how can it be done effectively?
- What are the potential pitfalls of using incorrect variable names in a PHP session?