How to Make Simple Login Form in PHP
In this article, you will learn how to make a simple login form in PHP.
Before following the example, you need to make sure that you have created a database name ‘codesource’, a table named ‘test’, a column named ‘username’ with type varchar(10) and another column named ‘password’ with type int(5). Then, insert the following data into the table.
Make Simple Login Form
In order to make a simple login form, you can use the mysqli_query()
method and mysqli_fetch_array()
method.
<html>
<body>
<div class="container">
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
</div>
<div>
<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="submit" id="submit" />
</div>
</div>
</form>
</div>
<?php
// Start a PHP session
session_start();
// Host name
$host = "localhost";
// User
$user = "root";
// Password
$password = "";
// Database name
$db = "codesource";
$connection = mysqli_connect($host, $user, $password, $db);
// If the connection fails
if (!$connection) {
// Display message and terminate script
die("Connection failed: " . mysqli_connect_error());
}
// If the submit button is pressed
if(isset($_POST['submit'])){
// Escape special characters in a string
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
// If username and password are not empty
if ($username != "" && $password != ""){
// Query database to find user with matching username and password
$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";
// Store query result
$result = mysqli_query($connection, $query);
// Fetch row as associative array
$row = mysqli_fetch_array($result);
// Get number of rows
$count = $row['cntUser'];
// If number of row is more than zero
if($count > 0){
// Set matched user as current user
$_SESSION['uname'] = $username;
// Display success message
echo "You are logged in!";
// Else if number of row is less than zero
} else {
// Display failed message
echo "Error! Invalid username and password.";
}
}
}
?>
</body>
</html>
Initial Login Form
Successful Login
Failed Login
Note: The mysqli_query()
method functions by executing a query on the database. In this example, mysqli_query()
method is used to search for rows that matches the username and password supplied in the login form. The mysqli_fetch_array()
method functions by fetching a result row as an associative array.