That's why a username or an email address and a password is required to accessed a certain system. That username/email and password should match an existing username and password in a database.
So I have here a login form for the interface and PHP for the functionality. First is you need to construct your HTML form like the code below:
HTML Code Login
<!DOCTYPE html>
<html>
<head>
<title>PHP Addict | Login</title>
</head>
<body>
<form method="post" action="login.php">
<label for="user">Username</label>
<input type="text" class="form-control" id="user" name="user" placeholder="Username" required>
<label for="pass">Password</label>
<input type="password" id="pass" name="pass" placeholder="Password" required>
<button type="submit" name="login">Login</button>
<button type="reset">Clear</button>
</form>
</body>
</html>
Output of HTML Login
PHP Code for login
Copy and save the code below as login.php<?php
session_start();
$con = mysqli_connect("localhost","root","","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['login']))
{
$user_unsafe=$_POST['user'];
$pass_unsafe=$_POST['pass'];
$user = mysqli_real_escape_string($con,$user_unsafe);
$pass = mysqli_real_escape_string($con,$pass_unsafe);
$query=mysqli_query($con,"select * from student where user='$user' and pass='$pass'")or die(mysqli_error());
$row=mysqli_fetch_array($query);
$counter=mysqli_num_rows($query);
if ($counter == 0)
{
echo "<script type='text/javascript'>alert('Invalid Username or Password!');
document.location='index.php'</script>";
}
elseif ($counter > 0)
{
$_SESSION['id']=$row['stud_id'];
echo "<script type='text/javascript'>document.location='home.php'</script>";
}
}
?>
Explanation: The first eight (8) lines of code serves as your database connection. The purpose of the $counter is to count the number of returned rows from your table. So if returned rows is equal to zero (0), it will display Invalid Username or Password and will redirect you to index.php. Otherwise, it will store the student id to SESSION['id'] to be able to access it later and redirect you to home.php.
Reminder: Put the session_start() at the start of the login page or in any page that will access the value of SESSION['id'].
Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php and mysql here in my blog. Watch out for more upcoming tutorials related to blogging and programming. Good day! ^_^
Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php and mysql here in my blog. Watch out for more upcoming tutorials related to blogging and programming. Good day! ^_^
No comments:
Post a Comment