Part 8 : PHP tutorial for kids and beginners


Part 8: Forms and Form Handling in PHP

Welcome back to our PHP programming tutorial series! 🎉 In Part 7, we explored functions in PHP, learning how to define functions, use parameters, return values, and manage variable scope. Today, in Part 8, we’re diving into Forms and Form Handling in PHP. We’ll learn how to create HTML forms, process form data, and validate user input. Let’s get started!

What Are Forms?

Forms are used to collect user input on a web page. They are essential for creating interactive websites where users can submit information. In PHP, we can handle form submissions to process the data and perform various tasks, such as saving information to a database or sending an email.

Creating a Simple HTML Form

An HTML form is created using the <form> element. Inside this form, you can include various input fields like text boxes, radio buttons, checkboxes, and submit buttons.

Basic HTML Form Syntax:

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

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

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

In this example:

  • action="process.php" specifies the script that will handle the form data.
  • method="post" specifies that form data will be sent via the POST method.
See also  Understanding PHP Laravel Database Migration Commands

Processing Form Data with PHP

When the form is submitted, the data is sent to the PHP script specified in the action attribute. You can access this data using the $_POST or $_GET superglobal arrays, depending on the form method used.

Example Form Handling Script (process.php):

<?php
    // Check if the form is submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Retrieve form data
        $name = $_POST['name'];
        $email = $_POST['email'];

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

In this example, $_POST['name'] and $_POST['email'] retrieve the data submitted by the form. htmlspecialchars() is used to prevent XSS (Cross-Site Scripting) attacks by escaping special characters.

Form Validation

Validating form data ensures that the input meets certain criteria before processing it. This step is crucial for maintaining data integrity and security.

Basic Form Validation Example:

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

        // Validate name
        if (empty($name)) {
            echo "Name is required.<br>";
        }

        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo "Invalid email format.<br>";
        }
    }
?>

In this example, we check if the name field is empty and if the email field contains a valid email address.

Form Handling with GET Method

You can also use the GET method to submit form data. The data is appended to the URL as query parameters.

Example HTML Form with GET Method:

<form action="process_get.php" method="get">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

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

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

Example Form Handling Script with GET Method (process_get.php):

<?php
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        $name = htmlspecialchars($_GET['name']);
        $email = htmlspecialchars($_GET['email']);

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

In this example, $_GET['name'] and $_GET['email'] retrieve the form data sent via the GET method.

See also  Authentication and Authorization in Laravel: A Comprehensive Guide

Adding Form Elements

Forms can include various input elements to collect different types of data:

  • Text Input: <input type="text" name="username">
  • Password Input: <input type="password" name="password">
  • Radio Buttons: <input type="radio" name="gender" value="male"> Male
  • Checkboxes: <input type="checkbox" name="subscribe" value="newsletter"> Subscribe to newsletter
  • Dropdown Menu: <select name="country"><option value="usa">USA</option><option value="canada">Canada</option></select>

Example with Multiple Form Elements:

<form action="process_form.php" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username">

    <label for="password">Password:</label>
    <input type="password" id="password" name="password">

    <p>Gender:</p>
    <input type="radio" id="male" name="gender" value="male">
    <label for="male">Male</label>
    <input type="radio" id="female" name="gender" value="female">
    <label for="female">Female</label>

    <p>Subscribe to newsletter:</p>
    <input type="checkbox" id="subscribe" name="subscribe" value="yes">
    <label for="subscribe">Yes</label>

    <label for="country">Country:</label>
    <select id="country" name="country">
        <option value="usa">USA</option>
        <option value="canada">Canada</option>
        <option value="uk">UK</option>
    </select>

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

Storing Form Data in a Database

To store form data in a database, you will need to connect to a MySQL database and perform an SQL INSERT operation.

Example Form Handling and Database Insertion (process_form.php):

<?php
    // Database connection
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "my_database";

    $conn = new mysqli($servername, $username, $password, $dbname);

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

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = $conn->real_escape_string($_POST['username']);
        $password = $conn->real_escape_string($_POST['password']);
        $gender = $conn->real_escape_string($_POST['gender']);
        $subscribe = isset($_POST['subscribe']) ? 1 : 0;
        $country = $conn->real_escape_string($_POST['country']);

        $sql = "INSERT INTO users (username, password, gender, subscribe, country)
                VALUES ('$username', '$password', '$gender', '$subscribe', '$country')";

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $conn->close();
    }
?>

In this example, form data is retrieved, escaped for security, and inserted into a users table in the database.

Example Form with All Concepts Combined

Here’s a full example of a form and its PHP handler:

<!DOCTYPE html>
<html>
<head>
    <title>PHP Form Handling</title>
</head>
<body>
    <h2>Registration Form</h2>
    <form action="process_form.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">

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

        <label for="password">Password:</label>
        <input type="password" id="password" name="password">

        <p>Gender:</p>
        <input type="radio" id="male" name="gender" value="male">
        <label for="male">Male</label>
        <input type="radio" id="female" name="gender" value="female">
        <label for="female">Female</label>

        <p>Subscribe to newsletter:</p>
        <input type="checkbox" id="subscribe" name="subscribe" value="yes">
        <label for="subscribe">Yes</label>

        <label for="country">Country:</label>
        <select id="country" name="country">
            <option value="usa">USA</option>
            <option value="canada">Canada</option>
            <option value="uk">UK</option>
        </select>

        <input type="submit" value="Submit">
    </form>
</body>
</html>
<?php
    // process_form.php

    $servername = "localhost";
    $username = "

root";
    $password = "";
    $dbname = "my_database";

    $conn = new mysqli($servername, $username, $password, $dbname);

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

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $conn->real_escape_string($_POST['name']);
        $email = $conn->real_escape_string($_POST['email']);
        $password = $conn->real_escape_string($_POST['password']);
        $gender = $conn->real_escape_string($_POST['gender']);
        $subscribe = isset($_POST['subscribe']) ? 1 : 0;
        $country = $conn->real_escape_string($_POST['country']);

        $sql = "INSERT INTO users (name, email, password, gender, subscribe, country)
                VALUES ('$name', '$email', '$password', '$gender', '$subscribe', '$country')";

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $conn->close();
    }
?>

Summary

In Part 8, we explored forms and form handling in PHP. We learned how to create HTML forms, process form data using PHP, validate user input, and store data in a database. Forms are a crucial part of web development, enabling user interaction and data collection.

See also  Comprehensive guide on Spatie Laravel Permission package in Laravel

What’s Next?

In Part 9, we will explore Working with Files in PHP. We’ll learn how to upload files, read from and write to files, and manage file operations.

Homework

  1. Create a Form: Design your own form with different types of input fields.
  2. Process Form Data: Write a PHP script to handle form submissions and perform basic validation.
  3. Database Integration: Extend your form to store submitted data in a MySQL database.

Feel free to leave comments if you have any questions or run into any issues. Happy coding! 🚀


Next Part Teaser

Stay tuned for Part 9: Working with Files in PHP, where we will explore file uploads, reading and writing files, and file management in PHP!

Additional Resources

If you want to explore more about forms and form handling in PHP, check out these resources:


Part 9 Teaser

Coming up next in Part 9: Working with Files in PHP, where we will explore file uploads, reading and writing files, and file management in PHP!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.