PHP mysqli code to create a signup or registration page or form

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

But before creating a registration form to allow users to register, 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.

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 codescracker. In this database, a table named users is created with the following columns:

Here is a 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 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 going with the same, to make understanding the things provided here much easier. After learning all the things given here, you can proceed to modify and implement them further to meet your own requirements.

PHP mysqli: Simple registration form

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

PHP mysqli Registration Form, Step No. 1

Now let's create an HTML form to allow users to enter their data to register on the website. Here I am going to create a simple and basic HTML form to get the data from the 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 the above user registration form code is shown in the snapshot given below:

php mysql signup form page

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

Now fill in the data in this user registration form, and hit the Register button to register. Here is the new snapshot of the same registration form after filling out 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 procedural and object-oriented scripts. Let's start with object-oriented first.

PHP mysqli object-oriented script: register.php

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

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $server = "localhost";
      $user = "root";
      $pass = "";
      $db = "codescracker";
      
      $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() function 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 or return the error code (if any) from the last connect call in object-oriented style.

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

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

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

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

Note: The close() function 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", "", "codescracker");
      
      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 = "codescracker";
      
      $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 in 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 codescracker, a record has been inserted. Here is the new snapshot of the table:

php mysql user registration signup

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

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

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

Note: The mysqli_query() function is used to perform queries on the MySQL database in procedural style.

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

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

PHP mysqli security issue with the 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 the internet or on your application, many suspicious users may try to exploit your application, hack your application, or do whatever they can to take steps against your application or for their own benefit.

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

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

Complete PHP mysqli Registration Form and Script in One Page

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

This PHP mysqli script uses prepared statements to register the users data in the database. Also, I have created the form and the form handler script on 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 = "codescracker";
      
         $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 the above PHP mysqli user registration form is shown in the snapshot given below:

php mysql user registration form

Now if you enter invalid or 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 leaving other fields empty:

php mysql user registration

I removed the required attribute before hitting the Register button, leaving the fields 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() function is used to modify the error reporting mode in object-oriented style.

Note: The header() function function is used to send raw HTTP headers. The majority of the time, it is used for redirection.

Note: The prepare() function 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() function is used to bind variables to a prepared statement as parameters in object-oriented style.

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

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!