PHP Form Handling

Learn how to handle forms in PHP, including processing, validation, and storing user input.

What is Form Handling?

Form handling in PHP refers to the process of collecting, validating, and processing user input submitted through an HTML form. This is essential for building interactive web applications.

Creating a Basic Form

Here’s a simple HTML form that collects a user's name and email:

<form action="form-handler.php" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <input type="submit" value="Submit">
</form>

Processing Form Data

Once the user submits the form, the data can be accessed in a PHP script using the $_POST or $_GET superglobal arrays, depending on the form method.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];

    echo "Name: " . htmlspecialchars($name) . "<br>";
    echo "Email: " . htmlspecialchars($email) . "<br>";
}
?>

Validating Form Data

Validation ensures that the data submitted meets specific criteria before processing it. Here’s how to perform basic validation:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));

    if (empty($name) || empty($email)) {
        echo "Both name and email are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
    } else {
        echo "Name: " . $name . "<br>";
        echo "Email: " . $email . "<br>";
    }
}
?>

Storing Form Data

Once the data is validated, you may want to store it in a database. Here’s a brief overview of how to connect to a MySQL database and insert data:

<?php
// Database connection
$conn = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));

    // Insert data
    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
$conn->close();
?>

Conclusion

Form handling in PHP is crucial for creating interactive web applications. By following best practices for validation and sanitization, you can ensure that user input is safely processed and stored. Always remember to check for errors and provide feedback to the user to enhance their experience.