3 forms submitted to 1 page

I have 3 forms
login, register, and forgot password
image


image

which are all popup windows
Im trying to figure out how to submit them to the same page so anyone can use them on any page
so the forms action is

<form action="<?=$_SERVER["SCRIPT_NAME"]?>" method="POST">
would something like this work?

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
if(isset($_POST[‘loginSubmit’]) || isset($_POST[‘registerSubmit’]) || isset($_POST[‘forgotSubmit’])){

}
}

Instead of making an OR condition where the IF condition contains many options, make IF conditions for specific processing code. You can have many processing sections on the same page.

if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['loginSubmit'])) {

}
1 Like

The point of testing if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) is because there are cases where both the $_POST and $_FILES arrays will be empty. Also, there are cases where a submit button won’t be set.

You should use a hidden field, such as, name=‘action’, with a value, such as ‘login’, ‘register’, or ‘forgot’ to control which post method form processing code gets executed (a switch/case statement would be a good choice), after you have detected that a post method form has been submitted.

BTW, to get a form to submit to the same page it is on, simply leave out the entire action attribute.

4 Likes

If password confirm was set, it’s the register page.
Else if password was set, it’s the login page.
Else if email was set, it’s the forgot password page.
Else it’s a bad submission.

(Find the differences in your form data… start with the most data, and work down to whatever’s left.)

I did it like this…
the form

<div id="register" class="overlay">
	<div class="popup">
		<div class="content">
		  <a class="close" href="#">&times;</a>
			<div class="alert alert-primary mb-0" role="alert">
		      <h3><i class="fa fa-registered"></i>&nbsp;&nbsp;Register</h3>
			  <hr>
				<div class="alert alert-light border border-light shadow-sm" role="alert">
				  <form action="<?=$_SERVER["SCRIPT_NAME"]?>" method="POST">
					<div class="form-group mb-3">
					  <label for="Troop">Troop</label>
					  <select class="form-select" id="Troop" name="Troop" aria-label="Default select example">
						<option value='' selected>Select</option>
