PHP MySQLi SignUp or Registration Page/Form

This article is created to describe, how a registration form or page can be created using PHP MySQLi object-oriented and procedural script.

But before creating a registration form, to allow user to register, to store their data in the database. We need to create a database, and then create a table inside it, to store the user registration data in the table of that database.

Note - A database consists of one or multiple tables. A table consists of information in the form of rows (records) and columns (fields).

Note - I have created a database named fresherearth. In this database, a table named users is created with following columns:

Here is the snapshot of the table available in my database:

php mysql registration page table

You can either follow the manual way to create this table, or can use the following SQL statement:

CREATE TABLE users (
    ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    FirstName VARCHAR(20),
    LastName VARCHAR(20),
    Username VARCHAR(30) NOT NULL,
    Email VARCHAR(30) NOT NULL,
    Password VARCHAR(16) NOT NULL )

You can also use your own custom table with custom fields/columns. But I recommend to go with same, to understand the things provided here, much easier. After learning all the things given here, you can proceed to modify and implement further with your own requirement.

PHP MySQLi Simple Registration Form

Before creating a complete version of registration form or page, using PHP MySQLi script. Let's first create the simple and basic one. To create a simple and basic registration form, we need the following two steps to do:

PHP MySQLi Registration Form - Step No.1

Now let's create an HTML form to allow user to enter the data to register on the website. Here I am going to create simple and basic HTML form to get the data from user. Later I will create the impressive one.

<H2>User Registration Form</H2>

<FORM action="register.php" METHOD="post">
   First Name: <INPUT type="text" name="firstname"><BR>
   Last Name: <INPUT type="text" name="lastname"><BR>
   Username: <INPUT type="text" name="username" required><BR>
   Email: <INPUT type="text" name="email" required><BR>
   Password: <INPUT type="text" name="password" required><BR>
   
   <BUTTON type="submit">Register</BUTTON><HR>
   
   <P>Already registered ? <a href="login.php">Login</a></P>
</FORM>

The output produced by above user registration form code, is shown in the snapshot given below:

php mysql signup form page

Notice the register.php page, assigned to FORM action. That is, whatever the user enters into the form, the form data will be send to the register.php page, after submitting the form, by clicking on the Register button.

Now fill the data in this user registration form, and hit on the Register button to register. Here is the new snapshot of the same registration form, after filling the data:

php mysql registration form

But before clicking on the Register button, I have to create a register.php page, that will handle the form data and send the data into the database. Let me create the register.php page.

PHP MySQLi Registration Form - Step No.2

I am going to create the register.php page, using both PHP MySQLi Object-Oriented Script as well as PHP MySQLi Procedural Script. Let's start with, object-oriented first.

PHP MySQLi Object-Oriented Script - register.php

This is register.php page, created using PHP MySQLi object-oriented script or code.

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $server = "localhost";
      $user = "root";
      $pass = "";
      $db = "fresherearth";
      
      $conn = new mysqli($server, $user, $pass, $db);
      
      if($conn -> connect_errno)
      {
         echo "Database connection failed!<BR>";
         echo "Reason: ", $conn->connect_error;
         exit();
      }
      else
      {
         $fname = $_POST["firstname"];
         $lname = $_POST["lastname"];
         $uname = $_POST["username"];
         $email = $_POST["email"];
         $pass = $_POST["password"];
      
         $sql = "INSERT INTO `users`(`FirstName`, `LastName`, `Username`, `Email`, `Password`)
            VALUES ('$fname', '$lname', '$uname', '$email', '$pass')";
         
         $qry = $conn -> query($sql);
         if($qry)
         {
            echo "Registration done successfully!";
            
            // block of code, to process further...
         }
         else
         {
            echo "Something went wrong while registration!<BR>";
            echo "Error Description: ", $conn -> error;
         }
      }
   }
   $conn -> close();
?>

Note - The mysqli() is used to open a connection to the MySQL database server, in object-oriented style.

Note - The new keyword is used to create a new object.

Note - The connect_errno is used to get/return the error code (if any) from last connect call, in object-oriented style.

Note - The connect_error is used to get the error description (if any) from last connection, in object-oriented style.

Note - The exit() is used to terminate the execution of the current PHP script.

Note - The query() is used to perform query on the MySQL database, in object-oriented style.

Note - The error is used to return the description of error (if any), by the most recent function call, in object-oriented style.

Note - The close() is used to close an opened connection, in object-oriented style.

