In this post i will show you how to create a basic login page and check those values in the database and also do some error checking like empty values are not allowed. Here i will use xampp as a server and it has a database with 4 columns username , password, gender and name. (refer to my previous post on creating a registration form) |
<!DOCTYPE HTML> <html> <head></head> <body> <?php $servername = "127.0.0.1"; $username = "codingcorner"; $password = "yourPassword"; $dbname="sample"; $StatusValid = $StatusInValid =$unameErr = $pwdErr = " "; $uname = $pwd = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["uname"])) { $unameErr = "Username is required"; } else { $uname = test_input($_POST["uname"]); } if (empty($_POST["pwd"])) { $pwdErr= "Password is required"; } else { $pwd = test_input($_POST["pwd"]); } } ?> <h2>A Simple Login Form</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Username: <input type="text" name="uname"> <span class="error">* <?php echo $unameErr;?></span> <br><br> Password: <input type="password" name="pwd"> <span class="error">*<?php echo $pwdErr;?></span> <br><br> <input type="submit" name="submit" value="Login"> </form> <br><br> <?php $conn = mysqli_connect($servername, $username, $password,$dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql= ("SELECT username, password FROM users WHERE username='$uname' && password='$pwd'"); $result = mysqli_query($conn, $sql); if ($result && mysqli_num_rows($result) >0) { $StatusValid = "Successfully Logged in"; } else { $StatusInValid = 'Username and Password NOT Found , TRY AGAIN !!'; } mysqli_close($conn); function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } echo "STATUS :"; if ($_SERVER["REQUEST_METHOD"] == "POST") { echo $StatusValid; echo $StatusInValid; } ?> </body> </html>OUTPUT :
Initially
When Incorrect details are entered
When valid details are entered
The Entries in database are (refer previous post - developing registration form )
That's it ! We are done with our login page.
Reference : W3schools