W3docs

PHP form - on submit stay on same page

To stay on the same page after a form submission in PHP, you can use the following steps.

To stay on the same page after a form submission in PHP, you can use the following steps:

  1. In the HTML form element, set the action attribute to the current page's URL, and set the method attribute to "post":

Example of a form action in HTML and PHP

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
  1. In the PHP code for the page, check if the form has been submitted using the $_SERVER['REQUEST_METHOD'] variable:

How to check if a form has been submitted in PHP?

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // form has been submitted, process the data
}
  1. Inside the if statement, process the form data and perform any desired actions, such as saving to a database or sending an email. To preserve user input after submission, set the value attribute of each input field to the corresponding $_POST variable.
  2. To display the form again after submission, you can include the form HTML code inside the if statement, like this:

How to stay on the same page after a form submission in PHP?

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // form has been submitted, process the data

  // display the form again
  ?>
  <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
    <!-- form fields go here -->
  </form>
  <?php
} else {
  // form has not been submitted, display the form
  ?>
  <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
    <!-- form fields go here -->
  </form>
  <?php
}

This will display the form either before or after submission, depending on whether the form has been submitted or not.

We hope this helps! Let us know if you have any questions.