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:

  1. In the HTML form element, set the action attribute to the current page's URL, and set the method attribute to "post":
<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:
<?php

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

Watch a course Learn object oriented PHP

  1. Inside the if statement, process the form data and perform any desired actions, such as saving to a database or sending an email.

  2. To display the form again after submission, you can include the form HTML code inside the if statement, like this:

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 usknow if you have any questions.