douliao5942 2014-08-09 21:05
浏览 40
已采纳

PHP if-else总是在mysql_num_rows等于1后显示else

I have a form named login that when is submitted sends the fields username and password to a MySQL database to check if they match. I want to echo an error when they don't match.

Here is the PHP code that goes above the form:

if (!isset($_POST['login'])) {
    mysql_connect (...);
    mysql_select_db (...);

    $username = $_POST['username'];
    $password = $_POST['password'];
    $location = $_POST['location'];

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    $sql = "SELECT * FROM members WHERE username='$username' and password='$password'";

    $result = mysql_query($sql);

    if (mysql_num_rows($result) == 1) {
        session_register("username"); 
        session_register("password"); 
        header("Location: $location");
    }
    else {
        echo "Wrong username or password.";
    }

    mysql_close();
}

And the form:

<form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input name="location" type="hidden" value="<?php echo $_GET['location']; ?>"/>
    <input name="username" type="text" value="Username" onclick="this.value=''"/>
    <input name="password" type="text" value="Password" onfocus="this.value='';this.type='password'"/>
    <input name="submit" type="submit" value="Login"/>
</form>

If I submit the form with the correct username and password the code works normally.

The problem is that the error message is always present, even before the form is submitted. Any ideas?

  • 写回答

3条回答 默认 最新

  • dpjj4763 2014-08-09 21:09
    关注

    change first line to :

     if (isset($_POST['username'])) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?