Registration page in PHP using PDO(PHP DATA OBJECT)

This is for beginners in PHP, make sure to read the limitations of this system at the last of the webpage. Ensure that XAMPP is set up and that MySQL and Apache are operating before running the PHP file as shown in the figure below.

After starting MySQL and apache, make a folder inside XAMPP’s htdocs. You can give any names to the newly created folder. I have given the name login, you can also do the same.

Inside that folder, make one PHP file named index.php and write <?php echo “Hello world” ?> inside that file. Run that index.php file by writing localhost/login/index.php in any browser you want. I am using Chrome for this tutorial as shown in the figure below.

If the “hello world” is seen on screen just like the above picture, the PHP file is running successfully. Now, you can add HTML codes to a PHP file.

 

 

Php files for different webpages

For registration, we need four PHP files.

  1. login.php

login.php is for the login page which page checks whether the username and password are correct or not.

2. Register.php

Another page is register.php is for the register to add new users to the systems.

3. Dashboard.php

The dashboard is the page where the logged-in users will be sent.

4. Logout.php

Logout is the page where logged-in users can log out.

Create above mentioned four PHP files inside htdocs.

Inside the login.php file, make a form that takes username and password just like this.

<html>
<head><title>Login</title></head> 
<body>
    <h1>Login</h1>
    <form action="" method="post">
    <input type="text" name="username" value="" autocomplete="off"><br ><br>
   <input type="password" name="password" value="" autocomplete="off"><br><br >
     <input type="submit" name='loginbtn' value="Login" class='submit'><br >
             </form>
            
</body>
</html>

 

 

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}

?>

Connecting to MYSQL DATABASE

To connect the PHP file with MySQL, we have to write the following PHP code for the connection. You can put this code in every PHP file.

The default database hostname is the localhost. if you haven’t set the username and password for your database, please write root as username and leave blank for the password. If you have set up the username and password for the database, please do write the username and password that you have given.

For database name, you must have to make the database. You can give any name to the database, in my case, I am giving a test as a database name.

Since we are using the PHP data object, we have to create new PDO object by using the new keyword. $conn is the connection variable name.

For error handling, we must have to enclose the connection statement with try and catch block. If an error occurred inside the connection code, the error is handled by the catch block.

Creating database

Now we have to make a database name test.

You can create a database and its content in three ways. One is with a Graphical user interface, another is writing SQL queries, and the other imports SQL files to your localhost.

In this article, we will discuss SQL queries needed to create the database for registration. First, we must have to create a database and a table. You can make a database with the help of the following query. you can write this query inside the SQL tab as shown in the figure below.

 

 

After creating a database, click on the database you have created and run the following query to make a table.

 

CREATE TABLE 
login 
(
   
id
 int(10) NOT NULL,
   
fullname
 varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
   
username
 varchar(20) NOT NULL,
   
password
 varchar(20) NOT NULL,
   
email 
varchar(20) NOT NULL
 ) 

Here we have created the table named login and given the columns with proper constraints. Now to uniquely identify the row of the table, we have to give a primary key to id. You can give the primary key as :

ALTER TABLE 
login

   ADD PRIMARY KEY (
id
);

Or alternatively, we can set the primary key while creating a table.

CREATE TABLE 
login 
(
   
id
 int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
   
fullname
 varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
   
username
 varchar(20) NOT NULL,
   
password
 varchar(20) NOT NULL,
   
email 
varchar(20) NOT NULL
 ) 

 

 

Just like the login.php page that we have created before, make another page for the registration page. You can give any name to the file.

Inside php file, make similar form as above and add <input> tag for the input just like below.

<html>
<head><title>Login</title></head> 
<body>
    <h1>Login</h1>
    <form action="" method="post">
    <input type="text" name="fullname" value="" placeholder="Fullname"><br><br>
    <input type="text" name="username" value="" autocomplete="off"><br ><br>
    <input type="password" name="password" value="" autocomplete="off"><br><br >
    <input type="text" name="email" value="" autocomplete="off"><br><br >
     <input type="submit" name='regsiterbtn' value="Login" class='submit'><br >
             </form>
            