The above PHP MySQLi object-oriented script to handle user registration form data, can also be created in this way:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $conn = new mysqli("localhost", "root", "", "fresherearth");
      
      if(!$conn->connect_errno)
      {
         $fname = $_POST["firstname"];
         $lname = $_POST["lastname"];
         $uname = $_POST["username"];
         $email = $_POST["email"];
         $pass = $_POST["password"];
      
         $sql = "INSERT INTO `users`(`FirstName`, `LastName`, `Username`, `Email`, `Password`)
            VALUES ('$fname', '$lname', '$uname', '$email', '$pass')";
         
         if($conn->query($sql))
            echo "Registration done successfully!";
      }
   }
   $conn->close();
?>

PHP MySQLi Procedural Script - register.php

Here is the register.php page, created using PHP MySQLi procedural script:.

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $server = "localhost";
      $user = "root";
      $pass = "";
      $db = "fresherearth";
      
      $conn = mysqli_connect($server, $user, $pass, $db);
      
      if(mysqli_connect_errno())
      {
         echo "Database connection failed!<BR>";
         echo "Reason: ", mysqli_connect_error();
         exit();
      }
      else
      {
         $fname = $_POST["firstname"];
         $lname = $_POST["lastname"];
         $uname = $_POST["username"];
         $email = $_POST["email"];
         $pass = $_POST["password"];
      
         $sql = "INSERT INTO `users`(`FirstName`, `LastName`, `Username`, `Email`, `Password`)
            VALUES ('$fname', '$lname', '$uname', '$email', '$pass')";
         
         $qry = mysqli_query($conn, $sql);
         if($qry)
         {
            echo "Registration done successfully!";
            
            // block of code, to process further
         }
         else
         {
            echo "Something went wrong while registration!<BR>";
            echo "Error Description: ", mysqli_error($conn);
         }
      }
   }
   mysqli_close($conn);
?>

Now fill the data and click on the Register button. Here is the output you will get:

php mysql registration form page handle

Now if you open the table named users available in the database fresherearth, a record has been inserted. Here is the new snapshot of the table:

php mysql user registration signup

Note - The mysqli_connect() is used to open a connection to the MySQL database server, in procedural style.

Note - The mysqli_connect_errno() is used to get/return the error code (if any) from last connect call, in procedural style.

Note - The mysqli_connect_error() is used to return the error description (if any) from the last connection, in procedural style.

Note - The mysqli_query() is used to perform query on the MySQL database, in procedural style.

Note - The mysqli_error() is used to return the description of error (if any), by the most recent function call, in object-oriented style.

Note - The mysqli_close() is used to close an opened connection to the MySQL database, in procedural style.

PHP MySQLi Security Issue with Registration Form

While creating a web application where users are allowed to enter their information, we need to take care about the steps to make our application more secure.

Over internet, or on your application, many suspicious users may try to exploit your application, hack your application, or whatever they take the steps against your application or for their benefits.

Therefore, we need to take care of some steps to avoid suspicious attack on our database:

I really do not know, what type of application you are building or going to build. But what I wanted to say is, just take all necessary steps to prevent your data/database, from attackers. Now let me create the complete registration form in single page. This time, I have taken some necessary steps to secure the registration form.

Complete PHP MySQLi Registration Form and Script in Single Page

It is very much subjective, that what developer wants to implement in registration form. For example, some developer wants to allow users to enter username and/or password whose length should be between 8 to 16 or whatever and some developer do not. It is up to you. Therefore, I am going to create a normal in-depth PHP MySQLi script for user registration page.

This PHP MySQLi script uses prepared statements do register the users data into the database. Also, I have created the form and the form handler script in a single page to display the error regarding the form (if any) on the same page.