<?php
try{
    $sql = 'SELECT troop_id,name FROM troops';
            
    $result = $pdo->query($sql);
    
    $troops = $result->fetchAll();
		foreach($troops as $troop) {
		  echo '<option value="1'.$troop['troop_id'].'">'.$troop['name'].'</option>';
		}
} catch(PDOException $e){
  die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
?>
					  </select>
					</div>
					<div class="form-group mb-3">
					  <label for="Name">Name</label>
					  <input type="text" class="form-control" id="Name" name="Name" required>
					</div>					
					<div class="form-group mb-3">
					  <label for="Email1">Email</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary">@</span>
							</div> 
						  <input type="email" class="form-control" id="Email1" name="Email" required>
						</div>
					</div>
					<div class="form-group mb-3">
					  <label for="Password1">Password</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary"><i class="fa fa-lock"></i></span>
							</div> 
						  <input type="password" class="form-control" id="Password1" name="Password" required>					
						</div>
					</div>						
					<div class="form-group mb-3">
					  <label for="Password2">Password (again)</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary"><i class="fa fa-lock"></i></span>
							</div> 
						  <input type="password" class="form-control" id="Password2" name="Password2" required>					
						</div>
					</div>
					<div class="form-row">
						<div class="col">
							<div class="d-grid">
							  <button class="btn btn-primary" type="submit"><span class="icon-ok"></span>&nbsp;&nbsp;Submit</button>
							</div>
						</div>
					</div>
				  <input type="hidden" name="type" value="register">
				  </form>
				</div>
			</div>
		</div>
	</div>
</div>

results in

Upon Submiting I get
image

but printing the POST shows
image
Heres my logic

<?php 
print_r($_POST);
...			
if(($_SERVER['REQUEST_METHOD'] == "POST") && ($_POST['type'] == "login")) {

} else if(($_SERVER['REQUEST_METHOD'] == "POST") && ($_POST['type'] == "register"))  {
	
	try {

	  if($_POST['Troop'] == '' | $_POST['Name'] == '' || $_POST['Email'] == '' || $_POST['Password'] == '' || $_POST['Password2'] == '') {
		$popup_alert_class = 'alert-danger';
		$popup_alert_header = '<i class="fa fa-times"></i>&nbsp;nbsp;Error';
		$popup_alert_body = 'All fields are required.';
	  }
	  if(!filter_var($_POST['Email'],FILTER_VALIDATE_EMAIL)) {
		$popup_alert_class = 'alert-danger';
		$popup_alert_header = '<i class="fa fa-times"></i>&nbsp;nbsp;Error';
		$popup_alert_body = 'Email not valid.';
	  }
	  $statement = $pdo->prepare("SELECT * FROM users WHERE email=?");
	  $statement->execute([$_POST['Email']]);
	  $total = $statement->rowCount();
	  if($total) {
		$popup_alert_class = 'alert-danger';
		$popup_alert_header = '<i class="fa fa-times"></i>&nbsp;nbsp;Error';
		$popup_alert_body = 'Email exists.';
	  }
	  if($_POST['Password'] != $_POST['Password2']) {
		$popup_alert_class = 'alert-danger';
		$popup_alert_header = '<i class="fa fa-times"></i>&nbsp;nbsp;Error';
		$popup_alert_body = 'Passwords must match.';
	  }

	  $sql = "INSERT INTO users (name,email,password,token) VALUES (?,?,?,?)";
	  //echo $sql;
	  $name = $_POST['Name'];
	  $email = $_POST['Email'];
	  $password = password_hash($_POST['Password'], PASSWORD_DEFAULT);
	  $token = time();

	  $result = $pdo->prepare($sql);
	  $result->execute([$name,$email,$password,$token]);
	  
	  $link = BASE_URL.'login/registration-verify.php?email='.$email.'&token='.$token;
	  $email_message = 'Please click on this link to verify registration: <br>';
	  $email_message .= '<a href="'.$link.'">';
	  $email_message .= 'Click Here';
	  $email_message .= '</a>';
	  
	  sendMail($email, "Registration Verification", $email_message);
	  
	  $popup_alert_class = 'alert-success';
	  $popup_alert_header = '<i class="fa fa-check"></i>&nbsp;&nbsp;Register Success!';
	  $popup_alert_body = 'You will recieve an email with a confirmation link.'; 

	} catch(Exception $e) {
	  $popup_alert_class = 'alert-danger';
	  $popup_alert_header = '<i class="fa fa-times"></i>&nbsp;nbsp;Error';
	  $popup_alert_body = $e-getMessage();
	}


} else if(($_SERVER['REQUEST_METHOD'] == "POST") && ($_POST['type'] == "forgot")) {
	
  ...

} else {
...
}
?>

Is my logic right? If Trooooop is blank, why isnt the first if statement trigred in the try…catch block trigerred?

Because the only statements in the current code that can throw an exception are the PDO database statements. And in fact, you don’t want to use exceptions for validation errors, because you want to validate as many of the inputs as possible each time the form is submitted, so that the user doesn’t need to keep resubmitting the form to see all the errors. Also, when you display the form, the form fields should be ‘sticky’ and repopulate field values/selected options with any existing data so that the user doesn’t need to keep reentering data/selecting options upon an error.

Here’s a list of points for the rest of the code -

  1. Because $_POST[‘type’] can only be one value at a time, you don’t need else logic. Just if() statements or a switch/case statement.
  2. Don’t Repeat Yourself (DRY). Don’t repeat the if(($_SERVER[‘REQUEST_METHOD’] == “POST”) multiple times.
  3. You should trim all the input data, before validating it, so that you can detect if a value was all white-space characters. Since the trimmed data has a different meaning from the raw $_POST data, you should store the trimmed data in a different php array variable, then operate on the trimmed data through out the rest of the code.
  4. You should validate all inputs, storing user/validation errors in an array using the field name as the array index.
  5. Later, dependent validation steps for the same field should first test that there are no prior validation errors for the same field.
  6. After the end of the validation logic, if the array holding the user/validation errors is empty, use the submitted data.
  7. Don’t attempt to execute a SELECT query to find if data doesn’t exist. There’s a race between multiple concurrent instances of your script, where they will all find that the value doesn’t exist and attempt to insert it. The first insert query that gets executed will ‘win’ the race. All other instances will either insert duplicate data or produce a duplicate index error, depending on if you have defined the database column to be a unique index. Instead, after you have defined the database column to be a unique index, just attempt to insert the data. If the value doesn’t exist, the row of data will be inserted. If the data already exists, a database exception will be thrown. In the database exception catch logic, for the insert query, test if the error number is for a duplicate index error. If it is, setup the duplicate error message for the user (add it to the array holding the user/validation errors.) For all other database error numbers, just rethrow the exception and let php handle it.
  8. If you do have a case where you need to find how many matching rows of data there are, use a SELECT COUNT(*) … query, then fetch the count value.
  9. Every time you execute a SELECT query you should fetch all the data from that query.
  10. After you have used the submitted form data (which can produce additional errors), if there are no user validation errors, redirect to the exact same URL of the current page to cause a get request for that page. This will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded.
  11. Your sendMail() code/function should contain logic to test for errors and setup error messages for the user.
  12. If you want to display a one time success message, either store it or a flag value in a session variable, then test for the session variable, display the success message, and clear the session variable at the appropriate location in the html document.
  13. If there are user/validation errors, the code will continue on to redisplay the html document, display any errors in the array holding the user/validation errors, either all at once or individually adjacent to the field they correspond to, and redisplay the form, populating the field values/selected option with any existing data, so that the user doesn’t need to keep reentering/reselecting values over and over upon an error.
  14. Any dynamic value you output in a html context (web page, email body) should have htmlentities() applied to it to help prevent cross site scripting.

good to know, is this better

if($_SERVER['REQUEST_METHOD'] == "POST") {
  switch($_POST['type'])
    case 'login':
      //code block
      break;   
    case 'register':

	$Troop = trim($_POST['Troop']);	
	$Name = trim($_POST['Name']);
	$Email = trim($_POST['Email']);
	$Password = trim($_POST['Password']);
	$Password2 = trim($_POST['Password2']);

	$data = array($Troop,$Name,$Email,$Password,$Password2);

      	  if((empty($data[0])) || (empty($data[1])) || (empty($data[2])) || (empty($data[3])) || (empty($data[4]))) {

	    $error = "All input fields are required.";

	  }
 	  if(!filter_var($data[2],FILTER_VALIDATE_EMAIL)) {


	    $error = "Email must be in correct format.";

	  }	      
	  if($data[3] != $data[4]) {


	    $error = "Passwords don\'t match.";

	  }      
	  //how do I test for duplicate email?

	  if(!isset($error) {

	    $sql = "INSERT INTO users (troop_id,name,email,password,token) VALUES (?,?,?,?,?)";
	    $password = password_hash($data[3], PASSWORD_DEFAULT);
	    $token = time();

	    $result = $pdo->prepare($sql);
	    $result->execute([$data[0],$data[1],$data[2],$password,$token]);
	  
	    $link = BASE_URL.'login/registration-verify.php?email='.$email.'&token='.$token;
	    $email_message = 'Please click on this link to verify registration: <br>';
	    $email_message .= '<a href="'.$link.'">';
	    $email_message .= 'Click Here';
	    $email_message .= '</a>';
	  
	    sendMail($email, "Registration Verification", $email_message);

	    header('Location: '.$_SERVER['REQUEST_URI'].'#register_success');



      break;
    case 'forgot':
      //code block
      break;
    default:

then can I test and show $error by the isset() in the form?

Just a small addendum, you don’t need a dedicated hidden field; submit buttons do also support name and value attributes, which can then be checked on the server side to determine which form got submitted. I.e.

<form method="POST">
  ...
  <button name="action" value="login">Login</button>
</form>

<form method="POST">
  ...
  <button name="action" value="register">Register</button>
</form>

Notably, those buttons aren’t submit buttons :wink:

There are cases where a submit button is not a successful form element, such as when using an event listener on the button to submit a form and for some clients when an enter key is used to submit the form. Using a hidden field is general purpose and will work regardless of how the form was submitted.

1 Like

Not sure what you mean… type="submit" is the default button type is it not?

Good point. :-)

Where are the words type="submit" in your code in post 8?
<input type="submit" is a submit button.
<button is not. It’s a generic button.

You’re relying more and more heavily on Implicit Submission. Implicit Submission is how we ended up with the problem in IE where hitting enter on the form DID NOT send the button’s value in the POST payload.

Well as I said it’s the default…

https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element

Yeah, the spec said you had to submit the value, too :wink:

1 Like

You are still not using an array for the errors. The current code will only show one error at a time. By using an array to hold the user/validation errors, you can validate all the inputs at once, so that the user can see and fix all of the validation problems at once, without needing to resubmit the form after correcting each one.

At the point of displaying the form, you can test if the array holding the user/validation errors is not empty(), then either loop over the array or implode() it to display the errors.

Here are some additional points -

  1. You should have separate first and last name fields/columns, so that you can distinguish between names like Ross Martin and Martin Ross.
  2. Don’t change the name or capitalization of any particular piece of data. This is just creating more work for you keeping track of the different variations. Use the same name for any piece of data throughout the code/query.
  3. Time() values are not unique and are easy to guess/generate. You should use random_bytes() for the token generator.

Here’s example code showing the points given and how to test in the database exception catch block for a duplicate index error -

// initialization

session_start();

$data = []; // array to hold a trimmed working copy of the form data. will also receive the initial data when editing/updating existing data
$errors = []; // array to hold user/validation errors

// post method form processing
if($_SERVER['REQUEST_METHOD'] == "POST")
{
	// php has a large number of array functions that will do work for you, when operating on sets (arrays) of data
	// you can trim all the data at once, without writing out lines of code for every field
	$data = array_map('trim',$_POST); // if any field is an array, use a recursive trim call-back function here instead of php's trim

	switch($data['type'])
	{
    case 'login':
      //code block
	break;

    case 'register':
	// inputs - 'troop_id' (select/option), 'first_name', 'last_name' 'email', 'password', 'password2'

	// validate inputs
	if($data['troop_id'] === '')
	{
		$errors['troop_id'] = "Troop is required";
	}
	if($data['first_name'] === '')
	{
		$errors['first_name'] = "First Name is required";
	}
	if($data['last_name'] === '')
	{
		$errors['last_name'] = "Last Name is required";
	}
	if($data['email'] === '')
	{
		$errors['email'] = "Email is required";
	}
	else if(!filter_var($data['email'],FILTER_VALIDATE_EMAIL))
	{
		$errors['email'] = "Email must be in correct format.";
	}
	if($data['password'] === '')
	{
		$errors['password'] = "Password is required";
	}
	if($data['password2'] === '')
	{
		$errors['password2'] = "Password Confirmation is required";
	}
	if(empty($errors['password']) && empty($errors['password2']) && $data['password'] != $data['password2'])
	{
		$errors['password2'] = "Passwords don't match";
	}

	// in no errors, use the submitted data
	if(empty($errors))
	{
	    $sql = "INSERT INTO users (troop_id,first_name,last_name,email,password,token) VALUES (?,?,?,?,?,?)";
	    $stmt = $pdo->prepare($sql);
		
		try { // a 'local' try/catch to handle a specific database error
		
			$stmt->execute([
				$data['troop_id'],
				$data['first_name'],
				$data['last_name'],
				$data['email'],
				password_hash($data['password'], PASSWORD_DEFAULT),
				$token = bin2hex(random_bytes(10))
			]);
			
			// build the link get parameters in an array, then use http_build_query, which url encodes the values, to produce the query string part of the url
			$get['email'] = $data['email'];
			$get['token'] = $token;

			// apply htmlentities to external, unknown, dynamic values to help prevent cross site scripting
			$get = array_map('htmlentities',$get);
			
			$link = BASE_URL.'login/registration-verify.php?'.http_build_query($get);
			$email_message = 'Please click on this link to verify registration:<br>';
			$email_message .= "<a href='$link'>Click Here</a>";
			
			// this function should return a true/false value that you can test and setup a message for the user when it fails
			if(!sendMail($data['email'], "Registration Verification", $email_message))
			{
				$errors['email'] = 'Could not send your registration verification email. Site owner has been notified.';
				// you would log the available information about the registration request so that you can find what's causing the problem
			}

		} catch (PDOException $e) {

			if($e->errorInfo[1] != 1062) // duplicate index error number
			{
				throw $e; // re-throw the exception if not handled by this logic
			}
			// since there's only one unique index in this example, a duplicate error is for that index
			$errors['email'] = "Email address already in use";
			// if there is more than one unique index, you would build and execute a SELECT query here to find which indexes contain duplicate values
		}
	}
	
	// if no errors, success
	if(empty($errors))
	{
		$_SESSION['success_message'] = 'Your registration information has been saved. Check your email to complete the registration process.';
		die(header("Refresh:0"));		
	}
	break;

    case 'forgot':
      //code block
	break;
	}
}

Code to test for and display user/validation errors -

// output any errors
if(!empty($errors))
{
    // apply any css/markup you are using to style the output
	echo "<p>".implode('<br>',$errors)."</p>";
}

While you’re in there, it’s receive, not recieve.

got it working.
Filled out the form with 2 errors
after submitting

echo '<pre>';print_r($data);echo '</pre>';
echo '<pre>';print_r($errors);echo '</pre>';

returned
image

All seems good, but the popup form closes, but When I click the Register button, I get


Is there a way to make the form not dissapear if the array is not empty?

if(!empty($errors))   {
//make form visable
 }

and should I do

also?

1 more thing, when I enter in all the fields correctly, then submit end see whats in the SESSION array


I want to show a succes message

<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['value']) && isset($_SESSION['success_message'])){ ?>
<div id="result" class="overlay" style="visibility:visible; opacity:1">
	<div class="popup">
		<div class="content">
		  <a class="close" id="close_login" href="#">&times;</a>
			<div class="alert alert-success mb-0" role="alert">
			  <h3><i class="fa fa-check"></i>&nbsp;&nbsp;Success.</h3>
			  <hr>
			  <p><?=$_SESSION['success_message']?></p>
			</div>
		</div>
	</div>
</div>
<script>
document.getElementById("result").style.display = "none"; 
 setTimeout(function(){
  document.getElementById("result").style.display = "none"; 
  window.location.href = "<?=$_SERVER['PHP_SELF']?>";
 }, 5000); 
</script>
<?php } ?> 

ok?

ok, it seems to work, when I fill out the form with an error…I ge


but when I try again with 0 errors, I get

with this logic, shouldn’t the form dissapear and a success message appear for 5 seconds

<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['type']) && empty($errors)){ ?>
<div id="result" class="overlay" style="visibility:visible; opacity:1">
	<div class="popup">
		<div class="content">
		  <a class="close" id="close_login" href="#">&times;</a>
			<div class="alert alert-success mb-0" role="alert">
			  <h3><i class="fa fa-check"></i>&nbsp;&nbsp;Success!</h3>
			  <hr>
			  <p><?=$_SESSION['success_message']?></p>
			</div>
		</div>
	</div>
</div>
<script>
document.getElementById("login").style.display = "none"; 
document.getElementById("reqister").style.display = "none"; 
document.getElementById("forgot").style.display = "none"; 
 setTimeout(function(){
  document.getElementById("result").style.display = "none"; 
 }, 5000); 
</script>
<?php } ?> 

