Can someone help me with the following please.
I have created a database called dbhr and a table in it called user with two fields 'username' and 'password' having VARCHAR data type.
I have a log in form with two textboxes (tbxUsername,tbxPassword) and an OK button. I have connected my database to authenticate the username and password. But it always give me wrong password message. I don't know where I went wrong.
Please help.
I use MySQL Workbench 6.1
Thanks in advance.
Here is the VB.NET log in button code.
Imports MySql.Data.MySqlClient
Public Class Login
Dim mydbcon As MySqlConnection
Dim COMMAND As MySqlCommand
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=rootword;database=hrdb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from user where username= ' " & tbxUsername.Text & "' and password= ' " & tbxPassword.Text & "' "
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Username and password are correct")
ElseIf count > 1 Then
MessageBox.Show("Username and password are duplicate")
Else
MessageBox.Show("Username and password are wrong")
End If
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
End Try
End Sub
Please click the following links to see the database table records and data types.
Click here!
You have some extra spaces in the line
Query = "select * from user where username= ' " & tbxUsername.Text & "' and password= ' " & tbxPassword.Text & "' "
which I would change to
Query = String.Format("SELECT * FROM user WHERE username = '{0}' AND password = '{1}'", Me.tbxUsername.Text.Trim(), Me.tbxPassword.Text.Trim())
I would use String.Format() to make it clearer, less chance to overlook those extra spaces.
Related
I am trying to make a secure login for my database, using a MySQL database.
Private Sub logIn_Click(sender As Object, e As EventArgs) Handles logIn.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=Catawba;database=catawbapartnership"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from database.admininfo where admin_username= ' " & TB_UN.Text & " ' and admin_password= ' " & TB_PD.Text & " '"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Username and Password Accepted")
ElseIf count > 1 Then
MessageBox.Show("Username and Password Are Incorrect")
Else
MessageBox.Show("Username and Password Are Incorrect")
End If
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try`
This is the code, but I keep getting the error of Unknown database'database'
In MySQL Workbench, the entire database is named catawbapartnership
And the table I need to get info from is called admininfo
But, it keep saying I have entered it incorrectly. Please help!
Remove database. from your code. As a default database is in the connection you don't need to specify it in the question.
Please copy your implementation from somewhere else. This has SQL injection vulnerabilities and you should never store plain text passwords.
OWASP has a lot of guidance on being a responsible programmer.
I have a very simple application where a user will login and be redirected to the dashboard. I got the login part working, however, my next goal is to be able to store the users information for later use on other forms.
Example: User "admin" logs in successfully. I need to be able to store every column in the table for admin so that we can call the user's information for welcome messages, user information form, etc without having to query the database everytime.
I believe this can be accomplished with a class, however, I'm unsure how to rewrite my login script to save all details into a class.
I've tried creating a class, and adding Public Shared properties for each column but I'm not sure how to get every column into the class rather than just the username.
Imports MySql.Data.MySqlClient
Public Class frmLogin
'count is number of invalid login attempts
Dim count As Integer
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
count = count + 1
Dim x As New MySqlConnection
Dim admin As New MySqlCommand
Dim dr1 As MySqlDataReader
ConnectDatabase()
admin.Connection = conn
admin.CommandText = "SELECT user.username, user.password FROM user WHERE user.username = '" & txtUsername.Text & "' and user.password = '" & txtPassword.Text & "'"
dr1 = admin.ExecuteReader
If dr1.HasRows Then
'Read the data
dr1.Read()
Me.Hide()
frmDashboard.Show()
Else
MsgBox("Invalid Username or Password! " & vbCrLf & count & " out of 3 attempts remaining.")
If count >= 3 Then
MsgBox("You have exceeded the maximum number of attempts to login. Account has been disabled. Please contact OJFS helpdesk at extension 100.", MsgBoxStyle.Critical)
txtUsername.Enabled = False
txtPassword.Enabled = False
End If
End If
Connect.conn.Close()
End Sub
Dim Assistance As Boolean = False
Private Sub linkLoginHelp_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles linkLoginHelp.LinkClicked
If Assistance = True Then
Me.Height = 284
Me.CenterToScreen()
Assistance = False
txtUsername.Select()
Else
Me.Height = 463
Me.CenterToScreen()
Assistance = True
txtUsername.Select()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
End Class
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
Of course in a real application you would NEVER store passwords as plain text.
Comments in line.
'Your class might look something like this
Public Class User
Public Shared ID As Integer
Public Shared Name As String
Public Shared Department As String
Public Shared Address As String
End Class
Private count As Integer
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
count = count + 1
'keep connections local for better control
'pass the connection strings directly to the constructor of the connection
Using cn As New MySqlConnection("Your connection string")
'pass the query and the connection directly to the constructor of the commmand
Using cmd As New MySqlCommand("SELECT * FROM user WHERE user.username = #User and user.password = #Password;", cn)
'Always use parameters to avoid SQL injection
cmd.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text
'Open the Connection at the last possible minute.
cn.Open()
Using dr1 = cmd.ExecuteReader
If dr1.HasRows Then
dr1.Read()
'The indexes of the data reader depent on th order of the fields in the database
User.ID = CInt(dr1(0))
User.Name = dr1(1).ToString
User.Department = dr1(2).ToString
User.Address = dr1(3).ToString
Me.Hide()
frmDashboard.Show()
Return 'a successful login will end here
End If
End Using 'closes and disposed the reader
End Using 'close and disposes the command
End Using 'closes and dipose the connection
MsgBox("Invalid Username or Password! " & vbCrLf & count & " out of 3 attempts remaining.")
If count >= 3 Then
MsgBox("You have exceeded the maximum number of attempts to login. Account has been disabled. Please contact OJFS helpdesk at extension 100.", MsgBoxStyle.Critical)
btnLogin.Enabled = False 'Instead of the text boxes disable the button.
'If you just disable the text boxes they can keep clicking the button and opening connections.
End If
End Sub
I receive this error every time I try log in with incorrect details which should show a message-box "invalid username..." and when no details are entered it should show "please enter...
conn = New MySqlConnection
conn.ConnectionString = "server=localhost; userid=root; password=...; database=..."
Dim reader As MySqlDataReader
Try
conn.Open()
Dim Query As String
Query = "SELECT Username, Password, Admin FROM appointments.tblLogin WHERE Username='" & TextBox_Username.Text & "' AND Password='" & TextBox_Password.Text & "' "
cmd = New MySqlCommand(Query, conn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If reader.GetInt32("Admin") = 1 Then
AdminMainMenu.Show()
Me.Hide()
ElseIf reader.GetInt32("Admin") = 0 Then
MainMenu.Show()
Me.Hide()
Else
MessageBox.Show("Invalid username or password")
End If
If TextBox_Username.Text.Equals("") And TextBox_Password.Text.Equals("") Then
MessageBox.Show("Please enter a username and password")
End If
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.GetBaseException.ToString)
Finally
conn.Dispose()
End Try
The MySqlDataReader can move forward-only, once it reaches the end of the rows retrieved by the command, it cannot go back to read previous rows.
The loop used to count the number of rows moves the reader to the end of the data stream. So trying to read the Admin field result in an exception.
If TextBox_Username.Text.Equals("") And _
TextBox_Password.Text.Equals("") Then
MessageBox.Show("Please enter a username and password")
Return
End If
.... opening and executing the command code....
If reader.Read Then
Dim isAdmin = (reader.GetInt32("Admin") = 1)
If isAdmin Then
AdminMainMenu.Show()
Me.Hide()
Else Then
MainMenu.Show()
Me.Hide()
End If
Else
MessageBox.Show("Invalid username or password")
End If
conn.Close()
Notice that I have removed the loop and used a simple if/else statement around the Read method to display the error message and I have changed the reading of the Admin flag creating a boolean variable to simplify the logic inside the true part of the if block.
Said that, you need to look at how build parameterized queries because your string concatenation to build the commandtext exposes your program to Sql Injection Attacks (not to mention syntax errors if some of your textbox contains a single quote, try it...)
Consider also that from a security standpoint you should never store passwords in the database in clear text. Use always an hash of the password
What I have is a small messaging function that basically can send a message to one user or to a group of users. There are two mysql tables; one called users for the users who use the system, and another messages where the messages are stored. The system can send to specific users but when sending to a group of people, VB gives me the
InvalidOperationException was handled: connection should be open and valid
The code is given below.
Dim receiver, subject, message As String
Dim user As Integer
Dim MySqlConnection As New MySqlConnection
Dim MyAdapter As New MySqlDataAdapter
Dim command As New MySqlCommand
Dim mydata As MySqlDataReader
Private Sub sendButton_Click(sender As Object, e As EventArgs) Handles sendButton.Click
user = loginForm.user
If recieverTextBox.Text = "" And studentCheckBox.Checked = False And facultyCheckBox.Checked = True Then
subject = subjectTextBox.Text
message = messageRichTextBox.Text
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=localhost; User ID=root; password=''; database=sis_db"
Dim query = "insert into messages (date, sender, receiver, subject, message) select CURRENT_DATE, '" & user & "',user_id,'" & subject & "', '" & message & "' from users where user_type='faculty';"
Try
MySqlConnection.Open()
command.CommandText = query
MyAdapter.SelectCommand = command
mydata = command.ExecuteReader 'the error message points here'
MsgBox("Messages sent", MsgBoxStyle.OkOnly, Title:="SUCCESS!")
recieverTextBox.Clear()
subjectTextBox.Clear()
messageRichTextBox.Clear()
Catch ex As MySqlException
MsgBox("DATABASE ERROR!")
End Try
MySqlConnection.Close()
ElseIf
you can replace the select current_date with DateTime.Now instead
have you tested the connection ? its probably just a typo
Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)