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条)

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型