This probably is a separate thread at this point.

Is this PHP code… being AJAX fetched?

I dont think so

the 3 forms are an include, heres my index.php page

<?php
session_start();
include ("db/pdo_conn.php"); 
include ("login/formEngines-inc.php"); 
?> 
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link type="text/css" rel="stylesheet" href="css/styles.css"/>
    <link type="text/css" rel="stylesheet" href="css/popup.css"/>
  </head>
  <body>
<nav class="navbar navbar-expand-lg">
  <div class="container-fluid">
    <a class="navbar-brand" href="index.php">Boy Scout Tracker</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarText">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="index.php">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="about.php">About us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="requirements.php">Requirements</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="contact.php">Contact us</a>
        </li>
      </ul>
      <span class="navbar-text">
<?php
if(isset($_SESSION['user'])) {
	echo 'You&nbsp;are&nbsp;logged&nbsp;in&nbsp;as&nbsp;&nbsp;'.$_SESSION['user']['name'].'&nbsp;&nbsp;';
	echo '<a class="btn btn-danger btn-sm" href="logout.php" role="button">Logout</a>';
} else {
	echo '<a class="btn btn-outline-light btn-sm" href="#register" role="button">Register</a>';
	echo '<a class="btn btn-outline-light btn-sm" href="#login" role="button">Login</a>';
}
?>	      
	  </span>
    </div>
  </div>
