Verifying StudentId and StudentPassword with mySql Database using Visual Basic - mysql

I am working on a school voting system. I Have tried this several times and there is no error but my login button doesn't work if I enter details and click login.
I use Visual Studio 2013 and would be glad if anyone can be of assistance.
Thank you
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ConnectToSQL()
End Sub
'connecting to sql method
Private Sub ConnectToSQL()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim StudentId As String
Dim StudentPassword As String
Try
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT StudentId, StudentPassword, StudentName FROM members"
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
TextBox1.Text = ""
TextBox2.Text = ""
End If
End While
Else
MsgBox("Username and password do not match")
TextBox2.Text = ""
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.Focus()
End Sub
End Class

From what I can see your problem is your first if statement:
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
This checks if the connectionstring is set to this value and will most definitely evaluate to false.
I assume that you want to set these settings and then open the connection to the database and not check if these settings are the set to a specific string
To make it work just remove this if statement and just set the connectionstring like this and then open the connection
con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then

First, I'm going to assume you have a typo here, as it's using the username and password as the same textbox:
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
Password is probably the 2nd one, forming this:
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
Since you are a student and new to this, not going to get into the parameters discussion, or SQL parameters or filtering, hashing passwords or anything like that, but a couple changes:
Your else on the not hasrows:
MsgBox("Username and password do not match")
TextBox2.Text = ""
The problem with this is that in your case, having no rows just means there's no members in the database, not really information you need, or should tell someone.
Also, you don't need to blank out the username and password if you are going to hide the form anyway. The studentFound var below is used to identify if a match was found. We want to display an error if no match was found.
So, that gives us this:
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
studentFound = True
End If
End While
If Not studentFound Then
MsgBox("Username/Password Combination Not Found")
TextBox1.Text = ""
TextBox2.Text = ""
End If

Related

Is there any way to fix this error in VBNET?

