i have made a simple login code for my program.
On my website i have made a mysql database for the program where usernames,emails,and password are stored , i have queried the database 2 times to insert 2 accounts.
I can login without a problem with the first account but not with the second and the third so on.
anyways here’s the code :
Dim dbConn As New MySqlConnection
Dim UsernameVerify As New MySqlCommand
Dim PasswordVerify As New MySqlCommand
Dim EmailVerify As New MySqlCommand
Dim typeverify As New MySqlCommand
Dim lgnUsername As String
Dim lgnPassword As String
Dim lgnEmail As String
Dim lgntype As String
'server info
dbConn.ConnectionString = "server=*************;UserID=*******;password=********;database=*****"
Try
dbConn.Open()
UsernameVerify.Connection = dbConn
UsernameVerify.CommandText = "Select USERNAME from users"
PasswordVerify.Connection = dbConn
PasswordVerify.CommandText = "Select PASSWORD from users"
EmailVerify.Connection = dbConn
EmailVerify.CommandText = "Select EMAIL from users"
typeverify.Connection = dbConn
typeverify.CommandText = "Select TYPE from users"
lgnUsername = UsernameVerify.ExecuteScalar
lgnPassword = PasswordVerify.ExecuteScalar
lgnEmail = EmailVerify.ExecuteScalar
lgntype = typeverify.ExecuteScalar
dbConn.Close()
If ComboBox1.Text = lgnUsername And ComboBox2.Text = lgnPassword And ComboBox3.Text = lgnEmail And ComboBox4.Text = lgntype Then
Panel1.BackgroundImage = mpng2
Label5.Text = "Succesfully verified user !"
Me.Close()
Else
Panel1.BackgroundImage = mpng
Label5.Text = "Could not find user check your credentials"
ComboBox1.Focus()
End If
Catch ex As MySqlException
Label5.Text = "Error while verifying "
MessageBox.Show("Error when connecting to database|" + ex.Message)
dbConn.Dispose()
verifying.Close()
End Try
Does anyone knows how to fix this.
I already was considering using a while loop or something or is there something else ?
There’s no need for a loop, and you’re making life hard for yourself. Remember to always keep it simple.
Simple login code could look something like this:
This code gets all the user info you may require in 1 single query (good for limiting overhead on the database). The WHERE clause in the sql means it’ll only get a row where the username and password match what the user logged in with.
The
List(Of SqlParameter)simply stores the entered values for use in the sql. This helps secure the form more as sql injection is much less likely this way. I converted this List to an array here because I’m not sure if SqlCommand.Paramaters.AddRange accepts a List. One way or the other will work.The session variables are useful for displaying content that is relevant to ONLY the logged in user. You could use the userid to limit results from the database to only get things where the userid is the same as the Session(“userid”) value.
Hope this helps!