How to check already exist username when user input on Sig Up Form

in #utopian-io7 years ago (edited)

What Will I Learn?

Write here briefly the details of what the user is going to learn in a bullet list.

  • You will learn how to get data from html element
  • You will learn how send data using ajax
  • You will learn on input event in jQuery
  • You will learn how to execute SQL query using PHP and AJAX

Requirements

  • Basic knowledge about HTML
  • Basic knowledge about JavaScript
  • Basic knowledge about PHP
  • Basic knowledge about MySql
  • You have to install or host the jQuery file, You can add jQuery CDN if you don't want to install or host it
  • To practice this tutorial you should have a webserver, text editor and a browser. In this tutorial I use XAMPP for webserver, Visual Studio Code for text editor and Google Crome for browser.

Difficulty

  • Intermediate

Tutorial Contents

On a website, the username of one account and other accounts should not be the same.to solve this problem, it is necessary to check the process when the user to register. In this tutorial we will create a checking process whether the filled username already exists or not. This process is automatic when the user inputs. If the username is already entered it will issue an error message and vice versa. For more detail lets pay attention steps bellow :

$activate webserver
  • ReActive your webserver. create new folder in Xampp/htdocs/ if you use XAMPP. While you use Linux create it at var/www.
$Creating Database
  • Open phpmyadmin if you use XAMPP to create a new database. Or open your sql then create new database.
CREATE DATABASE SIGUP;
  • Create a sample user table
CREATE TABLE `sigup`.`user` ( `id` SMALLINT NOT NULL AUTO_INCREMENT , `username` VARCHAR(30) NOT NULL , `password` VARCHAR(30) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
  • INSERT some data for example, username and password
INSERT INTO `user` (`id`, `username`, `password`) VALUES (NULL, 'utopian', 'utopian'), (NULL, 'dsound', 'dsound'), (NULL, 'dmania', 'dmania'), (NULL, 'dtube', 'dtube'), (NULL, 'esteem', 'esteem')

image.png

$Creating a simple username input in HTML sigup Form
  • Open your text editor software, Create new file and save as sigup.html in the previous folder that created by you.

  • Add the HTML element as usual.

<html>
<head>
<title>Check username</title>
</head>
<body>
</body>
</html>
  • Creata a simple input text
Username : <input id="uname" type="text"> 
  • Add a <span> element to display alert message
<span id="alert"></span>  
$Adding jQuery AJAX
  • As we know, to use jQuery we need to install or host it. Or we can also add jQuery CDN if we don't want to install or host it. we also have many choices CDN that we can use, either Google CDN or Microsoft CDN. For more Detail you can visit jquery official web. In this tutorial I use Google CDN. Add the CDN in <head> element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  • To write the jQuery Script we should open <script> tag. You can put it in <head> element or in <body> element.
<script></script>
  • Before add more event in jQuery. There is an event that we should add for the first. It is ready() event. this event to make sure that all html elements are loaded. if it is, then it will load jQuery script. So, all jQuery Script must write in this function event.
$(document).ready(function(){
});
  • Select the username input and add on input event function
 $("#uname").on("input", function(){
});
  • Get data from input and save it to variable. To get data when inputing we can use $(this)
var uname=$(this).val();
  • Check username length. Here we make the condition if the username input < 3 will say so short. And will process in input > 3.
if(uname.length < 3){
                    $("#alert").text("so short");
                }
  • Create else condition
else{
}
  • to check data in database add the ajax function in else condition.
$.ajax({
                        url:'check.php',
                        method:'POST',
                        data:{
                            username:uname
                        },
                        success:function(response){
                            $("#alert").text(response);
                        }
                    });

Explanation Script : url:'check.php', url address that will send the data. method:'POST', sending method. data:{username:uname }, getting data from JS variabel. success:function(response) the function that will be execute if Ajax success, the response is the parameter to get back data from check.php. $("#alert").text(response); set text for span with id=alert with the data that send from php file

$Create The PHP file
  • Create new file on your text editor application and save as check.php [the url that you mention on AJAX function].

  • Open MySql connection.

$conn = new mysqli('localhost', 'root', '', 'sigup');
  • Add the variable to accommodate data that send from the FORM by method POST
$user=$_POST['username'];
  • Add the sql Query to check data is already exist on database
$sql="SELECT * FROM user where username='$user'";
  • Execute the sql query
$result = $conn->query($sql);
  • Create a condition to check if the the username exist or not
if ($result->num_rows > 0) {
    echo "Username Already Exist";
}
else{
    echo 'Available';
}
&Testing
  • Save all file and try to run sigup.html on your localhost.
    image.png

  • Try to input less then 3 character. You will get message "so short"

  • In database we already has user : utopian, dtube, dmania, dsound, esteem. Try to input except the the username mentioned

  • Try to input same with the username already exist

$full code

sigup.html

<html>
<head>
    <title>Check username</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    Username : <input id="uname" type="text"> 
    <span id="alert"></span>  
    <script>
        $(document).ready(function(){
            $("#uname").on("input", function(){
                var uname=$(this).val();
                if(uname.length < 3){
                    $("#alert").text("so short");
                }
                else{
                    $.ajax({
                        url:'check.php',
                        method:'POST',
                        data:{
                            username:uname
                        },
                        success:function(response){
                            $("#alert").text(response);
                        }
                    });
                }
            });
        });
    </script> 
</body>
</html>

check.php

<?php
$conn = new mysqli('localhost', 'root', '', 'sigup');
$user=$_POST['username'];
$sql="SELECT * FROM user where username='$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    echo "Username Already Exist";
}
else{
    echo 'Available';
}
?>

Downoad file on GDRIVE

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

thank sir

Hey @shreyasgune, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Sukses terus adinda @sogata...!.

terimong genaseh adun @foways

Gure bek tuwe neu vote ata lon beuh @sogata 😊

Setelah melihat ini..sepertinya aku harus mengulang lagi ilmu lama

good informative post @sogata....

Oman gurei...kreuh bhan keu liket sang heuh...vote kreuh...level kreuh...bantu ngen dilei bacut...hahaha

Oman gurei...beu meutuah long baro nyo merempek 0,7$...trimeng geunaseh beu rayek that...man bak hana su nah..jadi hana tatuoh 0,7 nyan..hahahhahaha
Sige teuk terimeng geunaseh ubeblang padang mahsyar raya gurei..hehe

hahahaha, biasa manteng ngon. hana payah pesibok dro sare

Hehehe....get..trmeng geunaseh..hehe

Saya memang tidak mengerti. Tapi ini pasti hal yg bermanfaat.

this is nit easy job

Hey @sogata I am @utopian-io. I have just upvoted you!

Achievements

  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

bereh sogata😊

Coin Marketplace

STEEM 0.22
TRX 0.20
JST 0.034
BTC 92362.74
ETH 3111.98
USDT 1.00
SBD 3.15