How can hidden fields in a form be used to track the current page and navigate between multiple pages of a form in PHP?
To track the current page and navigate between multiple pages of a form in PHP, hidden fields can be used to store the current page number. These hidden fields can be updated as the user navigates through the form, allowing the PHP script to determine which page to display next based on the current page number.
<?php
// Retrieve the current page number from the hidden field or set it to 1 if not set
$current_page = isset($_POST['current_page']) ? $_POST['current_page'] : 1;
// Process form submission based on the current page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($current_page) {
case 1:
// Process page 1 form data
break;
case 2:
// Process page 2 form data
break;
// Add more cases for additional pages as needed
}
// Update the current page number for the next iteration
$current_page++;
}
?>
<form method="post">
<!-- Hidden field to store the current page number -->
<input type="hidden" name="current_page" value="<?php echo $current_page; ?>">
<?php if ($current_page == 1): ?>
<!-- Page 1 form fields -->
<?php elseif ($current_page == 2): ?>
<!-- Page 2 form fields -->
<?php endif; ?>
<!-- Submit button to process the form -->
<button type="submit">Next</button>
</form>