<?php
   $driver = new mysqli_driver();
   $driver -> report_mode = MYSQLI_REPORT_OFF;
   
   if(isset($_SESSION['log']))
   {
      header('Location: welcome.php');
      exit();
   }
   else
   {
      if($_SERVER["REQUEST_METHOD"] == "POST")
      {
         function validData($x)
         {
            $x = trim($x);
            $x = stripslashes($x);
            $x = htmlspecialchars($x);
            return $x;
         }
         
         $server = "localhost";
         $user = "root";
         $pass = "";
         $db = "fresherearth";
      
         $conn = @new mysqli($server, $user, $pass, $db);
      
         if($conn->connect_errno)
         {
            echo "Database connection failed!<BR>";
            echo "Reason: ", $conn->connect_error;
            exit();
         }
      
         $fname = $lname = $uname = $email = $pass = "";
         $unameE = $emailE = $passE = "";
         
         $fname = validData($_POST["firstname"]);
         $lname = validData($_POST["lastname"]);
         $uname = validData($_POST["username"]);
         $email = validData($_POST["email"]);
         $pass = validData($_POST["password"]);
         
         if(empty($uname))
            $unameE = "Username field was empty!<BR>";
         if(empty($email))
            $emailE = "Email Id field was empty!<BR>";
         if(empty($pass))
            $passE = "Password field was empty!<BR>";
         if(strlen($uname)<6)
            $unameE .= "Username must be of 6 or more characters!<BR>";
         if(strlen($pass)<6)
            $passE .= "Password must be of 6 or more characters!<BR>";
         if(!filter_var($email, FILTER_VALIDATE_EMAIL))
            $emailE .= "Enter a valid Email ID!<BR>";
      
         if(!empty($unameE) || !empty($emailE) || !empty($passE))
            $err = "Try again";
         else
         {
            $sql = "INSERT INTO `users`(`FirstName`, `LastName`, `Username`, `Email`, `Password`)
               VALUES (?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssss", $fname, $lname, $uname, $email, $pass);
      
            if($stmt->execute())
            {
               $_SESSION['log'] = $uname;
               header('Location: welcome.php');
               exit();
            }
            else
               $execE = "Something went wrong<BR>Please try again!";
         }
         $conn->close();
      }
   }
?>
<HTML>
<HEAD>
<STYLE>
   .form{width: 400px; margin: auto; padding: 12px; border-left: 2px solid #ccc; border-radius: 18px;}
   h2{color: purple; text-align: center;}
   input{padding: 12px; width: 100%; margin-bottom: 12px; border: 0px; border-radius: 6px;
      background-color: #ccc;}
   button{margin: 20px 0px; width: 100%; background-color: #008080; color: white; padding: 12px;
      font-size: 1rem; border-radius: 6px;}
   p{text-align: center;}
   button:hover{cursor: pointer;}
   .red{color: red;}
</STYLE>
</HEAD>
<BODY>

<DIV class="form">
   <H2>User Registration Form</H2>
   <FORM name="register" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <LABEL>First Name</LABEL><BR>
      <INPUT type="text" name="firstname" placeholder="First Name"><BR>
      <LABEL>Last Name</LABEL><BR>
      <input type="text" name="lastname" placeholder="Last Name"><BR>
      <LABEL>Username
      <?php
         if(!empty($unameE))
            echo "<SPAN class=\"red\">*</SPAN>";
         else
            echo "*";
      ?>
      </LABEL><BR>
      <INPUT type="text" name="username" placeholder="Create Username" required><BR>
      <LABEL>Email
      <?php
         if(!empty($emailE))
            echo "<SPAN class=\"red\">*</SPAN>";
         else
            echo "*";
      ?>
      </LABEL><BR>
      <INPUT type="text" name="email" placeholder="Email ID" required><BR>
      <LABEL>Password
      <?php
         if(!empty($passE))
            echo "<SPAN class=\"red\">*</SPAN>";
         else
            echo "*";
      ?>
      </LABEL><BR>
      <INPUT type="text" name="password" placeholder="Create Password" required><BR>
      <BUTTON type="submit">Register</BUTTON>
   </FORM>
   <?php
   if(isset($err))
   {
      echo "<DIV class=\"red\">";
      if(!empty($unameE))
         echo $unameE;
      if(!empty($emailE))
         echo $emailE;
      if(!empty($passE))
         echo $passE;
      echo "</DIV>";
   }
   elseif(isset($execE))
      echo $execE;
   else
   {
      echo "<P><B>Direction: </B> Username and Password must be of 6 or more characters.<BR>";
      echo "Star (*) Fields must not be empty.<BR>";
      echo "Special characters are not allowed.</P>";
   }
   ?>
   <P>Already registered ? <a href="login.php">Login</a></P>
</DIV>

</BODY>
</HTML>

The output produced by above PHP MySQLi user registration form, is shown in the snapshot given below:

php mysql user registration form

Now if you enter invalid/wrong input, then you will get the error message on the same page. Here is the snapshot after providing codes#xyz.com as Email ID and other field as empty:

php mysql user registration

I removed the required attribute before hitting on the Register button, leaving the field Username and Password empty, and the Email ID field with codes#xyz.com.

After providing valid data, the user gets registered on the website, and the page will be redirected to the welcome.php page.

Note - The mysqli_driver() is used to modify the error reporting mode, in object-oriented style.

Note - The header() function is used to send raw HTTP header. Most of the time, used for redirection.

Note - The prepare() is used to prepare an SQL statement before its execution on the MySQL database, in object-oriented style, to avoid SQL injection.

Note - The bind_param() is used to bind variables to a prepared statement, as parameters, in object-oriented style.

Note - The execute() is used to execute a prepared statement on the MySQL database, in object-oriented style.

PHP Online Test


« Previous Tutorial Next Tutorial »