Social Icons

Friday, November 30, 2012

Make Login form using PHP MySql

Create Login Page Using PHP MySql

For most of the websites, it is a common requirement to have registration for users and accordingly login for them. Only users who have login account for the website like username and password, they can access most of the sections of the website. While unauthorized users (who doesn't have account for the website) can't. Herein this tutorial, we will read how to make a login page for any website. To understand this tutorial completely, I assume that you have basic knowledge of PHP, MySql. Anyway, I will try to explain each and every line of code in the tutorial. So, here we go.

Let us make a rough idea what we have to do. There will be a username column and a password column and a Login Button in the webpage. User will enter his/her username and password there and will click on Login button. It will check from database either these details match or not. If matches it will give success message else failure. So, firstly we need a database in which there will be a table and two columns as 'username' and 'password'. We will store email in username and any string in password.

Open your mysql with localhost/phpmyadmin. You can create a database there directly using GUI or by commands also. I provide you the query to write there.

Step 1 – Create a Database

Run this query in mysql:

CREATE DATABASE tutorials

This query will create a database named 'tutorials' in your mysql database. Here, 'tutorials' is the database name. You can replace it with your own name whatever you want.

Step 2 – Create a table (having columns username and password) in the above database


Now, we have to create a table in the database 'tutorials'. Now, select the database 'tutorials' in your  localhost/phpmyadmin. There run this query:


create table user (username varchar(50), password varchar(50))

This query will create a table named 'user' in the database 'tutorials'. It will have two columns as 'username' and 'password'. Varchar above in the query is the data type for username and password both. Both of them have size of 50 characters max. We could take char as data type also but then it would allocate 50 bytes for each. While varchar is flexible.

Now as no data is there in our database so we have to insert some data into it. Lets insert some username and password values into table 'user'. Run this query:

INSERT INTO user (username,password) VALUES ('prem@prembaranwal.com', '123')

It will insert a row having username value as prem@prembaranwal.com and password as 123.

Lets insert one more value similarly. Run this query:

INSERT INTO user (username,password) VALUES ('talkmeonprem@gmail.com', 'prem')

Now enough for the database part. Lets move to the front-end PHP and HTML part.

Lets create a login page. There will be a two textboxes for username and password where user will enter its username and password values. Apart from this there will be a submit login button. On clicking this button it will validate username and password as it is correct or not and display a message 'success' if correct and 'failure' if wrong.

Create a file named login.php

Code for login.php
            
            <html>
            <head>
            <title>Login Page in PHP</title>
            </head>
            <body>
            <form name=”myForm” action=”loginconnect.php” method=”POST”>
            <table>
            <tr>
                   <td>Username: </td>
                   <td><input type=”text” name=”username” id=”username” value=””/></td>
            </tr>
            <tr>
                   <td>Password: </td>
                   <td><input type=”password” name=”pwd” id=”pwd” value=””/></td>
            </tr>
            <tr></tr>
            <tr>
                   <td><input type=”submit” name=”login” value=”Login”/></td>
            </tr>
            </table>
            </form>
            </body>
            </html>


It will create a login page having username, password fields and submit button.

Now, user will enter its details in the textboxes and click on Login button. After clicking we have to check either the username and password is correct for the user or not. After clicking on Login button it will go to loginconnect.php page as it is written in form action in the above code ( see in login.php)

Lets write the code for loginconnect.php

Code for loginconnect.php

            <?php

            $user = $_POST['username'];  // store username entered by user

            $pwd = $_POST['pwd'];         // store password entered by user

            $con = mysql_connect("localhost","root","");  //establish connection to mysql database

            mysql_select_db("tutorials", $con);  //selects database tutorials
            $result = mysql_query("SELECT * FROM user WHERE username = '$user' and password='$pwd'”); // Query to check username and password is correct or not.

            $count = mysql_num_rows($result);  // Return number of rows from the above query

            if($count > 0)  // If it equals to 1 means username and password is correct
            {
                        echo “Successfully logged in”;
            }
            else
            {
                        echo “Either username or password is incorrect”;
            }

The description for the above code is given there in the comment itself for each line of code. I think these descriptions are enough to understand. Now run the login page.

Ø  Open your browser and type localhost/login.php in the url.

Ø  It will give you the login page containing username and password fields and login button.

Ø  Enter the details which we saved in our database.

Ø  In username, enter prem@prembaranwal.com and in password enter 123 and click on login button. It will give you successfully logged in message. Try with some wrong data and it will give you error message.

So, with this making basic login page finishes. Now, lets make it more better. We haven't put any validation here in the login page. Suppose if user doesn't enter anything in username and password and directly click on login button. In that case we can validate the form and ask user to enter those fields. Lets put validation in the form. Some modification is required in login.php file only.

Code for login.php with validation

            <html>
            <head>
            <title>Login Page in PHP</title>
            <script language=”javascript” type=”text/javascript”>
            function validateForm()
            {
                        var a = document.forms[“myForm”][“username”].value;
                        var b = document.forms[“myForm”][“pwd”].value;
                        if(a == null || a == “”)
                        {
                                    alert(“Enter Username”);
                                    return false;
                        }
                        if(b == null || b == “”)
                        {
                                    alert(“Enter Password”);
                                    return false;
                        }
            }
            </script>
            </head>
            <body>
            <form name=”myForm” action=”loginconnect.php” method=”POST”>
            <table>
            <tr>
                   <td>Username: </td>
                   <td><input type=”text” name=”username” id=”username” value=””/></td>
            </tr>
            <tr>
                   <td>Password: </td>
                   <td><input type=”password” name=”pwd” id=”pwd” value=””/></td>
            </tr>
            <tr></tr>
            <tr>
                   <td><input type=”submit” name=”login” value=”Login” onclick=”return validateForm()”/></td>
            </tr>
            </table>
            </form>
            </body>
            </html>


The above code will validate if the user has not entered username or password field and clicks on Login button directly. This results in a complete working login form in PHP.

No comments:

Post a Comment

Total Pageviews