Creating a Login and Registration Form using PHP PDO Tutorial

In this tutorial we will create a PDO Login and Registration using PHP. PHP is a server-side scripting language designed primarily for web development. PDO stands for PHP Data Objects. It is a lean and consistent way to access databases. This means developers can write portable code much easier. It is mostly used by a newly coders for its user-friendly environment.

So Let's do the coding...

Before we started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. Then, Open the XAMPP's Control Panel and start Apache and MySQL. Also I used Bootstrap for this tutorial, go to https://getbootstrap.com/ to download.

Creating Database

Open your database web server [i.e. http://localhost/phpmyadmin] then create a database name in it db_login.

To create the members table in the database. Click the SQL tab and copy/paste the code below. Click the Go button to submit the SQL Code.

  1.        
  2. CREATE TABLE `member` (
  3.   `firstname` varchar(50) NOT NULL,
  4.   `lastname` varchar(50) NOT NULL,
  5.   `username` varchar(30) NOT NULL,
  6.   `password` varchar(12) NOT NULL

Import the provided SQL along with the working source code. To do this, click Import tab in then locate the SQL file inside the database folder then click ok.

tut1

Creating the database connection

Open your any kind of text editor(notepadd++, etc..). Then just copy/paste the code below then save it as conn.php.

  1. <?php
  2.         $db_username = 'root';
  3.         $db_password = '';
  4.         $conn = new PDO( 'mysql:host=localhost;dbname=db_login', $db_username, $db_password );
  5.         if(!$conn){
  6.                 die("Fatal Error: Connection Failed!");
  7.         }
  8. ?>

Creating The Mark Up/Interface

This is where we will create a simple form for our application. To create the forms simply copy and paste it into you text editor, then save them as shown below.

index.php

This page is the default page when browsing the application. This shows the login form.

  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5.         <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6.         <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  7. </head>
  8. <body>
  9.         <nav class="navbar navbar-default">
  10.                 <div class="container-fluid">
  11.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  12.                 </div>
  13.         </nav>
  14.         <div class="col-md-3"></div>
  15.         <div class="col-md-6 well">
  16.                 <h3 class="text-primary">PHP - PDO Login and Registration</h3>
  17.                 <hr style="border-top:1px dotted #ccc;"/>
  18.                 <div class="col-md-2"></div>
  19.                 <div class="col-md-8">
  20.                         <?php if(isset($_SESSION['message'])): ?>
  21.                                 <div class="alert alert-<?php echo $_SESSION['message']['alert'] ?> msg"><?php echo $_SESSION['message']['text'] ?></div>
  22.                         <script>
  23.                                 (function() {
  24.                                         // removing the message 3 seconds after the page load
  25.                                         setTimeout(function(){
  26.                                                 document.querySelector('.msg').remove();
  27.                                         },3000)
  28.                                 })();
  29.                         </script>
  30.                         <?php
  31.                                 endif;
  32.                                 // clearing the message
  33.                                 unset($_SESSION['message']);
  34.                         ?>
  35.                         <form action="login_query.php" method="POST">  
  36.                                 <h4 class="text-success">Login here...</h4>
  37.                                 <hr style="border-top:1px groovy #000;">
  38.                                 <div class="form-group">
  39.                                         <label>Username</label>
  40.                                         <input type="text" class="form-control" name="username" />
  41.                                 </div>
  42.                                 <div class="form-group">
  43.                                         <label>Password</label>
  44.                                         <input type="password" class="form-control" name="password" />
  45.                                 </div>
  46.                                 <br />
  47.                                 <div class="form-group">
  48.                                         <button class="btn btn-primary form-control" name="login">Login</button>
  49.                                 </div>
  50.                                 <a href="registration.php">Registration</a>
  51.                         </form>
  52.                 </div>
  53.         </div>
  54. </body>
  55. </html>

registration.php

This page shows the registration form.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  5.                 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-3"></div>
  14.         <div class="col-md-6 well">
  15.                 <h3 class="text-primary">PHP - PDO Login and Registration</h3>
  16.                 <hr style="border-top:1px dotted #ccc;"/>
  17.                 <div class="col-md-2"></div>
  18.                 <div class="col-md-8">
  19.                         <form action="register_query.php" method="POST">       
  20.                                 <h4 class="text-success">Register here...</h4>
  21.                                 <hr style="border-top:1px groovy #000;">
  22.                                 <div class="form-group">
  23.                                         <label>Firstname</label>
  24.                                         <input type="text" class="form-control" name="firstname" />
  25.                                 </div>
  26.                                 <div class="form-group">
  27.                                         <label>Lastname</label>
  28.                                         <input type="text" class="form-control" name="lastname" />
  29.                                 </div>
  30.                                 <div class="form-group">
  31.                                         <label>Username</label>
  32.                                         <input type="text" class="form-control" name="username" />
  33.                                 </div>
  34.                                 <div class="form-group">
  35.                                         <label>Password</label>
  36.                                         <input type="password" class="form-control" name="password" />
  37.                                 </div>
  38.                                 <br />
  39.                                 <div class="form-group">
  40.                                         <button class="btn btn-primary form-control" name="register">Register</button>
  41.                                 </div>
  42.                                 <a href="index.php">Login</a>
  43.                         </form>
  44.                 </div>
  45.         </div>
  46. </body>
  47. </html>

home.php

This will be the page where user will be redirected after logging in.

  1. <!DOCTYPE html>
  2. <?php
  3.         require 'conn.php';
  4.         session_start();
  5.        
  6.         if(!ISSET($_SESSION['user'])){
  7.                 header('location:index.php');
  8.         }
  9. ?>
  10. <html lang="en">
  11.         <head>
  12.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  13.                 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  14.         </head>
  15. <body>
  16.         <nav class="navbar navbar-default">
  17.                 <div class="container-fluid">
  18.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  19.                 </div>
  20.         </nav>
  21.         <div class="col-md-3"></div>
  22.         <div class="col-md-6 well">
  23.                 <h3 class="text-primary">PHP - PDO Login and Registration</h3>
  24.                 <hr style="border-top:1px dotted #ccc;"/>
  25.                 <div class="col-md-2"></div>
  26.                 <div class="col-md-8">
  27.                         <h3>Welcome!</h3>
  28.                         <br />
  29.                         <?php
  30.                                 $id = $_SESSION['user'];
  31.                                 $sql = $conn->prepare("SELECT * FROM `member` WHERE `mem_id`='$id'");
  32.                                 $sql->execute();
  33.                                 $fetch = $sql->fetch();
  34.                         ?>
  35.                         <center><h4><?php echo $fetch['firstname']." ". $fetch['lastname']?></h4></center>
  36.                         <a href = "logout.php">Logout</a>
  37.                 </div>
  38.         </div>
  39. </body>
  40. </html>

Creating the Main Function

This code contains the specific script for the process of queries in the database. This code is consists of different functionalities, such as logout, login, and registration. To do that write these blocks of codes inside the Text editor and save them accordingly as shown below.

register_query.php

This is where the code register all the data in the input to the database server. PDO create a request then it will gather all the data that been collected ,and will store afterwards.

  1. <?php
  2.         session_start();
  3.         require_once 'conn.php';
  4.  
  5.         if(ISSET($_POST['register'])){
  6.                 if($_POST['firstname'] != "" || $_POST['username'] != "" || $_POST['password'] != ""){
  7.                         try{
  8.                                 $firstname = $_POST['firstname'];
  9.                                 $lastname = $_POST['lastname'];
  10.                                 $username = $_POST['username'];
  11.                                 // md5 encrypted
  12.                                 // $password = md5($_POST['password']);
  13.                                 $password = $_POST['password'];
  14.                                 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  15.                                 $sql = "INSERT INTO `member` VALUES ('', '$firstname', '$lastname', '$username', '$password')";
  16.                                 $conn->exec($sql);
  17.                         }catch(PDOException $e){
  18.                                 echo $e->getMessage();
  19.                         }
  20.                         $_SESSION['message']=array("text"=>"User successfully created.","alert"=>"info");
  21.                         $conn = null;
  22.                         header('location:index.php');
  23.                 }else{
  24.                         echo "
  25.                                 <script>alert('Please fill up the required field!')</script>
  26.                                 <script>window.location = 'registration.php'</script>
  27.                         ";
  28.                 }
  29.         }
  30. ?>

login_query.php

This where the code can login the user. PDO send a request to the database server then receive some confirmation if the user account is a valid to access the data.

  1. <?php
  2.         session_start();
  3.        
  4.         require_once 'conn.php';
  5.        
  6.         if(ISSET($_POST['login'])){
  7.                 if($_POST['username'] != "" || $_POST['password'] != ""){
  8.                         $username = $_POST['username'];
  9.                         $password = $_POST['password'];
  10.                         $sql = "SELECT * FROM `member` WHERE `username`=? AND `password`=? ";
  11.                         $query = $conn->prepare($sql);
  12.                         $query->execute(array($username,$password));
  13.                         $row = $query->rowCount();
  14.                         $fetch = $query->fetch();
  15.                         if($row > 0) {
  16.                                 $_SESSION['user'] = $fetch['mem_id'];
  17.                                 header("location: home.php");
  18.                         } else{
  19.                                 echo "
  20.                                 <script>alert('Invalid username or password')</script>
  21.                                 <script>window.location = 'index.php'</script>
  22.                                 ";
  23.                         }
  24.                 }else{
  25.                         echo "
  26.                                 <script>alert('Please complete the required field!')</script>
  27.                                 <script>window.location = 'index.php'</script>
  28.                         ";
  29.                 }
  30.         }
  31. ?>

logout.php

This where the code can logout the user account. The user will be will force to logout when the logout button is click.

  1. <?php
  2.         session_start();
  3.         session_destroy();
  4.         header('location: index.php');
  5. ?>

DEMO

There you have it we successfully created a PDO Login and Registration using PHP. You can now test your work if it runs properly or the way we intend to create it in this tutorial. If there's an error occurred on your end, kindly recheck the code or download the working source code to differentiate it from your work.

I hope that this simple tutorial helps you to what you are looking for. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!!

Comments

the code in register_query.php is wrong. please edit it. thank you.

Note to anyone.. This script saves the passwords in plain text in your database which is a HUGE no no... Look up password_hash in PHP to securely store the password information.

Add new comment