Skip to main content

PDO Login Server

<?php
session_start();
$host = "localhost";
$username = "root";
$password = "";
$database = "testdb";
$message = "";
try {
    $conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
    if(empty($_POST["username"]) || empty($_POST["password"]))
    {
        $message = '<label> All fields are required</label>';
    }
    else
    {
        $query = "SELECT * FROM users WHERE username = :username AND password=:password";
        $statement = $conn->prepare($query);
        $statement-> execute(
                    array(
                        'username' => $_POST["username"],
                        'password'=>  $_POST["password"]
                    )
        );
        $count = $statement->rowCount();
        if($count>0)
        {
            $_SESSION["username"] = $_POST["username"];
            header("location:login_success.php");
        }
        else
        {
            $message = 'worng data';
        }
    }}
}
catch(PDOException $error)
    {
    $message= $error->getMessage();
    }
$conn = null;
 ?>

Comments

Popular posts from this blog

index.php

<?php include('server.php') ?> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="pdo.js"></script> <link rel="stylesheet" type="text/css" href="pdo.css"> <title>PDO Registration forms </title> </head> <body> <?php if(isset($message)) { echo '<label class="text-danger">'.$message.'</label> '; } ?> <h2> PHP login using PDO</h2> <form method="POST" action="index.php"> <div class="inputs"> <label>Enter your username </label> <input type="text" name="username"> </div> <div class="inputs"> <label> Enter your Password</label> <input type="Password" name="password"> </div> <div class="inputs"> <i...

Login_success.php

<?php session_start(); if(isset($_SESSION['username'])) { echo '<h3> You are successfully logged in, '.$_SESSION["username"]. ' </h3>'; echo '<br /><br/><a href="logout.php">Logout</a>'; } else{ header("location:index.php"); }  ?>