All TalkersCode Topics

Follow TalkersCode On Social Media

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

PHP Registration Form With Database

Last Updated : Jul 1, 2023

PHP Registration Form With Database

In this article we will show you the solution of PHP registration form with database, in this project, you will design and build a sign-up or registration form that will insert data into the database of our MySQL server automatically when a user fills out the form.

A simple approach:

The first thing we need to do is build the MySQL server database and a table to meet our specifications.

In order to connect to our MySQL server, we use the PHP method mysqli_connect(), which takes four parameters—our "servername," "username," "password," and "database."

We will now discuss the idea of how to create a registration form with a database using php with an example.

Step By Step Guide On PHP Registration Form With Database :-

<?php
$showAlert = false;
$showError = false;
$exists=false;
if($_SERVER["REQUEST_METHOD"] == "POST") {
    // Include file which makes the
    // Database Connection.
    include 'dbconnect.php';
    $username = $_POST["username"];
    $password = $_POST["password"];
    $cpassword = $_POST["cpassword"];
    $sql = "Select * from users where username='$username'";
    $result = mysqli_query($conn, $sql);
    $num = mysqli_num_rows($result);
    // This sql query is use to check if
    // the username is already present
    // or not in our Database
    if($num == 0) {
        if(($password == $cpassword) && $exists==false) {
            $hash = password_hash($password,
                                PASSWORD_DEFAULT);
            // Password Hashing is used here.
            $sql = "INSERT INTO `users` ( `username`,
                `password`, `date`) VALUES ('$username',
                '$hash', current_timestamp())";
            $result = mysqli_query($conn, $sql);
            if ($result) {
                $showAlert = true;
            }
        }
        else {
            $showError = "Passwords do not match";
        }
    }// end if
   if($num>0)
   {
      $exists="Username not available";
   }
}//end if
?>
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1,
        shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
        crossorigin="anonymous">
</head>
<body>
<?php
    if($showAlert) {
        echo ' <div class="alert alert-success
            alert-dismissible fade show" role="alert">
            <strong>Success!</strong> Your account is
           created and you can login.
            <button type="button" class="close"
                data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
        </div> ';
    }
    if($showError) {
        echo ' <div class="alert alert-danger
            alert-dismissible fade show" role="alert">
        <strong>Error!</strong> '. $showError.'
       <button type="button" class="close"
            data-dismiss="alert aria-label="Close">
            <span aria-hidden="true">×</span>
       </button>
     </div> ';
   }
    if($exists) {
        echo ' <div class="alert alert-danger
            alert-dismissible fade show" role="alert">
        <strong>Error!</strong> '. $exists.'
        <button type="button" class="close"
            data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button>
       </div> ';
     }
?>
<div class="container my-4 ">
    <h1 class="text-center">Signup Here</h1>
    <form action="signup.php" method="post">
        <div class="form-group">
            <label for="username">Username</label>
        <input type="text" class="form-control" id="username"
            name="username" aria-describedby="emailHelp">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" class="form-control"
            id="password" name="password">
        </div>
        <div class="form-group">
            <label for="cpassword">Confirm Password</label>
            <input type="password" class="form-control"
                id="cpassword" name="cpassword">
            <small id="emailHelp" class="form-text text-muted">
            Make sure to type the same password
            </small>
        </div>
        <button type="submit" class="btn btn-primary">
        SignUp
        </button>
    </form>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="
https://code.jquery.com/jquery-3.5.1.slim.min.js"
    integrity="
sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
    crossorigin="anonymous">
</script>
<script src="
https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity=
"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous">
</script>
<script src="
https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
    integrity=
"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
    crossorigin="anonymous">
</script>
</body>
</html>
  1. The first step is to initialize some variables, such as $showAlert, $showError, and $exists to false. According to the result of the user's attempt to register, these messages will be displayed.
  2. The next step is to check the REQUEST_METHOD variable to see if the user has completed the signup form. When it is "POST", we proceed with processing the form submissions.
  3. In addition, we include a file called "dbconnect.php" that handles database connections.
  4. By grabbing the values of the "username", "password", and "cpassword" fields in the form, we are able to retrieve the user's input.
  5. To check if the username already exists in the database, we perform a SQL query. A new record will be inserted into the "users" table if it does not already exist.
  6. In this example, we are hashing the user's password using password_hash(). Using this approach, passwords are stored securely in the database.
  7. In the event that the insertion of the new user record is successful, we set $showAlert to true. Users will receive a success message as a result of this action.
  8. Our code sets $showError to "Passwords do not match" if the user's passwords do not match. When this happens, a message will be displayed to the user.
  9. Whenever the $exists variable contains a username that already exists, it displays "Username not available". When this happens, a message will appear telling the user that something went wrong.
  10. After using the echo statement and HTML markup to output the appropriate message(s), we return the results to the user.
  11. Our website displays a form for users to enter their desired username and password.
  12. In the same way described above, when a user fills out the form, the data is sent to the same page (signup.php).
  13. In addition, we include the JavaScript files that are required by Bootstrap to function correctly.

Conclusion :-

As a result, we have successfully learned how to create a php registration form with a database.

By following the previous tutorial, you have successfully created a Login System and a Registration System with PHP and MySQL.

If you want to use the code in this tutorial in your own project, you are welcome to adapt it. Just keep in mind that this is just a secure base from which you can work.

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