Tuesday, 25 September 2018

PHP login with PDO connection

In this tutorial, I will show you how to do PHP login with PDO connection. Unlike MySQL or SQL, PDO is not database specific. You can connect and use any database using PDO. Different databases may have slightly different connection methods, but its very easy to switch.

User_Details Table

Create the below table in the database and insert some data.
  1. CREATE TABLE IF NOT EXISTS `User_Details` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `username` varchar(50) NOT NULL,
  4. `password` varchar(50) NOT NULL,
  5. `name` varchar(50) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. )

db.php

Create a PHP file db.php and write the below codes in it. Here in this tutorial, I used MySQL as the database, you can use any other database.
  1. <?php
  2. try {
  3. $db = new PDO('mysql:host=localhost;dbname=YOUR_DATABASE_NAME;charset=utf8mb4', 'root', '');
  4. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  5. $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  6. } catch (PDOException $e) {
  7. echo "Connection failed : ". $e->getMessage();
  8. }
  9. ?>
If you want to use PostgreSQL, then you have to change the first line of the above-mentioned code. That is
  1. $db = new PDO('pgsql:host=localhost;dbname=YOUR_DATABASE_NAME;charset=utf8mb4', 'root', '');

 HTML – Login Form

This is a simple HTML form, which will take username and password to gain access to the home page. If the details are wrong it will display the appropriate error message.
  1. <form method="post">
  2. <table class="loginTable">
  3. <tr>
  4. <th>ADMIN PANEL LOGIN</th>
  5. </tr>
  6. <tr>
  7. <td>
  8. <label class="firstLabel">Username:</label>
  9. <input type="text" name="username" id="username" value="" autocomplete="off" />
  10. </td>
  11. </tr>
  12. <tr>
  13. <td><label>Password:</label>
  14. <input type="password" name="password" id="password" value="" autocomplete="off" /></td>
  15. </tr>
  16. <tr>
  17. <td>
  18. <input type="submit" name="submitBtnLogin" id="submitBtnLogin" value="Login" />
  19. <span class="loginMsg"><?php echo @$msg;?></span>
  20. </td>
  21. </tr>
  22. </table>
  23. </form>

PHP Code

At the first line, you should include the db.php. If username and password are not blank then a simple query will execute and return the row if any match found. Valid users will be redirected to the home page.
  1. <?php
  2. session_start();
  3. include("db.php");
  4. ?>
  5. <?php
  6. $msg = "";
  7. if(isset($_POST['submitBtnLogin'])) {
  8. $username = trim($_POST['username']);
  9. $password = trim($_POST['password']);
  10. if($username != "" && $password != "") {
  11. try {
  12. $query = "select * from `user_login` where `username`=:username and `password`=:password";
  13. $stmt = $db->prepare($query);
  14. $stmt->bindParam('username', $username, PDO::PARAM_STR);
  15. $stmt->bindValue('password', $password, PDO::PARAM_STR);
  16. $stmt->execute();
  17. $count = $stmt->rowCount();
  18. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  19. if($count == 1 && !empty($row)) {
  20. /******************** Your code ***********************/
  21. $_SESSION['sess_user_id'] = $row['uid'];
  22. $_SESSION['sess_user_name'] = $row['username'];
  23. $_SESSION['sess_name'] = $row['name'];
  24. } else {
  25. $msg = "Invalid username and password!";
  26. }
  27. } catch (PDOException $e) {
  28. echo "Error : ".$e->getMessage();
  29. }
  30. } else {
  31. $msg = "Both fields are required!";
  32. }
  33. }
  34. ?>

home.php

  1. <?php
  2. session_start();
  3. if(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != "") {
  4. echo '<h1>Welcome '.$_SESSION['sess_name'].'</h1>';
  5. echo '<h4><a href="logout.php">Logout</a></h4>';
  6. } else {
  7. header('location:index.php');
  8. }
  9. ?>

logout.php

  1. <?php
  2. session_start();
  3. $_SESSION['sess_user_id'] = "";
  4. $_SESSION['sess_username'] = "";
  5. $_SESSION['sess_name'] = "";
  6. if(empty($_SESSION['sess_user_id'])) header("location: index.php");
  7. ?>
You can download the complete source code from the download link below and please like and share the tutorial link to others.


0 comments:

Post a Comment