String from Database set as public string - mysql

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?)

Related

Unknown database 'database'

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.

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.

Read and Write SQL information from VB.Net

I have a linked my vb.net project to an only SQL database which holds a list of predefined email addresses. My vb form contains a 'firstname','lastname' and 'email' textbox.
How do I program vb.net to locate the text in the 'email' textbox within the database and add the fistname and lastname textbox values to the appropriate column in the same row as the located email field? (filling the gaps)
My code so far:
' Initiate SQL Connection for db4free.net on port: 3306
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=db4free.net; Port=3306; user id=username; password=password; database=databasename"
Try
MySqlConnection.Open()
Catch ex As Exception
MsgBox("The server could not be reached, check that you have internet connectivity and try again.", MsgBoxStyle.Critical, "Connection Error")
End Try
--- SQL DATABASE CONNECTION --- '
Dim Myadaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM registration WHERE email='" & emailTextBox.Text & "';"
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.CommandText = sqlquery
Myadaptor.SelectCommand = command
Dim Mydata As MySqlDataReader
Mydata = command.ExecuteReader
' SQL Entry Validation
If Mydata.HasRows = 0 Then
MsgBox("Please enter a valid E-Mail address", MsgBoxStyle.Critical, "Invalid Details")
Else
--- THE ANSWER TO MY QUESTION (write firstname and lastname into row based on email) ---
Thank you in advance, (I only just started learning SQL).
You'll want to do something like this:
If Mydata.HasRows = 0 Then
MsgBox("Please enter a valid E-Mail address", MsgBoxStyle.Critical, "Invalid Details")
Mydata.Close()
Else
Mydata.Close()
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.ConnectionText = "UPDATE `registration` SET `firstname` = #firstname,`lastname` = #lastname WHERE `email` = #email"
command.Prepare()
command.Parameters.AddWithValue("#firstname", firstnameTextBox.Text)
command.Parameters.AddWithValue("#lastname", lastnameTextBox.Text)
command.Parameters.AddWithValue("#email", emailTextBox.Text)
command.ExecuteNonQuery()
End If
You may want to adjust the SQL or the references to the UI elements to match your setup.
I've also bound the parameters into the SQL rather than creating a string by concatenating in the parameters in order to protect against SQL Injection.

VB.NET log in form using MySQL database

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.

visual basic 2012 connection must be valid and open

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