All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Code For Registration Form With Database And Validation

Last Updated : Jul 1, 2023

PHP Code For Registration Form With Database And Validation

In this article we will show you the solution of PHP code for registration form with database and validation, continuing our earlier guide, Secure Login System with PHP & MySQL, this guide focuses on building a secure login system.

In this lesson, we'll build a safe registration form and implement fundamental validation.

A registration form is where visitors can register their details, which are subsequently stored in a MySQL database and used for authentication.

We will now discuss the idea of how to use php code for registration form with database and validation with example.

Step By Step Guide On PHP Code For Registration Form With Database And Validation :-

<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";
$name = $email = $mobileno = $gender = $website = $agree = "";
//Input fields validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//String Validation
    if (emptyempty($_POST["name"])) {
         $nameErr = "Name is required";
    } else {
        $name = input_data($_POST["name"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                $nameErr = "Only alphabets and white space are allowed";
            }
    }
    //Email Validation
    if (emptyempty($_POST["email"])) {
            $emailErr = "Email is required";
    } else {
            $email = input_data($_POST["email"]);
            // check that the e-mail address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email format";
            }
     }
    //Number Validation
    if (emptyempty($_POST["mobileno"])) {
            $mobilenoErr = "Mobile no is required";
    } else {
            $mobileno = input_data($_POST["mobileno"]);
            // check if mobile no is well-formed
            if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
            $mobilenoErr = "Only numeric value is allowed.";
            }
        //check mobile no length should not be less and greator than 10
        if (strlen ($mobileno) != 10) {
            $mobilenoErr = "Mobile no must contain 10 digits.";
            }
    }
    //URL Validation
    if (emptyempty($_POST["website"])) {
        $website = "";
    } else {
            $website = input_data($_POST["website"]);
            // check if URL address syntax is valid
            if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=_|!:,.;]*[-a-z0-9+&@#\/%=_|]/i",$website)) {
                $websiteErr = "Invalid URL";
            }
    }
    //Empty Field Validation
    if (emptyempty ($_POST["gender"])) {
            $genderErr = "Gender is required";
    } else {
            $gender = input_data($_POST["gender"]);
    }
    //Checkbox Validation
    if (!isset($_POST['agree'])){
            $agreeErr = "Accept terms of services before submit.";
    } else {
            $agree = input_data($_POST["agree"]);
    }
}
function input_data($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
    Name:
    <input type="text" name="name">
    <span class="error">* <?php echo $nameErr; ?> </span>
    <br><br>
    E-mail:
    <input type="text" name="email">
    <span class="error">* <?php echo $emailErr; ?> </span>
    <br><br>
    Mobile No:
    <input type="text" name="mobileno">
    <span class="error">* <?php echo $mobilenoErr; ?> </span>
    <br><br>
    Website:
    <input type="text" name="website">
    <span class="error"><?php echo $websiteErr; ?> </span>
    <br><br>
    Gender:
    <input type="radio" name="gender" value="male"> Male
    <input type="radio" name="gender" value="female"> Female
    <input type="radio" name="gender" value="other"> Other
    <span class="error">* <?php echo $genderErr; ?> </span>
    <br><br>
    Agree to Terms of Service:
    <input type="checkbox" name="agree">
    <span class="error">* <?php echo $agreeErr; ?> </span>
    <br><br>
    <input type="submit" name="submit" value="Submit">
    <br><br>
</form>
<?php
    if(isset($_POST['submit'])) {
    if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $websiteErr == "" && $agreeErr == "") {
        echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
        echo "<h2>Your Input:</h2>";
        echo "Name: " .$name;
        echo "<br>";
        echo "Email: " .$email;
        echo "<br>";
        echo "Mobile No: " .$mobileno;
        echo "<br>";
        echo "Website: " .$website;
        echo "<br>";
        echo "Gender: " .$gender;
    } else {
        echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
    }
    }
?>
</body>
</html>
  1. The registration form has input fields that need to be validated in this PHP script. Among the information requested on the form are the user's name, email address, mobile number, website URL, gender, and terms and conditions.
  2. Several PHP variables are defined as empty strings. These include $nameErr, $emailErr, $mobilenoErr, $genderErr, $websiteErr, and $agreeErr. A validating error message will be stored in these variables if any of the input fields fail to validate.
  3. When the script checks $_SERVER["REQUEST_METHOD", it determines whether the form has been submitted. As soon as the input fields have been validated, the input_data() function is called.
  4. When using the input_data() function, a security vulnerability can be prevented by trimming, stripping, and escaping special characters from user input.
  5. Script checks that only alphabets and spaces can be entered in the name field with the help of a regular expression. $nameErr is used to store error messages when the input doesn't pass validation.
  6. In order to make sure that the email address is well-formed, filter_var is used to validate it.
  7. Regular expressions are used to validate the mobile number field to allow only numeric values, and to check that the mobile number is at least 10 digits in length. In the event it fails validation, $mobilenoErr is set to contain an error message.
  8. We check the website URL field using a regular expression to make sure it is valid. The $websiteErr variable sets an error message if validation fails.
  9. The gender field is validated by checking if the input value is set. If it's not set, it sets an error message in $genderErr.
  10. The terms of service agreement field is validated by checking if the checkbox is checked. If it's not checked, it sets an error message in $agreeErr.
  11. After validation, the script checks if all the error messages are empty, indicating that all the input fields have passed validation. If yes, it displays a success message and shows the user's input. If there are errors, it displays an error message.
  12. The HTML form uses the POST method to submit the form data to the same page using the PHP_SELF constant to ensure the script runs on the same page. The input fields have their names set accordingly to be successfully retrieved in the PHP script.
  13. Finally, the script uses HTML to display the form and displays any error messages or success messages.

Conclusion :-

As a result, In this registration form in php and mysql with a validation tutorial, you have learned how to create a registration form and store data into a MySQL database.

Also, you have learned how to validate form data on the server side.

I hope this article on PHP code for registration form with database and validation helps you and the steps and method mentioned above are easy to follow and implement.