PHP登录错误以及以下消息

时间:2015-01-19 18:21:53

标签: php

我是PHP的新手。我正在尝试登录,但它总是给我以下消息:

  

'用户名或密码无效,请重试'。

如果有人能帮助我,我将非常感激。

<?php

$errors = array(
    1=>"Invalid user name or password, Try again",
    2=>"Please login to access this area"
);

$error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;

if ($error_id == 1) {
    echo '<p class="text-danger">'.$errors[$error_id].'</p>';
} elseif ($error_id == 2) {
    echo '<p class="text-danger">'.$errors[$error_id].'</p>';
}
?>
<h2 id="loginfont">Login Page</h2>
<br/><br/>
<fieldset style="font-family: Arial; background-color: lightblue; color: rgb(0,0,100)">
<legend style="font-variant: small-caps; font-weight:bold"> Login Form </legend>
<form name="LoginForm" method="POST" action="authenticate.php">
<label style="position: relative; line-height: 2; margin: 10px 0px"> Username: <input placeholder="Type K-number" style="position: absolute; margin-left: 20px; width: 15am; left: 80px" type="text" name="username" /> <span style="color: red">*</span> </label> <br/>
<label style="position: relative; line-height: 2; margin: 10px 0px"> Password: <input type="password" placeholder="Type Password" style="position: absolute; margin-left: 20px; width: 15am; left: 80px" type="text" name="password" /> <span style="color: red">*</span> </label> <br/>
<input type="submit" value="Login" /> <input type="reset" />
</fieldset>
</form>

这是我的authenticate.php代码:

    <?php 
        require 'database.php';

        session_start();

        $username = "";
        $pass = "";

        if(isset($_POST['username'])){
            $username = $_POST['username'];
        }
        if (isset($_POST['password'])) {
            $password = $_POST['password'];

        }

        echo $username ." : ".$password;

        $q = 'SELECT * FROM username WHERE username=:username AND password=:password';

        $query = $db->prepare($q);

        $query->execute(array(':username' => $username, ':password' => $password));


        if($query->rowCount() == 0){
            header('Location: index.php?err=1');
        }else{

            $row = $query->fetch(PDO::FETCH_ASSOC);

            session_regenerate_id();
            $_SESSION['sess_user_id'] = $row['id'];
            $_SESSION['sess_username'] = $row['username'];
            $_SESSION['sess_userrole'] = $row['role'];

            echo $_SESSION['sess_userrole'];
            session_write_close();

            if( $_SESSION['sess_userrole'] == "0"){
                header('Location: adminpage.php');
            }else{
                header('Location: studentpage.php');
            }               
        }
    ?>

1 个答案:

答案 0 :(得分:-3)

尝试用以下代码替换查询行:

$q = "SELECT * FROM username WHERE username='$username' AND password='$password'";

问题可能是因为您错过了用户名和密码周围的单引号。看起来你现在生成的实际查询看起来像这样,所以它不知道jsmith和hello123是什么:

SELECT * FROM username WHERE username=jsmith AND password=hello123;
相关问题