5

I want to create a working login form. Here's what I have done and this displays cannot select db.

Edited login.php file

<?php
    error_reporting(E_ALL);
    //Connection Variables:
    $dbhost = "localhost";
    $dbname = "";
    $dbuser = "";
    $dbpass = "";
try{
    //Connection to SQL:
        $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
    //Error messagin enabled:
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $e)
    {
        echo $e->getMessage();
    }


    $user = '';
    $pass = '';
    $sum = 0;
    $error_msg = "Please type a username and a password";
    if(isset($_POST['login']))
    {
        //Start a session:
        session_start();

        $user = $_POST['email'];
        $pass = $_POST['password'];
        if(empty($user) && empty($pass))
        {
            echo $error_msg;
            $pass = '';
        }
        if(empty($user) || empty($pass))
        {
            echo $error_msg;
            $user = '';
            $pass = '';
        }
        if(!empty($user) && !empty($pass))
        {
            //SQL:
            $query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
            $query->bindParam(":u", $user);
            $query->bindParam(":p", $pass);
            //Execute query:
            $query->execute();
            $number_rows = $query->fetch(PDO::FETCH_NUM);
            if($number_rows>0)
            {
                echo $user;
                $_SESSION['usern'] = $user;
                $_SESSION['passw'] = $pass;
                header("Location: ./pages/home.php");
            }
            //echo $user;
            else
            {
                echo "Invalid username or password";
                header("Location: index.html");
            }
        }
    }
    if(!isset($_POST['login']))
    {
        echo "Login button not clicked";
    }
?>

I read more and more articles on this, still I can't find a solution.

Edited HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Signin for OTMS</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="signin.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <div class="container">

      <form action="login.php" method="post" class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
      </form>

    </div> <!-- /container -->


    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="assets/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>

Please help me to find what is the error. I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.

This is the error I'm getting now:

enter image description here

database name- otmsdb
table name- login
email, passowrd, 
button name- login
0

2 Answers 2

9

Your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you: Source: Udemy Online course.

Use this code, and change the variables into yours**

<?php
session_start();
if(isset($_POST['login'])){
    $errmsg_arr = array();
    // configuration
    $dbhost     = "localhost";
    $dbname     = "your database name";
    $dbuser     = "your username";
    $dbpass     = "your password";
     
    // database connection
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // new data
     
    $user = $_POST['username'];
    $password = $_POST['password'];
     
    if($user == '') {
        $errmsg_arr[] = 'You must enter your Username';
    }
    if($password == '') {
        $errmsg_arr[] = 'You must enter your Password';
    }
     
    // query
    if (!$errmsg_arr) {
        $result = $conn->prepare("SELECT * FROM login WHERE username= :user");
        $result->execute(['user' => $username]);
        $row = $result->fetch(PDO::FETCH_NUM);
        if($row && password_verify($_POST['password'], $row['password']) {
            $_SESSION['user'] = $row;
            header("location: ./pages/home.php");
            exit;
        }
        else{
            $errmsg_arr[] = 'Username and Password are not found';
        }
    }
}
?>

HTML FORM:

<body>
<?php foreach($errmsg_arr as $msg): ?>
    <?=htmlspecialchars($msg, ENT_QUOTES) ?><br>
<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password"  value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>
</body>
Sign up to request clarification or add additional context in comments.

24 Comments

No no, just type that
see the link on udemy, and I am waiting you here to see if that works, and change connection variables and sql statements according to your informations
So I changed the code you sent according to my code. 'code' and it's displaying following erros.
Notice: Undefined index: username in C:\xampp\htdocs\OTMS\login.php on line 22 Notice: Undefined index: password in C:\xampp\htdocs\OTMS\login.php on line 23 Please type a username and a passwordPlease type a username and a password
Ok wait a second, it is easy to solve problems using PDO but do not use your previous code ever. Wait now I will tell you where the problem is
|
-1

Suggestions:

  1. echo mysql_error() to determine why the error is occurring:

    mysql_select_db("$db_name") or die("cannot select DB: " . mysql_error());

  2. Stop using deprecated functions " mysql_connect()", "mysql_query()" and friends. You'd be much better served with mysqli instead.

  3. Use Prepared Statements instead of building your "select" directly from your POST parameters.

1 Comment

Your answer is too complicated. I am just a beginner. Now only I'm starting to use php and mysql. Can you describe more simply??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.