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.  
  5. if(!ISSET($_SESSION['user'])){
  6. header('location:index.php');
  7. }
  8. ?>
  9. <html lang="en">
  10. <head>
  11. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  12. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  13. </head>
  14. <body>
  15. <nav class="navbar navbar-default">
  16. <div class="container-fluid">
  17. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  18. </div>
  19. </nav>
  20. <div class="col-md-3"></div>
  21. <div class="col-md-6 well">
  22. <h3 class="text-primary">PHP - PDO Login and Registration</h3>
  23. <hr style="border-top:1px dotted #ccc;"/>
  24. <div class="col-md-2"></div>
  25. <div class="col-md-8">
  26. <h3>Welcome!</h3>
  27. <br />
  28. <?php
  29. $id = $_SESSION['user'];
  30. $sql = $conn->prepare("SELECT * FROM `member` WHERE `mem_id`='$id'");
  31. $sql->execute();
  32. $fetch = $sql->fetch();
  33. ?>
  34. <center><h4><?php echo $fetch['firstname']." ". $fetch['lastname']?></h4></center>
  35. <a href = "logout.php">Logout</a>
  36. </div>
  37. </div>
  38. </body>
  39. </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. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['register'])){
  5. if($_POST['firstname'] != "" || $_POST['username'] != "" || $_POST['password'] != ""){
  6. try{
  7. $firstname = $_POST['firstname'];
  8. $lastname = $_POST['lastname'];
  9. $username = $_POST['username'];
  10. // md5 encrypted
  11. // $password = md5($_POST['password']);
  12. $password = $_POST['password'];
  13. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  14. $sql = "INSERT INTO `member` VALUES ('', '$firstname', '$lastname', '$username', '$password')";
  15. $conn->exec($sql);
  16. }catch(PDOException $e){
  17. echo $e->getMessage();
  18. }
  19. $_SESSION['message']=array("text"=>"User successfully created.","alert"=>"info");
  20. $conn = null;
  21. header('location:index.php');
  22. }else{
  23. echo "
  24. <script>alert('Please fill up the required field!')</script>
  25. <script>window.location = 'registration.php'</script>
  26. ";
  27. }
  28. }
  29. ?>

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

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. header('location: index.php');
  3. ?>

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

Submitted byNabihah (not verified)on Thu, 02/21/2019 - 15:11

the code in register_query.php is wrong. please edit it. thank you.
Submitted byRyanTheB (not verified)on Thu, 07/11/2019 - 03:46

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