0

id-textbox我正在编写一个项目,有时我必须检查数据库中是否有与and的内容匹配的条目password-textbox。但我不知道如何在我的后端代码(VB)中表明查询不返回任何内容。

这是我正在使用的代码。但它以某种方式不起作用。错误消息没有提示:

Try
    myconn.Open()
    Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
    Dim smd As MySqlCommand
    Dim myreader As MySqlDataReader
    smd = New MySqlCommand(stquery, myconn)
    myreader = smd.ExecuteReader()
    If myreader.Read() = True Then
        If myreader.Item("user_ID") = IdNumb.Text Then
            If myreader.Item("password") = CurrPass.Text Then
                'some code if the user input is valid
             Else
                errorPassID.Visible = True
             End If
        Else
           errorPassC.Visible = True
        End If
    End If
    myconn.Close()
Catch ex As Exception
    Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
    Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)   myconn.Close()
End Try

将不胜感激任何帮助或建议。

4

1 回答 1

0

我将尝试检查阅读器是否返回行,如果没有,则发出错误消息。此外,不要使用字符串连接来构建查询,始终使用参数化查询

        myconn.Open()
        Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = @id"
        Dim smd = New MySqlCommand(stquery, myconn)
        smd.Parameters.AddWithValue("@id", Convert.ToInt32(IdNumb.Text))
        Dim myreader = smd.ExecuteReader()
        if Not myreader.HasRows Then
            Dim ErrorMessage As String = "alert('No user found');"
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
            myconn.Close()
            return
        else
            myreder.Read()
            ' no need to check if id is equal, you pass it as parameter to a where clause'
            If myreader.Item("password") = CurrPass.Text Then
                 'some code if the user input is valid '
            Else
                 errorPassID.Visible = True
                  ' or error message '
            End If
        End If
        myconn.Close()
    Catch ex As Exception
        Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
        myconn.Close()
    End Try

另请注意,沿线路传递明文密码是一个严重的安全漏洞。我希望您已经存储了密码的哈希值并检查它。

顺便说一句,为什么不在查询中传递密码哈希?像这样的东西:

  Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = @id AND password = @pwd"

这样,如果您返回了一条记录,则该用户已通过验证,并且您的客户端代码将很简单

于 2013-05-02T07:34:14.317 回答