0

I'm having trouble with my project, it's a project where multiple users within the database are involved.

I don't understand how the SqlDataReader works. Even if used twice in my code, it doesn't show any errors. Somehow, the SqlDataReader executes only the first If and not the second one. Why didn't the data reader execute the second one? Currently, I'm using Visual basic 2019 and SQL Server 2018.

Here is my code:

Imports System.Data.SqlClient

Public Class Loaning_Login
    Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click

        Dim conn As New SqlConnection

        If txtUsername.Text = "" Or txtPassword.Text = "" Then
            MessageBox.Show("Please fill in all fields.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        Else
            conn.ConnectionString = "Data Source=NECRONOMICON\SQLEXPRESS01;Initial Catalog=Register;Integrated Security=True;"

            Try
                Dim sql As String = "SELECT Username, Password FROM [Register].[dbo].[RegisterList] WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
                Dim cmd As New SqlCommand(sql, conn)
                cmd.Connection = conn
                conn.Open()
                Dim dr As SqlDataReader = cmd.ExecuteReader

                If dr.Read = True Then
                    sql = "SELECT Username, Password FROM [Register].[dbo].[RegisterList] WHERE Username ='Joshua' " & "WHERE Password ='Maria' "
                    Me.Hide()
                    MessageBox.Show("W E L C O M E !")
                    Loaner_Status10.Show()

                    If sql = "SELECT Username, Password FROM [Register].[dbo].[RegisterList] WHERE Username = 'Gabby'" & "WHERE Password = 'Nanamin' " Then
                        Me.Hide()
                        MessageBox.Show("W E L C O M E !")
                        Admin_control_interface.Show()
                    End If


                Else
                    MessageBox.Show("Incorrect Username or Password.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If

            Catch ex As Exception
                MessageBox.Show("Failed to connect to databse. System Error:" & ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End Try

            If conn.State <> ConnectionState.Closed Then
                conn.Close()

            End If
        End If
    End Sub

Upon inputting the Username (Gabby) and password (Nanamin), the Admin_control_interface form must be shown, but the Loaner_Status10 form keeps showing up

6
  • There is no SQL Server 2018 - we have 2012, 2014, 2016, 2017 and 2019 in the works .... take your pick! Commented Sep 17, 2019 at 4:55
  • 1
    Hi! Welcome to stackoverflow. Your code has serious sql-injection vulnerability. Never concatenate parameters in sql-queries, always use parameterized queries. Commented Sep 17, 2019 at 4:58
  • 1
    You should not check what the sql-clause consist of (the sql-clause should consist only of placeholders for the parameters), simply check if login is succesfull and then who (username) logged in to grant access to admin or not. Or better yet, have this data retrieved from the database when logging in. Commented Sep 17, 2019 at 5:03
  • You should check this out. Commented Sep 17, 2019 at 5:20
  • And this too. Commented Sep 17, 2019 at 5:23

2 Answers 2

1

when you select from database you get values in columns, those values are read by your datareader. to read a value you don't check if sql, just add another column which indicates if a user has admin privs or not, like a boolean but as varchar True/False "isAdmin" and check it like:

if dr.hasrows then
  if dr("isAdmin").tostring = "True" then
    'user is admin'''
  else
    'user is not admin'''
  end if
else
  msgbox("Access Denied")
end if

hope it's what you're looking for

btw

WHERE Username = 'Gabby'" & "WHERE Password = 'Nanamin' "

will give you an error cause GabbyWHERE has no space between

i would put it like this:

...WHERE Username = 'Gabby' AND Password = 'Nanamin'"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, but I still have no idea about it. I want to know how to implement a code where, if the Username and password correspond to that Username and password in the database, it would show the assigned form. Sorry, it took me a while to respond, I was with school works. My teacher didn't teach us about the commands and functions of SQL, I was looking for help through the internet.
0

The answer posted by @Devcon is what you need and should be accepted. I am just filling in a few details on how to accomplish this.

Notice that all database objects are enclosed by Using...End Using blocks. This ensures that your database objects are closed and disposed even if there is an error.

Connection strings are passed directly to the constructor of the Connection and sql statements and connections are passed directly to the constructor of the Command.

Sql statements are parameterized. Never concatenate strings to build sql statements. It opens your database to sql injection.

First, you need to add a column to the RegisterList table to indicate if a user is an administrator. We made this a Boolean column which is a bit datatype in Sql Server. You will be able to add values of True or False. You would only do this once. It would not normally be part of your program.

Private Sub AddColumn()
    Using cn As New SqlConnection("Data Source=NECRONOMICON\SQLEXPRESS01;Initial Catalog=Register;Integrated Security=True;")
        Using cmd As New SqlCommand("Alter Table RegisterList Add IsAdministrator bit;", cn)
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub

Next, update your users records to reflect their administrative status. This would normally be done as part of creating the user record with the original Insert command and not in an Update.

Private Sub AddAdminStatus()
    Using cn As New SqlConnection("Data Source=NECRONOMICON\SQLEXPRESS01;Initial Catalog=Register;Integrated Security=True;")
        Using cmd As New SqlCommand("Update RegisterList Set IsAdministrator = @IsAdmin Where Username = @Name")
            cmd.Parameters.Add("@IsAdmin", SqlDbType.Bit)
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100)
            cmd.Parameters("@IsAdmin").Value = False
            cmd.Parameters("@Name").Value = "Joshua"
            cmd.ExecuteNonQuery()
            cmd.Parameters("@Name").Value = "Gabby"
            cmd.Parameters("@IsAdmin").Value = True
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub

Finally, we can validate the input. The Select command only askes for the value of the IsAdministrator column. If there is no matching record or no value in this column then Nothing is returned.

Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    If txtUsername.Text = "" OrElse txtPassword.Text = "" Then
        MessageBox.Show("Please fill in all fields.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return
    End If
    Dim RetVal As Object
    Using conn As New SqlConnection("Data Source=NECRONOMICON\SQLEXPRESS01;Initial Catalog=Register;Integrated Security=True;")
        Using cmd As New SqlCommand("SELECT IsAdministrator FROM RegisterList WHERE Username= @UserName AND Password= @Password;", conn)
            cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100).Value = txtUsername.Text
            cmd.Parameters.Add("@Password", SqlDbType.VarChar, 100).Value = txtPassword.Text
            conn.Open()
            RetVal = cmd.ExecuteScalar 'Returns a single value, the first column or the first row of the result set
        End Using
    End Using
    If RetVal Is Nothing Then
        MessageBox.Show("Sorry, your login is not valid or your have no status assigned")
    ElseIf CBool(RetVal) Then
        MessageBox.Show("Welcome")
        Admin_control_interface.Show()
        Hide()
    Else
        Loaner_Status10.Show()
        Hide()
    End If
End Sub

Lastly, passwords should NEVER be stored as plain text. This is the fault of your instructor. Before teaching you logins the process of salting and hashing passwords should be taught.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.