set number in button using vb 2008 - mysql

i have problem in my record database. why when click btnOut. system will save status=1
please anyone help me. to set number in button. this is code, please check if any error. thank.
I'm using vb 2008 and databse mysql
form 1
Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
Const btnIn As Integer = 1
Form1.Show()
End Sub'
Private Sub btnOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOut.Click
Const btnO As Integer = 0
Form1.Show()
End Sub
Form 2
Private Sub btnD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnD.Click
Dim command As MySqlCommand
command = New MySqlCommand
Const btnO As Integer = 0
Const btnI As Integer = 1
command.CommandText = "SEARCH INTO visitor WHERE nokp VALUES ('" & TextBox1.Text & "')"
If TextBox1.Text = "Masukkan No.I/C Anda" Or TextBox1.Text = "" Then
MessageBox.Show("Sila Masukkan No Kad Pengenalan Anda", "Mesej", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
If btnO = 0 Then
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(nok,tkhupd,status)VALUES ('" & TextBox1.Text & "','" & tkhupd & "','" & 1 & "' )"
MessageBox.Show("ok")
command.ExecuteNonQuery()
TextBox1.ResetText()
Else
If btnO = 0 Then
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(nok,tkhupd,status)VALUES ('" & TextBox1.Text & "','" & tkhupd & "','" & 1 & "' )"
MessageBox.Show("ok Out")
command.ExecuteNonQuery()
TextBox1.ResetText()
End If
End If
End If
Exit Sub
End Sub

I hate to say it, but there's just so much wrong in that code. Don't even get me started on the sql injection vulnerabilities (right now, you're just asking to get hacked). No, I'll go even more basic. Look at these two lines from your sample:
Const btnO As Integer = 0
'...
If btnO = 0 Then
'...
Else
'...
End If
btnO is a constant. It can't change. It will always be 0. Therefore, your If/Then check is just play silly: it will always be true. Anything you put in the Else block is worthless: the code can never run.

Related

Bug when displaying data on a list view VB.Net with MySQL

I recently came up with a problem that wasn't there before. On the list view part of my program, it usually displays the right data. But something happened (and I tried in vain to retrace my steps but I couldn't remember touching the codes of this part), the data on the list view suddenly started not to display properly.
The recent data that I am adding aren't showing up in the list view and instead of being posted in the bottom part of the last successful data entry, it gets inserted in the beginning of the list and it only shows blanks. But whenever I click update the data is there, it just won't display properly on the list view.
Where did I go wrong? Here's my code:
Displaying of data:
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM employee_table"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
'Listview fix
ListView1.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With ListView1
.Items.Add(TABLE.Rows(i)("id"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("emp_no"))
.Add(TABLE.Rows(i)("emp_firstnm"))
.Add(TABLE.Rows(i)("emp_midnm"))
.Add(TABLE.Rows(i)("emp_lastnm"))
.Add(TABLE.Rows(i)("dept1"))
.Add(TABLE.Rows(i)("dept2"))
.Add(TABLE.Rows(i)("position"))
.Add(TABLE.Rows(i)("schedtype"))
.Add(TABLE.Rows(i)("date_hired"))
End With
End With
Next
End Sub
Adding of data:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD=; DATABASE = cph;Convert Zero Datetime=True"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO employee_table(emp_no, emp_firstnm, emp_midnm, emp_lastnm, dept1, dept2, position, schedtype, date_hired) VALUES ('" & txtEmpno.Text & _
"','" & txtFname.Text & "','" & txtMname.Text & "','" & txtLname.Text & "','" & txtDept1.Text & "','" & txtDept2.Text & "','" & txtPosition.Text & "','" & txtSchedtype.Text & "','" & txtDatehired.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Added new record")
Dispose()
Close()
'Update
ViewRecord.LoadPeople()
End Sub

Automatic verify the Fingeprint of a user [BLOB]

Hi? I have here fingerprint scanner. I want to automatically verified user's fingerprint when they are touching the scanner but I cant.
I have here codes but before you verify the fingerprint if it correct, you need to put first his/her userID.
This is my codes:
Private Sub SaveButton_Click() Handles SaveButton.Click
Using files As New IO.MemoryStream
Template.Serialize(files)
objconn.Open()
If Not Template Is Nothing Then
Dim cmd = New MySqlCommand("INSERT INTO employeefp " +
"SET id=#id, " +
"FP=#FP " +
" ", objconn)
cmd.Parameters.Add(New MySqlParameter("#id", TextBox1.Text))
cmd.Parameters.Add(New MySqlParameter("#FP", Template.Bytes))
cmd.ExecuteNonQuery()
objconn.Close()
MessageBox.Show("Template Successfuly Saved.", "Finger Enrolled")
End If
End Using
End Sub
And this my verify button codes:
Private Sub VerifyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VerifyButton.Click
If TextBox1.Text = "" Then
MsgBox("Please input id no.", MsgBoxStyle.Information)
Else
objconn.Open()
Dim cmd As New MySqlCommand("SELECT * FROM employeefp where id ='" & TextBox1.Text & "'", objconn)
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
If rdr.HasRows Then
Dim Verifier As New VerificationForm
Verifier.Verify(Template)
Else
MsgBox("The id doesn`t exist", MsgBoxStyle.Information)
End If
End If
objconn.Close()
End Sub
i thought its all about in templates.bytes but i don't know what will I do.
Thanks in advance. Hope you will help me.

error when update data ms access using visual basic 2010

**i have simple application, but i dont know how to fix it.
this pic when i try to edit my database--> http://i861.photobucket.com/albums/ab171/gopak/sa_zps5a950df5.jpg
when i click button edit i want my access data will be update.this is my code..
thanks for your advice**
Imports System.Data.OleDb
Public Class Form2
Public cnstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gop's\Downloads\admin site\admin site\admin site\bin\Debug\data_ruangan.accdb"""
Public cn As New OleDbConnection
Public cmd As New OleDbCommand
Public adaptor As New OleDbDataAdapter
Private Sub logout_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logout_btn.Click
Form1.Show()
Me.Close()
End Sub
Private Sub exit_btn_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exit_btn.Click
Dim a As Integer
a = MsgBox("Are you sure want to exit application?", vbInformation + vbYesNo, "Admin Site Virtual Tour Application")
If a = vbYes Then
End
Else
Me.Show()
End If
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Data_ruanganDataSet.data_ruangan' table. You can move, or remove it, as needed.
Me.Data_ruanganTableAdapter.Fill(Me.Data_ruanganDataSet.data_ruangan)
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i = DataGridView1.CurrentRow.Index
Label7.Text = DataGridView1.Item(0, i).Value
txtName.Text = DataGridView1.Item(1, i).Value
txtLocation.Text = DataGridView1.Item(2, i).Value
txtCapacity.Text = (DataGridView1.Item(3, i).Value).ToString
txtOperational.Text = (DataGridView1.Item(4, i).Value).ToString
txtInformation.Text = DataGridView1.Item(5, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'If txtName.Text <> "" And txtLocation.Text <> "" And txtCapacity.Text <> "" And txtOperational.Text <> "" And txtInformation.Text <> "" Then
Dim i = DataGridView1.CurrentRow.Index
Dim ID = DataGridView1.Item(0, i).Value
Dim cmd As New OleDb.OleDbCommand
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.Connection = cn
cmd.CommandText = ("update data_ruangan set Name = '" & txtName.Text & _
"',Location = '" & txtLocation.Text & "',Capacity = '" & txtCapacity.Text & _
"',Operational_Hours ='" & txtOperational.Text & "',Information = '" & txtInformation.Text & ";")
cmd.ExecuteNonQuery()
cn.Close()
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
'End If
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
Try to use a parameterized query to execute your code. The error message is relative to the fact that you haven't initialized your connection with the information contained in the ConnectionString.
Here an example on how to do that...... but......
Dim cmdText = "update data_ruangan set [Name] = ?,Location = ?,Capacity = ?, " & _
"Operational_Hours =?,Information = ?;"
Using cn = new OleDbConnection( cnstring )
Using cmd = OleDb.OleDbCommand(cmdText, cn)
cn.Open
cmd.Parameters.AddWithValue("#p1", txtName.Text)
cmd.Parameters.AddWithValue("#p2", txtLocation.Text)
cmd.Parameters.AddWithValue("#p3", txtCapacity.Text)
cmd.Parameters.AddWithValue("#p4", txtOperational.Text)
cmd.Parameters.AddWithValue("#p5", txtInformation.Text)
'''' WARNING ''''
' WITHOUT A WHERE STATEMENT YOUR QUERY WILL UPDATE
' THE WHOLE TABLE WITH THE SAME VALUES
'''' WARNING ''''
cmd.ExecuteNonQuery()
End Using
End Using
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
This code updates all the records of your table with the same value, so, unless you have only one record and update Always the same record you need to add a WHERE condition to your command.
Also, the NAME word is a reserved keyword in Access 2007/2010 and it is better to encapsulate that word with square brackets to avoid a syntax error message.
I have also removed the global variable OleDbConnection and used a local one that will be closed and destroyed when the code exits from the Using statement. This is the correct way to handle disposable objects, in particular every connection object is Always to be used in this way to release as soon as possible the expensive unmanaged resource used by the object.

Limiting the time in and time out in a day in VB.NET?

I have developed a time monitoring system using fingerprint where the employee will scan his/her finger then it will record the time in and time out. But my problem is logging in and logging out by the employee is unlimited. Is there a solution where the employee can log in and log out ONCE IN A DAY? Every employee will log in and log out once. Here is my code for my Daily Time Record Form: (Im using visual studio 2010/Digital Persona UareU for my scanner)
Imports MySql.Data.MySqlClient
Imports System.Windows.Forms
Imports DPFP
Public Class frmDTR
Dim counter As Integer = 0
Dim oConn As New MySqlConnection(ConnectionString.ConnString)
Private matcher As DPFP.Verification.Verification
Private matchResult As DPFP.Verification.Verification.Result
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Me.Close()
End Sub
Public Sub SEARCH_EMPLOYEE()
Try
'Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_records WHERE ID_Number='" & strid & "'" 'check tag number if existing
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
With Me
'plot the data into controls
.txtID.Text = reader(1).ToString
.txtFirst.Text = reader(2).ToString
.txtMiddle.Text = reader(3).ToString
.txtLast.Text = reader(4).ToString
.txtAge.Text = reader(5).ToString
.txtBday.Text = reader(6).ToString
.txtDepartment.Text = reader(7).ToString
.txtYear.Text = reader(8).ToString
.txtGender.Text = reader(9).ToString
.txtContact.Text = reader(10).ToString
.txtMobile.Text = reader(11).ToString
.txtEmail.Text = reader(12).ToString
'fetch image from database
Dim imgBytes() As Byte = reader("image") 'image field
Dim image As Bitmap = New Bitmap(New System.IO.MemoryStream(imgBytes)) 'convert binary to image
.ProfilePic.Image = image 'show picture to picture box
End With
Call LOG_EMP() 'look up if login /log out
Timer1.Enabled = True
End While
Else
'Me.lblStatus.Text = "ID not recognized!"
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
Public Sub LOG_EMP()
Try
' Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_logs WHERE ID_Number='" & strid & "' AND Time_Out='Null'"
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
End While
'logout
Call EMP_LOGOUT()
Else
'log in
Call EMPT_LOGIN()
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
'insert login data
Public Sub EMPT_LOGIN()
' Connect to Database
GlobalFunctions.db_connect()
Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
command = New MySqlCommand("INSERT INTO employee_logs values('','" & txtID.Text & "','" & txtFirst.Text & "','" & txtMiddle.Text & "','" & txtLast.Text & "','" & txtDepartment.Text & "','" & Date.Today & "','" & TimeOfDay & "','Null') ", GlobalFunctions.connection, transaction)
command.ExecuteNonQuery()
transaction.Commit()
'sms = txtFirst.Text & " Enter the Building Premises #" & Now 'actual sms
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Welcome!" & txtFirst.Text)
Me.lblStatus.Text = "Successfully Logged IN! Welcome!" 'set status to login
'Will_SendSMS() 'send sms to number
Catch ex As MySqlException
MessageBox.Show("Error in inserting new record! Error: " & ex.Message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
'close connections
GlobalFunctions.connection.Close()
End Sub
Public Sub EMP_LOGOUT()
' Connect to Database
GlobalFunctions.db_connect()
' Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
GlobalFunctions.execute_nonquery("Update employee_logs set Time_Out='" & TimeOfDay & "' WHERE ID_Number='" & strid & "' AND Time_Out='Null' AND Date='" & Date.Today & "'")
transaction.Commit()
'sms = txtFirst.Text & " Left the Building Premises #" & Now & "Powered by: " ' actual sms to be sent
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Goodbye!" & txtFirst.Text)
lblStatus.Text = "Successfully Logged OUT! Goodbye!" ' set status to logout
'Will_SendSMS() 'send sms
Catch ex As MySqlException
MessageBox.Show("Error in updating a record! Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
' close connections
GlobalFunctions.connection.Close()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'counter for display
counter += 1
If counter = 6 Then
Call ClearTextBox(Me)
lblStatus.ForeColor = Color.Lime
Me.lblStatus.Text = "Please scan your finger....."
Lblverify.ForeColor = Color.Black
Lblverify.Text = "Status"
ProfilePic.Image = Nothing
Timer1.Enabled = False
counter = 0
End If
End Sub
Private Sub frmDTR_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Try
Me.VerificationControl.Focus()
Catch ex As MySqlException
MessageBox.Show("System Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub frmDTR_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
matcher = New Verification.Verification()
matchResult = New Verification.Verification.Result
Me.VerificationControl.Focus()
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Please scan your finger")
End Sub
Private Sub VerificationControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus) Handles VerificationControl.OnComplete
Dim strSQL As String = "Select * from finger_template"
Dim oDa As New MySqlDataAdapter(strSQL, oConn)
Dim dt As New DataTable
Dim dr As DataRow
Try
oDa.Fill(dt)
For Each dr In dt.Rows
Lblverify.ForeColor = Color.Red
Lblverify.Visible = True
Dim bytes As Byte() = Nothing
bytes = dr.Item("byte_template")
Dim tmplate = New DPFP.Template()
tmplate.DeSerialize(bytes)
matcher.Verify(FeatureSet, tmplate, matchResult)
If matchResult.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
strid = dr.Item("Account_ID")
Call SEARCH_EMPLOYEE()
Exit For ' success
End If
If Not matchResult.Verified Then EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
Lblverify.Text = "Status"
lblStatus.Text = "Unrecognize fingerprint....."
Lblverify.ForeColor = Color.Red
lblStatus.ForeColor = Color.Red
Timer1.Start()
Next
Catch ex As Exception
End Try
End Sub
End Class
This is very nice that you are developing this logic. Actually I have come a crossed YOUR question. Now I can recommend you some vb.net code using back end MS ACCESS 2007 .well You just validate when an employee logged in then put this code after log In button or what ever you are using .
Dim cmd1 as oledbcommond
cmd1 = New OleDbCommand("SELECT * FROM LOGTIME WHERE timein<>null and timeout<>null and dt='" & Label8.Text & "' and eid='" & txtemid.Text & "' ", cn)
dr = cmd1.ExecuteReader()
If dr.Read Then
MessageBox.Show("Already this Employee ID contains today's attendance,now you can't Log again", "Information On Your ID", MessageBoxButtons.OK, MessageBoxIcon.Information)
cmd1.Dispose()
cn.Close()
Exit Sub
End If
just follow the steps
Use normal login button which will validate for user
then if the authenticate user then show his login time in another textbox in the same form.and
use one more textbox to show the logout time ,now
1)use two buttons a)button1 as logintime button and b)button2 as logout time button
2)Then write code to add the login time into the data base,and for ur better understanding put one message box too which will shows the"Time in added to the database" and after that put the above code which will validate the current day attendance if the employee wants to login twice or thrice in a day this code will not allow him to login again only once he/she can ... and code the above behind the login button
note:-keep in mind that all the procedure will work after the employee log out ..Hope this will help you out..

What's Causing My If Statement To Be Skipped?

I have an embedded IF statement that should execute following a Database query. However, I noticed at run-time that the entire statement is not being evaluated at all (the one right after While dbData.Read()). What am I doing wrong?
HERE'S THE CODE:
Private Sub ButtonNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonNew.Click
If TextBoxSearch.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxSearch.Focus()
Else
Try
Dim dbConn As MySqlConnection
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting")
Dim account As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM customer WHERE accountNumber = '" & TextBoxSearch.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows Then
'MessageBox.Show("Customer record already exists!")
Call recordExists()
account = False
Call lockForm()
TextBoxSearch.Focus()
Me.Refresh()
Else
'dbData.Close()
account = True
TextBoxAccount.Text = TextBoxSearch.Text
TextBoxAccount.BackColor = Color.LightGray
TextBoxAccount.TabStop = False
Call unlockForm()
TextBoxLastName.Focus()
ButtonSubmit.Visible = True
Me.Refresh()
End If
End While
dbData.Close()
dbCmd.Dispose()
dbAdapter.Dispose()
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
End If
End Sub
If dbData.Read() returns False, then it will not enter your loop and therefore the If statement will not be executed. If there are no rows to be read, then Read always returns False, so the If statement is useless where it's at. You need to move that If statement up so that the while loop is inside the If block:
If dbData.HasRows Then
While dbData.Read()
' ...
End While
Else
' ...
End If