允许用户从用户名或电子邮件登录

本文关键字:用户 电子邮件 登录 许用户 | 更新日期: 2023-09-27 18:04:12

在我的网站,我想让用户从电子邮件或用户名登录。我试着跟随,但只有当我用电子邮件而不是用用户名

时才登录。
if (!string.IsNullOrEmpty(username.Text) & !string.IsNullOrEmpty(password.Text)) {
    string str = "select * from login where username=@username or email = @email and Password=@password";
    MySqlCommand cmd = new MySqlCommand(str, con);
    cmd.Parameters.AddWithValue("@username", username.Text);
    cmd.Parameters.AddWithValue("@email", username.Text);
    cmd.Parameters.AddWithValue("@password", password.Text);
    con.Open();
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    user = ds.Tables(0).Rows(0)("username");
    email = ds.Tables(0).Rows(0)("email");
    pswd = ds.Tables(0).Rows(0)("password");
    page = ds.Tables(0).Rows(0)("link");
    if (ds.Tables(0).Rows.Count > 0) {
        if (user == username.Text.ToString | email == username.Text.ToString & pswd == password.Text.ToString) {
            Response.Cookies("User_Type").Value = "manager";
            Response.Cookies("masterLogin").Value = username.Text;
            Response.Redirect(page);
        } else {
            Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>");
        }
    }
}

允许用户从用户名或电子邮件登录

检查此答案请尝试用以下代码替换您的代码

    if (user == username.Text.ToString || email == username.Text.ToString 
        && pswd == password.Text.ToString) {

使用下面的SQL查询。

select * from login where (username=@username or email = @email) and [Password]=@password // Password is a reserved keyword you cant use this as a column name.

缺陷在这一行:

if (user == username.Text.ToString | email == username.Text.ToString 
    & pswd == password.Text.ToString) {

|&替换为||&&

同样,您应该将||放入括号中,因为&&具有更高的优先级。

所以这就是解决方案:

if ((user == username.Text.ToString || email == username.Text.ToString) 
    && pswd == password.Text.ToString) {

WHERE中的OR将做空AND检查。

试试下面的例子,它相当于你的逻辑:
SELECT 'a' WHERE 1 = 1 OR 2 = 1 AND 3 = 1

这将选择'a'
你想要的可能是:

select * from login where (username=@username or email = @email) and Password=@password"

您应该考虑在查询中对条件进行分组,如

select * 
 from login 
 where (username=@username or email = @email) 
 and Password=@password";