</nav>  


<?php
include ("login/forms-inc.php"); 
?> 
  
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
  </body>
</html>

heres the forms-inc.php

<?php


?>
<div id="login" class="overlay">
	<div class="popup">
		<div class="content">		 
		  <a class="close" href="#">&times;</a>
			<div class="alert alert-primary mb-0" role="alert">
		      <h3><i class="fa fa-sign-in"></i>&nbsp;&nbsp;Login</h3>
			  <hr>
				<div class="alert alert-light border border-light shadow-sm" role="alert">
				  <form method="POST">
					<div class="form-group mb-3">
					  <label for="Email">Email</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary">@</span>
							</div> 
						  <input type="email" class="form-control" id="Email" name="Email" required>
						</div>
					</div>
					<div class="form-group mb-3">
					  <label for="Password">Password</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary"><i class="fa fa-lock"></i></span>
							</div> 
						  <input type="password" class="form-control" id="Password" name="Password" required>					
						</div>
					</div>
					<div class="form-row">
						<div class="col">
							<div class="d-grid">
						      <button class="btn btn-primary" type="submit"><i class="fa fa-check"></i>&nbsp;&nbsp;Submit</button>
							</div>
						</div>
					</div>
				  <input type="hidden" name="type" value="login">
				  </form>
				</div>
			  <h6 class="text-end text-secondary"><a href="#forgot">Forgot Password</a></h6>
			</div>
		</div>
	</div>
