2016-08-26 89 views
0

在我的网站我想允许用户从电子邮件或用户名登录。我尝试以下,但是当我去的电子邮件不具有的用户名是唯一的登录允许用户同时使用userename或电子邮件登录

if (!string.IsNullOrEmpty(username.Text) & !string.IsNullOrEmpty(password.Text)) { 
    string str = "select * from login where [email protected] or email = @email and [email protected]"; 
    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>"); 
     } 
    } 
} 
+4

你存储明文密码来代替你的代码?不要这样做。 –

+0

为什么不使用[asp.net认证](https://msdn.microsoft.com/en-us/library/eeyk640h.aspx)。它负责密码加密,用户锁定等等。 – VDWWD

回答

1

检查这个答案就在尝试用下面的代码

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

0

的缺陷是在这一行:

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) { 
+0

我调试了我的代码,我在这行看不到任何错误。我的查询生成的空结果创建问题 – SUN

+0

@SUN单用|和&一般是错误的。这些是位操作员。你应该总是使用布尔运算符||和&&布尔操作。 –

0

你或你哪里会短你查查看。

尝试例如下面这相当于你的逻辑:
SELECT 'a' WHERE 1 = 1 OR 2 = 1 AND 3 = 1

这将选择'a'
什么你以后可能:

select * from login where ([email protected] or email = @email) and [email protected]"

0

你应该考虑分组在你的查询中通过加上它们的状态就好像

select * 
from login 
where ([email protected] or email = @email) 
and [email protected]"; 
+0

我在mysql中试过这个查询。这是我的实际输入(select * from login where(username ='09840610866'或email ='09840610866')和Password ='subhash123'),但给出空的结果 – SUN

1

使用下面的sql查询。

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

并请指出您正在得到什么错误。

相关问题