How to Create a Simple Form and Handle Form Data in PHP

PHP helps to create a simple form and handle form data. PHP allows you to collect and process form data submitted by users through HTML forms.

Follow the steps below to create and handle a simple form in PHP

1.Create a Simple HTML Form

First, create a form that asks for user input, like a name.

<form method="POST" action="process.php">
<label for="name">Enter your name:</label>
  <input type="text" id="name" name="name">
  <button type="submit">Submit</button>
</form>
  • method=”POST” means data will be sent securely.
  • action=”process.php” means form data will be handled in process.php file.

2. Handle Form Data in PHP (process.php)

Now in process.php, get the data using $_POST.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
     // Get the value from input field
    $name = $_POST['name'];
// Display the name
    echo "Hello, " . htmlspecialchars($name);
}
?>

 

  • $_POST[‘name’] gets the input data.
  • htmlspecialchars() is used for security

 

3. Using $_GET Instead of $_POST

If you use method=”GET” in the form, you will collect data like this:

<?php
// Get the value if form submitted with GET
$name = $_GET['name'];
echo "Hello, " . htmlspecialchars($name);
?>

 

  • GET method shows data in URL, while POST does not.

 

Summary

Create a simple form and handle form data in PHP is simple. You design the form using HTML and then capture user input in PHP using $_POST or $_GET.

Read Also :-
How to Connect PHP with MySQL Database

The Role of $wpdb for Custom Queries in WordPress

Also visit:
http://www.inimisttech.com/

Leave a Reply