4

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
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
dilk
  • 103
  • 3
  • 10

2 Answers2

10

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>
Dharman
  • 30,962
  • 25
  • 85
  • 135
alim1990
  • 4,656
  • 12
  • 67
  • 130
  • No no, just type that – alim1990 Dec 26 '15 at 07:46
  • 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 – alim1990 Dec 26 '15 at 07:47
  • So I changed the code you sent according to my code. 'code' and it's displaying following erros. – dilk Dec 26 '15 at 07:54
  • 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 – dilk Dec 26 '15 at 07:59
  • 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 – alim1990 Dec 26 '15 at 08:00
  • I don't have user name variable. I have email. – dilk Dec 26 '15 at 08:02
  • Okay, in your html form, what are the names of your user and pass inputs ? Please post the html code of your form. So if your username input is like name="usern", change the code at line 23 to $user = $_POST['usern'] – alim1990 Dec 26 '15 at 08:02
  • whatever it is sir, username or email or anything, just see yor input name and change it at line 23. Please add a html form code to your question. – alim1990 Dec 26 '15 at 08:03
  • Now I fixed it. but I'm getting another error.Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\xampp\htdocs\OTMS\login.php:42 Stack trace: #0 C:\xampp\htdocs\OTMS\login.php(42): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\OTMS\login.php on line 42 – dilk Dec 26 '15 at 08:10
  • Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\xampp\htdocs\OTMS\login.php:42 Stack trace: #0 C:\xampp\htdocs\OTMS\login.php(42): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\OTMS\login.php on line 42 ** I'm getting this error now** – dilk Dec 26 '15 at 08:12
  • put this code inside a try{} catch like this: see my edit – alim1990 Dec 26 '15 at 08:14
  • I'll edit my codes above. Still getting same error message. – dilk Dec 26 '15 at 08:17
  • Okay edit your code then I am waiting to see what is the problem, I think you have a missing variable – alim1990 Dec 26 '15 at 08:18
  • yes, and I add the error as an image. Pls see it and help me to fix it – dilk Dec 26 '15 at 08:24
  • Shouldn't we specify the database name?? – dilk Dec 26 '15 at 08:26
  • of course, specify it, and i am working on it, but specify the db name – alim1990 Dec 26 '15 at 08:29
  • database name- otmsdb, table name- login, email, passowrd, button name- login – dilk Dec 26 '15 at 08:33
  • Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'email'@'localhost' (using password: YES)' in C:\xampp\htdocs\OTMS\login.php:13 Stack trace: #0 C:\xampp\htdocs\OTMS\login.php(13): PDO->__construct('mysql:host=loca...', 'email', 'password') #1 {main} thrown in C:\xampp\htdocs\OTMS\login.php on line 13 – dilk Dec 26 '15 at 08:52
  • Okay, this isn't a code error, see your connections please. The code is clean and working properly. Make a new question displaying your codes and errors so we can help more – alim1990 Dec 26 '15 at 08:57
  • One of your parameters is wrong. It may be the password or username or db name. The code is good – alim1990 Dec 26 '15 at 08:58
  • see and read this carefully http://stackoverflow.com/questions/31154124/sqlstatehy000-1045-access-denied-for-user-usernamelocalhost-using-cakep?answertab=votes#tab-top – alim1990 Dec 26 '15 at 08:59
  • Actually I don't understand that much. Can't I do it more simpler way. – dilk Dec 26 '15 at 09:12
  • your problem is about your host user, try to see if this user exist or not, or at least try: host="localhost" and tell us about the outcome – alim1990 Dec 26 '15 at 09:30
  • You should definitely not be teaching anyone to syore unencrypted passwords. – mickmackusa Jan 13 '20 at 06:20
0

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.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 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?? – dilk Dec 26 '15 at 07:46