VB.NET login with a MySQL database - mysql

I do have an annoying problem here, I am not able troubleshoot this issue. My problem is that I cannot confirm my login, somewhere's a logical error because my try-catch block is not 'catching' anything, I even used breakpoints between DataBase Opening and DB.Close to see if there's any issue. Here are some screens :
So if I enter the user Gigel and his password 123 (it's encrypted) I get my false execution from my IF , 'Something's wrong out there'
Error..., anyone ?
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
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()
System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(TextBox2.Text)))
End Using
'Counter
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = #Password; "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
'Sanitising parameters
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", HashedPass))
'checker
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Me.Hide()
Else
MsgBox("Something's wrong down there")
End If
MySQLConnection.Close()
End Sub
End Class

Try this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = MD5(#Password); "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", TextBox2.Text))
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Else
MsgBox("Invalid username or password")
End If
MySQLConnection.Close()
Catch ex as Exception
MsgBox(ex.Message)
End Sub

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.

How to select from a cell in mysql and add to button.text

i'm a newbie to visual basic 2015 in visual studio community.
what i'm trying to do on load of main form
i have 7 buttons that need the text field changed to correspond with the entries in the Database. these buttons can be change to now categories by the end user down the road.
I'm using MySQL for my database. Any help would be MUCH appreciated as i have searched google and youtube and it's an endless world of OVERLOAD.
My DB Structure is as follows since i cant embed an image:
idbtncat btn_Name btn_caption PanelNo btn_image
1 btn_cat1 Pizza pnl_cat1 pizza.jpg
Public Class frm_MainConsole
Dim conn As New MySqlConnection
Sub dbconn()
Dim DatabaseName As String = "posdb"
Dim server As String = "localhost"
Dim userName As String = "root"
Dim password As String = "8943117"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
dbconn()
Dim query As String
Dim command As MySqlCommand
Dim reader As MySqlDataReader
Try
dbconn()
query = "select * from posdb.button_cat where btn_caption"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
btn_Cat1.Text = reader("btn_caption")
conn.Close()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Private Sub testDatabaseConnectionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles testDatabaseConnectionToolStripMenuItem.Click
If mnit_dbConn.Text = "DB NOT Connected" Then
dbconn()
mnit_dbConn.Text = "DB CONNECTED"
Else
mnit_dbConn.Text = "DB NOT Connected"
conn.Close()
End If
End Sub

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!

MySQL query (sum) not working in VB

I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot

KEY cannot be null - VB.net error

I need your help, guys. I'm having an error. Please see my code below:
Imports MySql.Data.MySqlClient
Public Class frmlogin
Dim conn As MySqlConnection = New MySqlConnection
Dim serverstring As String = "Server=localhost;User Id=root;Password=root;Database=dasystem"
Dim login As Boolean
Dim ds As DataSet
Dim cusds As DataSet
Dim da As MySqlDataAdapter
Dim dt As DataTable
Dim ctrshowlogin, ctrshowsearch As Integer
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim rowctr As Integer
Dim password As String
ctrshowlogin = 0
ds = New DataSet
da = New MySqlDataAdapter("select * from password", conn)
da.Fill(ds, "pword")
If cmbuser.SelectedItem = "Administrator" Then
For rowctr = 0 To ds.Tables(0).Rows.Count - 1
password = ds.Tables(0).Rows(rowctr).Item(0).ToString
If password = txtpass.Text Then
login = True
End If
Next (rowctr)
If login = True Then
MessageBox.Show("Login Successful!")
frmcomodities.Show()
Me.Hide()
cmbuser.Text = ""
ElseIf login = False Then
MessageBox.Show("Wrong Password, Please try again.")
txtpass.Focus()
End If
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Close()
End Sub
End Class
Any ideas? I'm stuck with this problem. If you could help, I'd gladly appreciate it. Thanks.
You need to either change the name of the table in the da.Fill(ds, "pword") line to match the database table name (password):
da.Fill(ds, "password")
or just remove that parameter altogether
da.Fill(ds)