</div>
<div id="register" class="overlay">
	<div class="popup">
		<div class="content">
		  <a class="close" href="#">&times;</a>
			<div class="alert alert-primary mb-0" role="alert">
		      <h3><i class="fa fa-registered"></i>&nbsp;&nbsp;Register</h3>
			  <hr>
				<div class="alert alert-light border border-light shadow-sm" role="alert">
				  <form method="POST">
					<div class="form-group mb-3">
					  <label for="Troop">Troop</label>
					  <select class="form-select" id="Troop" name="troop_id" aria-label="Default select example">
						<option value='' selected>Select</option>
<?php
try{
    $sql = 'SELECT troop_id,name FROM troops';
            
    $result = $pdo->query($sql);
    
    $troops = $result->fetchAll();
		foreach($troops as $troop) {
		  echo '<option value="'.$troop['troop_id'].'">'.$troop['name'].'</option>';
		}
} catch(PDOException $e){
  die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
?>
					  </select>
					</div>
					<div class="form-group mb-3">
					  <label for="fName">First Name</label>
					  <input type="text" class="form-control" id="fName" name="first_name" required>
					</div>					
					<div class="form-group mb-3">
					  <label for="lName">Last Name</label>
					  <input type="text" class="form-control" id="lName" name="last_name" required>
					</div>					
					<div class="form-group mb-3">
					  <label for="Email1">Email</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary">@</span>
							</div> 
						  <input type="email" class="form-control" id="Email1" name="email" required>
						</div>
					</div>
					<div class="form-group mb-3">
					  <label for="Password1">Password</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary"><i class="fa fa-lock"></i></span>
							</div> 
						  <input type="password" class="form-control" id="Password1" name="password" required>					
						</div>
					</div>						
					<div class="form-group mb-3">
					  <label for="Password2">Password (again)</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary"><i class="fa fa-lock"></i></span>
							</div> 
						  <input type="password" class="form-control" id="Password2" name="password2" required>					
						</div>
					</div>
					<div class="form-row">
						<div class="col">
							<div class="d-grid">
							  <button class="btn btn-primary" type="submit"><i class="fa fa-check"></i>&nbsp;&nbsp;Submit</button>
							</div>
						</div>
					</div>
<?php
if(!empty($errors))
{
	echo '<div class="form-group mt-3">';
	echo '<div class="alert alert-danger" role="alert">';
	echo implode('<br>',$errors);
	echo '</div>';
	echo "</div>";
}
?>
				  <input type="hidden" name="type" value="register">
				  </form>
				</div>
			</div>
		</div>
	</div>
</div>
<div id="forgot" class="overlay">
	<div class="popup">
		<div class="content">
		  <a class="close" href="#">&times;</a>
			<div class="alert alert-primary mb-0" role="alert">
		      <h3><i class="fa fa-question"></i>&nbsp;&nbsp;Forgot Password.</h3>
			  <hr>
				<div class="alert alert-light border border-light shadow-sm" role="alert">
				  <form method="POST">
					<div class="form-group mb-3">
					  <label for="Email2">Email</label>
						<div class="input-group">
							<div class="input-group-prepend">
							  <span class="input-group-text text-secondary">@</span>
							</div> 
						  <input type="email" class="form-control" id="Email2" name="Email" required>					
						</div>
					</div>
					<div class="form-row">
						<div class="col">
							<div class="d-grid">
							  <button class="btn btn-primary" type="submit"><i class="fa fa-check"></i>&nbsp;&nbsp;Submit</button>
							</div>
						</div>
					</div>
				  <input type="hidden" name="type" value="forgot">
				  </form>
				</div>
			</div>
		</div>
	</div>
</div>
<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['type']) && empty($errors)){ ?>
<div id="result" class="overlay" style="visibility:visible; opacity:1">
	<div class="popup">
		<div class="content">
		  <a class="close" id="close_login" href="#">&times;</a>
			<div class="alert alert-success mb-0" role="alert">
			  <h3><i class="fa fa-check"></i>&nbsp;&nbsp;Success!</h3>
			  <hr>
			  <p><?=$_SESSION['success_message']?></p>
			</div>
		</div>
	</div>
</div>
<script>
document.getElementById("login").style.display = "none"; 
document.getElementById("reqister").style.display = "none"; 
document.getElementById("forgot").style.display = "none"; 
 setTimeout(function(){
  document.getElementById("result").style.display = "none"; 
 }, 5000); 
</script>
<?php } ?>