Create Registration form with MySQL and PHP

In membership-based website registration and login page is common.

User needs to create a new account and login to the website to access services and manage its account.

In this tutorial, I show how you can create a signup page with MySQL and PHP.

Create registration form with MySQL and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML & PHP
  4. Form Submit
  5. Demo
  6. Conclusion

1. Table structure

I am using users table in the example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `fname` varchar(80) NOT NULL,
  `lname` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for database configuration.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML & PHP

Create a <form method='post' action='' >.

If $error_message is not empty then display $error_message value on the screen. Similarly, if $success_message is not empty then display the $success_message value on the screen.

NOTE – Value is assigned to $error_message and $success_message variable on <form > submit according to conditions.

Add input fields for entering – first name, last name, email, password, and confirm password.

Also, add a submit button.

Completed Code

<?php 
include "config.php";
?>
<!DOCTYPE html>
<html>
  <head>
    <title>Create Registration form with MySQL and PHP</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

  </head>
  <body>
    <div class='container'>
      <div class='row'>

        <div class='col-md-6' >

          <form method='post' action=''>

            <h1>SignUp</h1>
            <?php 
            // Display Error message
            if(!empty($error_message)){
            ?>
            <div class="alert alert-danger">
              <strong>Error!</strong> <?= $error_message ?>
            </div>

            <?php
            }
            ?>

            <?php 
            // Display Success message
            if(!empty($success_message)){
            ?>
            <div class="alert alert-success">
              <strong>Success!</strong> <?= $success_message ?>
            </div>

            <?php
            }
            ?>

            <div class="form-group">
              <label for="fname">First Name:</label>
              <input type="text" class="form-control" name="fname" id="fname" required="required" maxlength="80">
            </div>
            <div class="form-group">
              <label for="lname">Last Name:</label>
              <input type="text" class="form-control" name="lname" id="lname" required="required" maxlength="80">
            </div>
            <div class="form-group">
              <label for="email">Email address:</label>
              <input type="email" class="form-control" name="email" id="email" required="required" maxlength="80">
            </div>
            <div class="form-group">
              <label for="password">Password:</label>
              <input type="password" class="form-control" name="password" id="password" required="required" maxlength="80">
            </div>
            <div class="form-group">
              <label for="pwd">Confirm Password:</label>
              <input type="password" class="form-control" name="confirmpassword" id="confirmpassword" onkeyup='' required="required" maxlength="80">
            </div>

            <button type="submit" name="btnsignup" class="btn btn-default">Submit</button>
          </form>
        </div>

     </div>
    </div>
  </body>
</html>

4. Form Submit

Add the following code in <head> section.

On <form > submit assign $_POST values in variables.

Validate the values –

To check the input values are valid or not created a $isValid = true variable. If any validation is false then assign false to $isValid and record not inserted.

  1. First, check if all values are entered or not. If not entered then assign false to $isValid and "Please fill all fields." to $error_message.
  2. Check if entered password and confirm password are equal or not. If not equal then assign false to $isValid and "Confirm password not matching." to $error_message.
  3. Check if $email variable value has a valid email or not. If not valid then assign false to $isValid and "Invalid Email-ID." to $error_message.
  4. Check if email-id already exists in users table or not. If available then assign false to $isValid and "Email-ID is already existed." to $error_message.

If $isValid has true value then insert a new record in the users table and assign "Account created successfully." to $success_message.

Completed Code

<?php 
$error_message = "";$success_message = "";