</body>
</html>

We have not added any PHP code till now. So we now add PHP code to our register.php file.

Register page

To connect to the MySQL database, you can use the same code which was mentioned above and after that, we have to write the PHP logic. In order to register a new user, we must have to take the value from the form and store that data in to the database once the button is clicked.

To get the data from the form we can use $_POST. Before that, we must check whether the button is clicked or not. For that, we can also use $_POST just like the below code.

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}

//to check whether the button is clicked or not
    if(isset($_POST['registerbtn'])) {
        

        // Getting data from the form named the following name
//make sure the name in the form matches the name in the $_POST['name']

        $fullname = $_POST['fullname'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $email = $_POST['email'];

First, we connected our PHP file with the MySQL database and we got the data from the form when the button is clicked. Now, we have to send the data to the database to store data.

Now, to submit the data to the database, we have to write the SQL query to the PHP file. For that, we can use the $conn->prepare() method and execute that code using execute method. Inside which we will write the SQL code just like this.

$statement = $conn->prepare('INSERT INTO login (fullname, username, password, email) VALUES (?, ?, ?, ?)');
$statement->execute(array( $fullname, $username, $password, $email ));

To catch errors we can enclose the above tag inside the try and catch block. If the SQL query runs successfully, we can redirect the user to the index.php file with the help of header(‘Location: index.php’); code just like the below code

try {
                $statement = $conn->prepare('INSERT INTO login (fullname, username, password, email) VALUES (?, ?, ?, ?)');
                $statement->execute(array( $fullname, $username, $password, $email
                    ));
                header('Location: index.php');
                exit;
            }
            catch(PDOException $e) {
                echo $e->getMessage();
            }
        }

Congratulations, we have successfully completed the register page. In case, you get confused the final register.php file looks like this.

 

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}


//to check whether the button is clicked or not
    if(isset($_POST['registerbtn'])) {
        

        // Getting data from the form named the following name
//make sure the name in the form matches the name in the $_POST['name']

        $fullname = $_POST['fullname'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $email = $_POST['email'];
try {
                $statement = $conn->prepare('INSERT INTO login (fullname, username, password, email) VALUES (?, ?, ?, ?)');
                $statement->execute(array( $fullname, $username, $password, $email
                    ));
                header('Location: login.php');
                exit;
            }
            catch(PDOException $e) {
                echo $e->getMessage();
            }
        }
?>
<html>
<head><title>Register</title></head>
<body>
                <form action="" method="post">
                    <input type="text" name="fullname" placeholder="Fullname" value="" autocomplete="off" /><br /><br />
                    <input type="text" name="username" placeholder="Username" value="" autocomplete="off" /><br /><br />
                    <input type="password" name="password" placeholder="Password" value=""/><br/><br />
                    <input type="text" name="email" placeholder="Email" value="" autocomplete="off" /><br /><br />
                    <input type="submit" name='registerbtn' value="Register" class='submit'/><br />
                </form>
</body>
</html>



You can alternatively run SQL code like this:

 

$statement = $conn->prepare('INSERT INTO login(fullname, username, password, email) VALUES (:fullname, :username, :password, :email)');
                $stmt->execute(array(
                    ':fullname' => $fullname,
                    ':username' => $username,
                    ':password' => $password,
                    ':email' => $email
                    ));

Now, You can see the data in the database like in the image below.

 

 

Login Page

Now for the login page, we have already created the HTML page. If you have forgotten, please scroll above, you will find it. The login.php is similar to regsiter.php, only difference is we have to write SQL query for retrieval of data instead of submitting data to the database.

To retrieve data from the database, we can use SELECT id, fullname, username, password, email FROM login WHERE username = ? and fetch the data using fetch(PDO::FETCH_ASSOC); After retrieving data from the database, we can check whether the password given by the user in the forms is the same which is in a database or not. To check that we can use if condition just like below.

$statement = $connect->prepare('SELECT id, fullname, username, password, email FROM login WHERE username = ?');
                $statement->execute(array($username));
                $data = $statement->fetch(PDO::FETCH_ASSOC);

                    if($password == $data['password']) {
                        header('Location: index.php');
                        exit;
                    }
                    else
                        $error= 'Password  do not match.';
                }

 

 

