Categories
PHP

Login and Registration using PHP Ajax

Learn how you can create a simple registration and login with database API.

Table structure for table `users`

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table structure for table `serial`

CREATE TABLE `serial` (
  `serial_key` varchar(25) NOT NULL,
  `serial_value` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_login';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>
<?php
    require 'database.php';
   
    function GetWebsiteName() {
        $db_connection = new Database();
        $conn = $db_connection->dbConnection();
        $param = "WEBSITE_NAME";
        $stmt = $conn->prepare("SELECT * FROM serial");
        $stmt->bindParam(1, $param, PDO::PARAM_STR);
        
        $stmt->execute();
        $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
        $serialValue = $results[0]['serial_value'];
        return $serialValue;
    }
?>
<?php
	session_start();
	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();
    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 
    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;
    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = '$username' and password  = '$password'");
   
    $stmt->bindParam(1, $username, PDO::PARAM_STR);
    $stmt->bindParam(2, $password, PDO::PARAM_STR);
    $stmt->execute();
    $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
    $msgResult = "Success";
    if($msgResult == "Success"){
    	$userID = $results[0]['id'];
    	$username = $results[0]['username'];
    
    	// Set Session variables
    	$_SESSION['USERID'] = $userID;
    	$_SESSION['USERNAME'] = $username;
  
    	echo "success";
    } else {
    	echo "failed";
    }
?>
<?php
	// start session
	session_start();
	// Destroy user session
	unset($_SESSION['USERID']);
	unset($_SESSION['USERNAME']);
	// Redirect to index.php page
	header("Location: ../index.php");
?>
<?php
	session_start();
	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();
    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 
    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;
    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";
    $statement = $conn->prepare("SELECT * FROM users WHERE username='$username'");
    $statement->execute();
    $results = $statement->fetchColumn();
    if ($results == 0) {
        $statement = $conn->prepare("INSERT INTO users (username, password) 
        VALUES (?, ?)");
        $statement->bindParam(1, $username, PDO::PARAM_STR);
        $statement->bindParam(2, $password, PDO::PARAM_STR);
        $statement->execute();
        echo "success";
    } else {
        echo "failed";
    }
?>
<?php 
    session_start();
    require_once('library/functions.php');
    if ((isset($_SESSION['USERID']))) {
      header("Location: home.php");
    } 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <div class="col-lg-8 col-md-10 bg-login py-3">
      <div class="row">
        <div class="col-lg-6 column-1">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Login</h3>
              <p class="card-text">Dont Have an Account? <a class="reg-user" href="#"> Create your Account</a></p>
              <form id="login_form" method="post">
                <div class="form-group">
                  <input id="email" class="form-control" type="email" name="email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="password" class="form-control" type="password" name="password"
                    placeholder="Enter Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit" id="login_button">Sign
                    In</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-0" style="display:none">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Register Account</h3>
              <p class="card-text">Do You Have an Account? <a class="login-user" href="#"> Login</a></p>
              <form id="reg_form" method="post">
                <div class="form-group">
                  <input id="reg-email" class="form-control" type="email" name="reg-email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="reg-password" class="form-control" type="password" name="reg-password"
                    placeholder="Enter Password">
                </div>
                <div class="form-group">
                  <input id="reg-re-password" class="form-control" type="password" name="reg-re-password"
                    placeholder="Confirm Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit">Sign
                    Up</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-2 overflow-hidden">
          <div class="card border-0 bg-transparent text-right text-white">
            <img class="card-img" src="assets/images/undraw_Directions_re_kjxs.svg" alt="">
            <div class="card-img-overlay">
              <h2 class="card-title">Welcome Back</h2>
              <p class="card-text">Simply Create your account by clicking the signup button</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>
</html>
<?php 
  session_start();
  require_once('library/functions.php');
  if (($_SESSION['USERID'] == '') || (!isset($_SESSION['USERID']))) {
    // Redirect to index.php page
    header("Location: index.php");
  } 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css?version:202">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
  <header>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
      <a class="navbar-brand">Proghubsterzeak</a>
      <button class="navbar-toggler" data-target="#my-nav" data-toggle="collapse" aria-controls="my-nav"
        aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div id="my-nav" class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="library/logout.php">Logout <span class="sr-only">(current)</span></a>
          </li>
        </ul>
      </div>
    </nav>
  </header>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <h1>Welcome User</h1>
  </main>
</body>
</html>
Donate to proghubsterzeak

You can make a donation to help us if you found this post helpful.

If you want to get source code, please click Download Code button on below link. For more information just leave a message/comment.

…I’m interested for Web Development Project (Shopify, WordPress, from Scratch Development) please email me at larrydaveemol@gmail.com

This simple codes will help you achieve your goals, learn and update your skills. Enjoy Coding!