// Register user
if(isset($_POST['btnsignup'])){
   $fname = trim($_POST['fname']);
   $lname = trim($_POST['lname']);
   $email = trim($_POST['email']);
   $password = trim($_POST['password']);
   $confirmpassword = trim($_POST['confirmpassword']);

   $isValid = true;

   // Check fields are empty or not
   if($fname == '' || $lname == '' || $email == '' || $password == '' || $confirmpassword == ''){
     $isValid = false;
     $error_message = "Please fill all fields.";
   }

   // Check if confirm password matching or not
   if($isValid && ($password != $confirmpassword) ){
     $isValid = false;
     $error_message = "Confirm password not matching";
   }

   // Check if Email-ID is valid or not
   if ($isValid && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
     $isValid = false;
     $error_message = "Invalid Email-ID.";
   }

   if($isValid){

     // Check if Email-ID already exists
     $stmt = $con->prepare("SELECT * FROM users WHERE email = ?");
     $stmt->bind_param("s", $email);
     $stmt->execute();
     $result = $stmt->get_result();
     $stmt->close();
     if($result->num_rows > 0){
       $isValid = false;
       $error_message = "Email-ID is already existed.";
     }

   }

   // Insert records
   if($isValid){
     $insertSQL = "INSERT INTO users(fname,lname,email,password ) values(?,?,?,?)";
     $stmt = $con->prepare($insertSQL);
     $stmt->bind_param("ssss",$fname,$lname,$email,$password);
     $stmt->execute();
     $stmt->close();

     $success_message = "Account created successfully.";
   }
}
?>

5. Demo

View Demo


6. Conclusion

In this tutorial, I only cover the registration system and if you want to know how to create a login page then you can view the following tutorial.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

18 thoughts on “Create Registration form with MySQL and PHP”

  1. Hi Yogesh, I’ve learned much from your posts. I’m wanting to make a sign up form for training in different city locations all on one web page. But i wondered if there is a way to limit sign ups per city. E.g if 25 people have already signed up for Denver, post message that says “Sorry sign up is full for this location.” Is this possible to limit number of sign-ups? Thx!

    Reply
    • Hi Brian,
      Yes, you can restrict it. When form is submitted then check total entries on a submitted city. If it is equal to 25 then skip record insertion and display your message.

      Reply
  2. A bunch of code is showing up on the web page after i inserted the last code block. It starts with prepare(“SELECT * FROM users WHERE email = ?”); Do you know what i could be doing wrong. I have the files in the htdocs folder on MAMP.

    Reply
  3. i figured out i needed to rename the file with .php instead of html. So anyway it looks like it should work, but nothing gets added to the table. I get the ‘Success’ message, but when i check the table it’s empty. Any idea?

    Reply
  4. Hi Yogesh, I added a record into the table manually. I then tried to enter a record on the form using the same email, and it recognized that the email was a duplicate. So i know it’s hitting the DB. Any But i still can’t get the data to enter the table when i do a new entry from the form. Are you able to check code?

    Reply
    • Hi Brian,
      I think there is some issue in your insert query.
      Replace the following code in the insert record section –

      $stmt->execute();

      with this –

      if (!$stmt->execute()) {
      echo “Execute failed: (” . $stmt->errno . “) ” . $stmt->error;
      }

      Reply
  5. I got it to work! Thanks. I ended up just deleting the DB and starting over. Sorry for all the comments. Great tutorial! Thank you!

    Reply
  6. Hello,
    Can anyone fix this error?
    50COUNT:23
    Warning: Cannot modify header information – headers already sent by (output started at /home/bitswgps/public_html/member/actions/signup_action.php:26)
    /home/bitswgps/public_html/member/actions/signup_action.php on line 49

    Reply
  7. When I click submit the script does nothing; no error message and no success message. Nothing is created in the database. I see that the action=” “; does not redirect to a php handler page? Could this be the issue?

    Reply
    • Definitely, that’s the issue. The action attribute of your form should have the file path to your validation file or if you have your php validation code on the same page as your form then you should paste in this code:
      <form method="POST" action="”>

      Reply
  8. Much obliged for the article. I have checked numerous articles on this point however couldn’t locate a total clarification and afterward I discovered your article. Clearly, you more likely than not done incredible examination for this article.

    Reply
  9. Fatal error: Uncaught Error: Call to a member function execute() on bool in D:\xampp\htdocs\htmlearnschool\register.php:67 Stack trace: #0 {main} thrown in D:\xampp\htdocs\htmlearnschool\register.php on line 67

    ————
    i dont get what im doing wrong, can someone help me please?

    Reply
  10. hello, thanks for all. I have learned and installed your code, works fine, when a user is logged-in, i have redirrect to a page. ( a phtml one ) . It’s ok.
    But, i don’t found the solution to have a text, or icon who says ” hello NAME” in my page, looks like { user logged-in => Check whether user is logged in or not => print result as a logo in my redirrected page when user succefully loggin }…

    Thanks everyone for help 🙂

    Reply

Leave a Comment