Building Dynamic Forms with PHP: A Comprehensive Tutorial
Tags: tutorial, php, database, html
Published: 2024-05-14 23:00:44

Welcome to our tutorial on creating dynamic forms using PHP! Forms are an integral part of web development, facilitating user interaction and data collection. Whether you're building a simple contact form or a complex registration system, PHP empowers you to create dynamic and interactive web forms effortlessly.

In this tutorial, we will walk you through the process of building PHP forms from scratch. We'll cover essential concepts, such as form structure, form handling, validation, and processing user input. By the end, you'll have a solid understanding of how to create robust and secure forms that meet your project requirements.


the Structure of HTML Forms:

SIGN UP form :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7zhu4smy5edecthdgae.png)

LOG IN form :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0jis1z3y1n3megz9hi0.png)

DASHBOARD :


PHP sign up part:

In this part we will connect our forms to the database, create the the database, create its tables and then use a catch to handle errors 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uieud8fnui4p3b8i5vwc.png)

First of all, we include the connexion page to our sign in page, then we initialize the error messages variables so we could use them in the validation process , after that we started our program by a condition that checked if our request methot is post, then we created three variables one the username input and the other for the password inoput and the last one for the confirmation password input and stored the values into them.
then we moved forward to the verification process, first we started by giving our inputs field an empty condition , so if any input was empty we will display an error message in the error message variables, then we put a following condition that check if the input value meet the wanted syntax .
and after the verification succuded we wrote a code that insert the input values in the database that we included to this page earlier.
and finaly we made a header that took us to the log In page in case of the the program succued ift it's not show a an error message.


PHP log in part(explanation included in code comments) :

```
<?php 
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: planetscards.php");
    exit;
}

// Include config file
require_once "dbconnexion.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        
        $_SESSION['username_err'] = "Please enter username.";
        header("location: connection.php");
        exit;
    } else{
        $username = trim($_POST["username"]);
    }
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $_SESSION['password_err'] = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = :username");
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        // checking if password is the same password hashed in database 
        if ($user && password_verify($password, $user['password'])) {
            //if true checking if checkbox remember me isset
            if (!isset($_POST['remember_me'])) {
            // if false stocking cookies 
            $expireTime = time() + 86400 * 30;
            setcookie('username', $user['username'], $expireTime);
            setcookie('email', $user['email'], $expireTime);
        }//if true stocking sessions 
        $_SESSION['id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['email'] = $user['email'];
        header("location: planetscards.php");
      exit;}
         else{
            $_SESSION['password_err'] = "The password you entered was not valid.";
            header("location: connection.php");
            exit;
            
        }        
        // Close statement
        unset($stmt);
    
    }
    
    // Close connection
    unset($pdo);
}
```

```
<?php
// Include database connection file
require_once "dbconnexion.php";

// Define variables and initialize with empty values
$email = $new_password = $confirm_new_password = "";
$email_err = $new_password_err = $confirm_new_password_err = "";

// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate email
    if (empty(trim($_POST["email"]))) {
        $email_err = "Please enter your email.";
    } else {
        $email = trim($_POST["email"]);
    }

    // Validate new password
    if (empty(trim($_POST["new_password"]))) {
        $new_password_err = "Please enter your new password.";
    } elseif (strlen(trim($_POST["new_password"])) > 10) {
        $new_password_err = "Password limit is 10 please enter a valid passsword";
    } else {
        $new_password = trim($_POST["new_password"]);
    }

    // Validate confirm new password
    if (empty(trim($_POST["confirm_new_password"]))) {
        $confirm_new_password_err = "Please confirm your new password.";
    } else {
        $confirm_new_password = trim($_POST["confirm_new_password"]);
        if (empty($new_password_err) && ($new_password != $confirm_new_password)) {
            $confirm_new_password_err = "Passwords did not match.";
        }
    }

    // Check input errors before updating the database
    if (empty($email_err) && empty($new_password_err) && empty($confirm_new_password_err)) {
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE email = :email";

        if ($stmt = $pdo->prepare($sql)) {
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":email", $param_email, PDO::PARAM_STR);

            // Set parameters
            $param_email = $email;

            // Attempt to execute the prepared statement
            if ($stmt->execute()) {
                // Check if email exists, if yes then update the password
                if ($stmt->rowCount() == 1) {
                    $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $sql = "UPDATE users SET password = :password WHERE email = :email";

                    if ($stmt = $pdo->prepare($sql)) {
                        // Bind variables to the prepared statement as parameters
                        $stmt->bindParam(":password", $hashed_new_password, PDO::PARAM_STR);
                        $stmt->bindParam(":email", $param_email, PDO::PARAM_STR);

                        // Set parameters
                        $param_email = $email;

                        // Attempt to execute the prepared statement
                        if ($stmt->execute()) {
                            // Password updated successfully. Redirect to login page
                            header("location: connection.php");
                            exit();
                        } else {
                            echo "Oops! Something went wrong. Please try again later.";
                        }
                    }

                    // Close statement
                    unset($stmt);
                }
                unset($pdo);
            }
        }
    }
}
```

DASHBOARD :
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3y2ltbr35ddtsulwcbi5.jpg)

DASHBOARD PHP part :
This PHP code checks if a user is logged in by verifying the existence of cookies or session variables. If the user is logged in, it sets a welcome message with the user's name. If not, it redirects the user to a login page (connection.php).


The code starts a PHP session using session_start().
It initializes an empty string $p.
It checks if two cookies, username and id, are set. If they are:
It extracts the values from the cookies and sets them to $username and $userID.
It sets the welcome message $p to "Welcome <username>".
If the cookies are not set, it checks if a session variable id is set. If it is:
It extracts the values from the session variables and sets them to $username and $userID.
It sets the welcome message $p to "Welcome <username>".
If neither cookies nor session variables are set, it redirects the user to connection.php (likely a login page) using header("location: connection.php") and exits the script.
```
<?php
// Start the session
session_start();
$p = "";
if(isset($_COOKIE["username"]) && isset($_COOKIE["id"])){
    // If cookies are set, use cookie data
    $username = $_COOKIE["username"];
    $userID = $_COOKIE["id"];
    $p = "Welcome" . " " . $username;
} elseif(isset($_SESSION["id"])) {
    // If sessions are set, use session data
    $username = $_SESSION["username"];
    $userID = $_SESSION["id"];
    $p = "Welcome" . " " . $username;
} else {
    // If neither cookies nor sessions are set, redirect to login page
    header("location: connection.php");
    exit;
}
?>
```


Conclusion :
By the end of this tutorial, you'll have the skills and knowledge to create powerful and secure PHP forms for your web projects. Whether you're a beginner or an experienced developer, understanding how to build dynamic forms with PHP will significantly enhance your web development capabilities. Let's dive in and start building!