The full code looks like this.

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}
//to check whether the button is clicked or not

    if(isset($_POST['loginbtn'])) {
        $error = '';

        // Getting data from the form named the following name
//make sure the name in the form matches the name in the $_POST['name']
        $username = $_POST['username'];
        $password = $_POST['password'];

            try {
                $statement = $conn->prepare('SELECT id, fullname, username, password, email FROM login WHERE username = ?');
                $statement->execute(array($username));
                $data = $statement->fetch(PDO::FETCH_ASSOC);

                    if($password == $data['password']) {
                        
                        header('Location: dashboard.php');
                        exit;
                    }
                    else
                        $error= 'Password  do not match.';
                }
            
            catch(PDOException $e) {
                $error = $e->getMessage();
            }
        }
        
    
?>

<html>
<head><title>Login</title></head>
    
<body>
    
            <?php
                if(isset($error)){
                    echo '<div style="color:red;">'.$error.'</div>';
                }
            ?>
            <h1>Login</h1>
            
                <form action="" method="post">
                    <input type="text" name="username" value="" autocomplete="off"/><br /><br />
                    <input type="password" name="password" value="" autocomplete="off"/><br/><br />
                    <input type="submit" name='loginbtn' value="Login" class='submit'/><br />
                </form>
            
</body>
</html>



Now, we can make a dashboard.php file. We can use $_SESSION[‘name’] to get the name of the logged-in user. Inside dashboard.php, we can add a link to logout the page just like this.

 

 

Dashboard page

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}
    if(empty($_SESSION['name']))
        header('Location: login.php');
?>

<html>
<head><title>Dashboard</title></head>
    
<body>
                Welcome <?php echo $_SESSION['name']; ?>  to our web application<br>
                <a href="logout.php">Logout</a>
</body>
</html>

 

 

Logout Page

Now we are only left with one task that is logout. To log out from our system, we have to destroy our session with session_destroy(); function and redirect the user to another page. In this example, I will redirect the user to index.php.

<?php
session_start();

// Define localhost, databaseuser, database user and database name
define('dbhost', 'localhost');
define('dbuser', 'root');
define('dbpass', '');
define('dbname', 'test');

// Connecting to above mentioned database
try {
    $conn = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
//if any error occured
catch(PDOException $e) {
    echo $e->getMessage();
}
    session_destroy();

    header('Location: index.php');
?>

 

Limitation of this system:

  1. This system hasnot handeled any other error like empty input from the user and hasnot checked the format error.
  2. This system hasnot hashed the password. In real life project, we generally hash the password for the security issue.
  3. Instead of writing connection code in each file we can write the connection code in one file and inclued that code in each page by using <?php require ‘conection.php’;
  4. The user interface is not used as we have not used any styling to our website.
  5. In regsiter.php, we havenot checked whether the username is already present or not. Duplicate username is allowed. This will add user with same username multiple time. Due to this, username with different password doesnot work at all. In login.php also we have not given user clue if they entered wrong password or username.
  6. We havenot added forget password option.

This is for learning purposes only. There may be many errors in this system. So, to cross-check I have uploaded the code to GitHub –>https://github.com/dingavinga/Registration-page-in-PHP-using-PDO-PHP-DATA-OBJECT

Comment if you enjoyed this content. Your single comment can motivate me to do more 🙂

Total
1
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Prepare an activity diagram for computing a restaurant bill. There should be a charge for each delivered item. The total amount should be subject to tax. There is a service charge of 18% for groups of six or more and 10% for smaller groups. Any coupons and gift certificates submitted by the customer should be subtracted.

Next Post

Basic Crud Operation In PHP And MySQL.