How to process multiple html form values in php?

Member

by denis , in category: PHP General , 4 months ago

How to process multiple html form values in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 4 months ago

@denis 

To process multiple HTML form values in PHP, you can use the $_POST or $_GET superglobal arrays to retrieve the form data and loop through the values.


Here are the steps to follow:

  1. Create an HTML form using the element with the method attribute set to "POST" or "GET". Each input element should have a unique name attribute.


Example:

1
2
3
4
5
6
<form method="post" action="process.php">
   <input type="text" name="name[]" />
   <input type="text" name="email[]" />
   <!-- Add more input fields as needed -->
   <input type="submit" value="Submit" />
</form>


  1. In the action attribute of the form, specify the PHP file (process.php) where you want to process the form data.
  2. In the PHP file (process.php in this case), use the $_POST or $_GET superglobal arrays to access the form values. Since the form fields have square brackets [] in their names, PHP will automatically convert them into arrays.


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Retrieve the form data
    $names = $_POST["name"];
    $emails = $_POST["email"];

    // Loop through the form values
    for ($i = 0; $i < count($names); $i++) {
        $name = $names[$i];
        $email = $emails[$i];

        // Process each value as needed
        echo "Name: $name, Email: $email<br>";
    }
}


Note: Make sure to validate and sanitize the form values before using them to prevent security vulnerabilities, such as SQL injection or cross-site scripting (XSS) attacks.