I'm working on a discord bot.
I'm currently working on the login panel (the classic MySQL login way, with the SELECT statement.).
But I've started doing a thing called 2FA, and the way that it works, is the following: If the login was successful the application should set the readytotwofactor column (in MySQL) to true. If it's true, the discord bot generates a 10 letter code, which is appearing in the twofactorcode column. The BOT knows who to send the message to by watching the username entered in the TextBox when logging in. It looks for this in MySQL, and each column (registered username) is associated with a discord ID. Based on this, the BOT knows to whom to send the code that is checked in the MySQL column, the application can identify whether the code is correct or not. Once the code has been sent, the readytotwofactor column will automatically change to false, and the code I wrote should change the value in the twofactorcode column to 0.
My problem, though, is that it doesn't work.
Here is the source code: (Form3 is the login form, and Form4 is the 2FA form.).
Imports MySql.Data.MySqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim connection As New MySqlConnection("just the login stuff")
Dim command As New MySqlCommand("SELECT * FROM karolyguilogin WHERE username=#username AND pass=#password", connection)
command.Parameters.Add("#username", MySqlDbType.VarChar).Value = TextBox1.Text
command.Parameters.Add("#password", MySqlDbType.VarChar).Value = TextBox2.Text
Dim command1 As New MySqlCommand("UPDATE `karolyguilogin` readytotwofactor SET readytotwofactor=#readytotwofactor WHERE username=#username", connection)
Dim Adapter As New MySqlDataAdapter(command)
Dim table As New DataTable()
Adapter.Fill(table)
connection.Open()
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
If TextBox2.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
If table.Rows.Count() <= 0 Then
MessageBox.Show("Helytelen felhasználónév, vagy jelszó!")
Else
command1.Parameters.Add("#readytotwofactor", MySqlDbType.VarChar).Value = "true"
MessageBox.Show("Hamarosan megkapod a 2FA kódod!")
Me.Hide()
Form4.Show()
Me.Close()
End If
connection.Close()
End Sub
End Class
Imports MySql.Data.MySqlClient
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New MySqlConnection("just the login stuff")
Dim command As New MySqlCommand("SELECT twofactorcode FROM karolyguilogin WHERE twofactorcode = #twofactorcode <> NULL", connection)
command.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = TextBox1.Text
connection.Open()
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
Dim Adapter As New MySqlDataAdapter(command)
Dim table As New DataTable()
Adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("A kódod helytelen, próbálkozz újra!")
Else
Dim command1 As New MySqlCommand("UPDATE `karolyguilogin` twofactorcode SET twofactorcode=#twofactorcode WHERE twofactorcode <> NULL", connection)
MessageBox.Show("A kódod helyes! Beléphetsz a felületre!")
command1.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = "NULL"
Me.Hide()
Form3.Hide()
Form1.Show()
Me.Close()
Form3.Close()
End If
connection.Close()
End Sub
End Class
In the first place, passwords should never be stored as plain text. I am hoping you have omitted the encryption code for brevity.
In ADO.net connections and commands need to be disposed, not just closed. A Using block will handle this for you even if there is an error.
Don't pull down the entire record. You only need to know if it exists. You don't need a DataAdapter to do this.
Do your validation outside the Using block before any database objects are created. Also, how to you expect the user to "Enter something" when you close the Form?
Use the same command for the second query, just change the CommandText. Note that we already have the #username parameter and the #readytotwofactor parameter is not needed because it can be hardcoded in the sql string.
Why hide the Form and then close it 2 lines later?
Perhaps your code doesn't work because you never execute the second command.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Validate first before the database code
If TextBox1.Text = "" OrElse TextBox2.Text = "" Then
MessageBox.Show("írj be valamit!")
Exit Sub
End If
Dim ReturnCount As Integer
Using connection As New MySqlConnection("datasource=sql11.freemysqlhosting.net;port=3306;username=sql11396664;password=eG1IbxNzLR;database=sql11396664"),
command As New MySqlCommand("SELECT Count(*) FROM karolyguilogin WHERE username=#username AND pass=#password", connection)
command.Parameters.Add("#username", MySqlDbType.VarChar).Value = TextBox1.Text
command.Parameters.Add("#password", MySqlDbType.VarChar).Value = TextBox2.Text
connection.Open()
ReturnCount = CInt(command.ExecuteScalar())
If ReturnCount = 0 Then
MessageBox.Show("Helytelen felhasználónév, vagy jelszó!")
Else
command.CommandText = "UPDATE `karolyguilogin` readytotwofactor SET readytotwofactor='true' WHERE username=#username"
command.ExecuteNonQuery()
MessageBox.Show("Hamarosan megkapod a 2FA kódod!")
Form4.Show()
Me.Close()
End If
End Using 'Closes and disposes both the command and the connection
End Sub
I assume there is some sort of trigger in the database when readytotwofactor is set to true.
You realize your Update will set all records in the karolyguilogin table to the string "NULL" not just the the user attempting to log in. If this is a multiuser database this could cause a problem.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Exit Sub
End If
Dim ReturnCount As Integer
Using connection As New MySqlConnection("datasource=sql11.freemysqlhosting.net;port=3306;username=sql11396664;password=eG1IbxNzLR;database=sql11396664"),
command As New MySqlCommand("SELECT Count(*) FROM karolyguilogin WHERE twofactorcode = #twofactorcode", connection)
command.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = TextBox1.Text
connection.Open()
ReturnCount = CInt(command.ExecuteScalar())
If ReturnCount = 0 Then
MessageBox.Show("A kódod helytelen, próbálkozz újra!")
Else
command.CommandText = "UPDATE `karolyguilogin` SET twofactorcode='NULL' WHERE twofactorcode <> 'NULL';"
MessageBox.Show("A kódod helyes! Beléphetsz a felületre!")
Form1.Show()
Me.Close()
End If
End Using 'Closes and disposes both the command and the connection
End Sub
I had fun translating the Hungarian message boxes so I could better understand your code.

