【问题标题】:Why my code is not reading the next condition in if statement为什么我的代码没有读取 if 语句中的下一个条件
【发布时间】:2019-03-24 06:41:33
【问题描述】:

为什么我的代码没有读取 if 语句中的下一个条件?

MySqlCommand cmd = new MySqlCommand("Select * from admin where Username='" + txtuser.Text + "'  and Password='" + txtpass.Text + "' ", con);

dr = cmd.ExecuteReader();
if (dr.Read())
{
    if (txtuser.Text == dr["Username"].ToString() && txtpass.Text == dr["Password"].ToString())
    {

        this.Hide();
        Form f1 = new Form1();
        f1.Show();
    }
    else if (txtuser.Text != dr["Username"].ToString() && txtpass.Text == dr["Password"].ToString())
    {
        MessageBox.Show("Incorrect Username!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        clear();
    }
    else if (txtuser.Text == dr["Username"].ToString() && txtpass.Text != dr["Password"].ToString())
    {
        MessageBox.Show("Incorrect Password!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        clear();
    }
    else if (txtuser.Text == "" & txtpass.Text == "")
    {
        MessageBox.Show("Please Enter Username and Password!", "Message", MessageBoxButtons.OK,
            MessageBoxIcon.Error);

    }
    else if (txtuser.Text == "" && txtpass.Text != "")
    {
        MessageBox.Show("Please Enter Username!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        clear();
    }
    else if (txtuser.Text != "" && txtpass.Text == "")
    {
        MessageBox.Show("Please Enter Password!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        clear();
    }
    else if (txtuser.Text != dr["Username"].ToString() && txtpass.Text != dr["Password"].ToString())
    {
        MessageBox.Show("Incorrect Username and Password!", "Message", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
        clear();
    }
}

【问题讨论】:

  • 不管您当前的问题是什么,您的代码都有两个更大的问题。 a) 您需要阅读 SQL 注入。 b) 你需要阅读stackoverflow.com/questions/42634489/…
  • else if (txtuser.Text != dr["Username"].ToString() && txtpass.Text != dr["Password"].ToString()) 想想为什么这个检查没有意义?您的查询是否可以返回一行以使 if 永远返回 true
  • 所以,现在你的代码已经改变了。哪个是真正的代码?原码,还是新码?
  • 当您调试代码时,发生了什么,您预期会发生什么(以及为什么)? 逐行调试。
  • 1.使用参数化查询。 2.不要使用ExecuteReader,选择1并使用Execute scalar。检查返回的对象是否为空或有值。 3. 不要将密码存储为纯文本。改为存储盐渍哈希。 4.不要让用户知道是密码错误还是用户名错误。您只是通过向黑客提供信息来帮助他们。总是回复“无效的用户名或密码”,

标签: c# if-statement


【解决方案1】:

如果 C# 中的 && 条件如果第一个变为 false,则不会验证下一个条件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2019-11-26
    相关资源
    最近更新 更多