The Wayback Machine - https://web.archive.org/web/20240624031140/https://www.geeksforgeeks.org/signup-form-using-php-and-mysql-database/
Open In App

Signup form using PHP and MySQL Database

Last Updated : 09 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to create and design a sign-up form in which if the user enters details, the HTML form data are inserted into our MySQL server database.

Approach:

  • First task is that we have to create our MySQL server Database and a Table according to our requirements.
  • We connect our MySQL server Database using PHP mysqli_connect() function which takes four arguments, i.e. our “servername”, “username”, “password” and “database”.

Note: No CSS code is used here as we are using Bootstrap in the following PHP code. You can apply CSS and style in your web page as per your own application requirement.

PHP code to create Database connection: First and the most basic step is to create a Database connection. The PHP file name used here is “dbconnect.php” and the database name used is “geeksforgeeks”.




<?php
   
    $servername = "localhost"; 
    $username = "root"; 
    $password = "";
   
    $database = "geeksforgeeks";
   
     // Create a connection 
     $conn = mysqli_connect($servername, 
         $username, $password, $database);
   
    // Code written below is a step taken
    // to check that our Database is 
    // connected properly or not. If our 
    // Database is properly connected we
    // can remove this part from the code 
    // or we can simply make it a comment 
    // for future reference.
   
    if($conn) {
        echo "success"; 
    } 
    else {
        die("Error". mysqli_connect_error()); 
    } 
?>


“users” table is created using MySQL phpMyAdmin tool as shown below.

user table

PHP code to design sign-up form: Now when we have successfully connected to our Database, it is time to create the Signup form for the users. The following PHP code demonstrates the sign-up form. The MySql database table name used is “users”.




<?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=
        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 
            now 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>


Output:

  • Sign-up form:
    user table
  • After successful user login:
    user table
  • After invalid user login:
    user table


Similar Reads

Signup Form Using Node.js and MongoDB
Installations First, we need to include a few packages for our Nodejs application. npm install express --save Express allows us to set up middlewares to respond to HTTP Requests. npm install body-parser --save If you want to read HTTP POST data , you have to use the "body-parser" node module. npm install mongoose --save Mongoose is an object docume
3 min read
Create a Simple Signup Form with Map Embedded in Tailwind CSS
We will create a signup form styled with Tailwind CSS. It includes fields for name, email, password, and location with an embedded map using an iframe. The form is designed with a simple, responsive layout and styling for a clean user experience. Syntax// CDN Link to integrate Tailwind CSS&lt;link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.
2 min read
Amazon auto signup script
Scripts are very powerful as they give us different features with which we can manipulate web apps and websites. Javascript being the most popular scripting language also has these features with which we can manipulate the contents of websites and web apps. In this article, we will make use of simple javascript code(script) which will allow us to f
3 min read
How to retrieve data from MySQL database using PHP ?
There are steps to understand for retrieving the data from the MySQL database. Approach: Create the database, then create the table for data.Enter the rows in the table. You have to connect to the database. Now we understand each and every step as shown below. Example 1: In this. we use PHPMyAdmin for the database handling. Start the server in the
2 min read
Upload pdf file to MySQL database for multiple records using PHP
We will upload multiple records to the database and display all the records from the database on the same page. In this article, we will see how we can upload PDF files to a MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be using the WAMP server. Creating Database and Table:
7 min read
How to Update Data in MySQL Database Table Using PHP?
Updating data in a MySQL database table using PHP is a fundamental aspect of web development, particularly in applications where user interactions involve modifying existing records. This guide delves into the process of updating data in a MySQL database table using PHP, covering database connection, SQL queries, error handling, and best practices.
3 min read
How to Insert JSON data into MySQL database using PHP?
To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Structure:[{ "data1": "value1", "data2": "value2", .
3 min read
How to Upload Multiple Images and Text to MySQL Database in PHP?
In web development, many times we need to handle multiple files at once while uploading and storing into the database. So in this article, we will see how to do this by various approaches to achieve this using PHP and MySQL. Table of Content Storing Images in the File SystemUsing Base64 EncodingApproach 1: Storing Images in the File SystemIn this a
4 min read
PHP | MySQL Database Introduction
What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL is a database system that runs on a server.MySQL
4 min read
PHP | MySQL ( Creating Database )
What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty, and admin staff etc. which helps in efficient retr
3 min read
three90RightbarBannerImg