Remote database connection in VB.net not working

I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form4
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Password As String
Dim Password2 As String
Dim userName As String
Try
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
Password = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Password2 = txtPassword.Text()
If Password = Password2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
Form2.Show()
Me.Hide()
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?
Don't store passwords in clear-text!
Furthermore your code is prone to sql incjection.
Nothing happens because this If will never be true:
...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...

VB.net Login with MySQL

I do not know what went wrong. Im new to vb. Can someone help me? Maybe correct my codes cause I've been spending so much time with this login form of mine. Thanks! here's my code.
By the way, I have a table with 3 columns. Username, Password and Privilege. Whenever I input my Login credentials, it only display the Msgbox Try again.
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim cn As New MySqlConnection
Dim cmd As MySqlCommand
Dim reader As MySqlDataAdapter
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim tblUser As New DataTable
Try
If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then
MessageBox.Show("Please provide your login credentials!")
Else
Dim sql As String
sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'"
Using con As New MySqlConnection(My.Settings.ConnectionString)
With cmd
.Connection = con
.CommandText = sql
End With
reader.SelectCommand = cmd
reader.Fill(tblUser)
If tblUser.Rows.Count > 0 Then
Dim userType As String
userType = tblUser.Rows(0).Item(2)
If userType = "admin" Then
MsgBox("Welcome, Admin!")
frmAdminMain.Show()
ElseIf userType = "encoder" Then
MsgBox("Welcome, User!")
MainForm.Show()
End If
Else
MsgBox("Invalid Credentials!")
End If
reader.Dispose()
End Using
End If
Catch ex As Exception
MsgBox("Try Again!")
End Try
End Sub
Add the "New" key word to your command declaration
Dim cmd As New MySqlCommand
"With" just set the properties, it does not initialize the object.

MySQL login works for me but not my friend using VB

I have a program that takes info from the user and logs them into a database using Phpmyadmin, our code is the exact same, except for my friend he can't login.
Code is here:
Both our database name, tables and columns are the EXACT same, he can register the account to the DB so it stores it, but when he tries to login with the same information it says that it was unsuccessful.
SignUpForm(THIS WORKS)
Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to DB")
Else
SQLConnection.Close()
MsgBox("Failed to connect to DB")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveAccountInformation(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
If txtPasswd.Text = txtPasswd2.Text Then
MessageBox.Show("Passwords Match!")
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
frmLogin.Show()
frmLoginScreen.Hide()
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
LOGIN FORM(THIS DOES NOT WORK FOR HIM BUT IT WORKS FOR ME)
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class frmLogin
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conStr = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQL = "SELECT * FROM accountinfodb WHERE Usernames = #uname AND `Passwords` = #pword"
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
' this object will be closed and dispose # End Using
Using dbCon As New MySqlConnection(conStr)
' the command object likewise
Using cmd As New MySqlCommand(SQL, dbCon)
dbCon.Open()
cmd.Parameters.Add(New MySqlParameter("#uname", txtUsername.Text))
cmd.Parameters.Add(New MySqlParameter("#pword", HashedPass))
' create a Using scope block for the reader
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
MessageBox.Show("Welcome, " & txtUsername.Text)
frmProduct.Show()
Else
MessageBox.Show("Oops! Login unsuccessful!(Password/Username may be wrong, or the user may not exist!")
txtUsername.Clear()
txtUsername.Focus()
txtPasswd.Clear()
End If
End Using
End Using ' close/dispose command
End Using ' close/dispose connection
End Sub
End Class
WOULD ALSO LIKE TO MENTION
I shared my files over google drive with him, so he did not copy and paste any of the code. This is the exact same files from MY computer.
Ok I found the issue, he was using an outdated version of MySQL while my version was the most up to date. I reinstalled the proper MySQL server to the newest version and it worked!

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()