Check SQL Update - mysql

Can someone help me how to check if my database is already been update after I make an edit, here are my codes.. my code is just to make an edit and after that update it on the database, what I dont know is how to check if the update happen..
Dim dT As DataTable = MyDB.ExecCommand("SELECT `Field Name` FROM `tblfield` ORDER BY `Field Order`", "wellsfargo").Tables(0)
For i As Integer = 1 To flp.Controls.Count - 1
Application.DoEvents()
Dim xHead As uHead = DirectCast(flp.Controls(0), uHead)
Dim xCont As uControl = DirectCast(flp.Controls(i), uControl)
Dim sSQL As String = ""
Dim dZ As DataTable = MyDB.ExecCommand("SELECT * FROM `" + MyJob + "` WHERE `Record Number`='" + rNum + _
"' AND `Line Number`='" + xCont.lblLine.Text.Trim.Replace("'", "\'") + "'", "wellsfargo").Tables(0)
If dZ.Rows.Count <> 0 Then
sSQL = "UPDATE `" & MyJob & "` SET "
sSQL = sSQL + "`Orig Document Begin ID`='" + xHead.txtOrigBegDoc.Text.Trim + "'"
sSQL = sSQL + ",`Orig Document End ID`='" + xHead.txtOrigEndDoc.Text.Trim + "'"
sSQL = sSQL + ",`Beg Doc`='" + xHead.txtBegDoc.Text.Trim + "'"
sSQL = sSQL + ",`End Doc`='" + xHead.txtEndDoc.Text.Trim + "'"
sSQL = sSQL + ",`Loan Number`='" + xHead.txtLoan.Text.Trim + "'"
sSQL = sSQL + ",`Page Count`='" + xHead.txtPage.Text.Trim + "'"
sSQL = sSQL + ",`Path`='" + xHead.txtPath.Text.Trim + "'"
sSQL = sSQL + ",`File Number`='" + xHead.txtFileNumber.Text.Trim + "'"
sSQL = sSQL + ",`Settlement`='" + xHead.txtDate.Text.Trim + "'"
sSQL = sSQL + ",`Long and Foster`='" + xHead.txtLaF.Text.Trim + "'"
sSQL = sSQL + ",`Comment`='" + xHead.txtComm.Text.Trim + "'"
sSQL = sSQL + ",`Description`='" + xCont.cboDesc.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Amount`='" + xCont.txtAmount.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Payee`='" + xCont.txtPayee.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Borrower`='" + xCont.txtBorrower.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Seller`='" + xCont.txtSeller.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Prosperity Borrower`='" + xCont.txtPBorrower.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL + ",`Prosperity Seller`='" + xCont.txtPSeller.Text.Trim.Replace("'", "\'") + "'"
sSQL = sSQL & " WHERE `Record Number` = '" & rNum & _
"' AND `Line Number`='" + xCont.lblLine.Text.Trim.Replace("'", "\'") + "'"
MyDB.ExecQuery(sSQL, "wellsfargo")
Else
Dim sColumn As String = ""
For z As Integer = 0 To dT.Rows.Count - 1
If z = 0 Then
sColumn = "`" & dT.Rows(z).Item(0).ToString & "`"
Else
sColumn = sColumn & ",`" & dT.Rows(z).Item(0).ToString & "`"
End If
Next
sSQL = "INSERT INTO `" + MyJob + "` (" + sColumn + ") VALUES (" + _
"'" + rNum + "'," + _
"'" + xHead.txtOrigBegDoc.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtOrigEndDoc.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtBegDoc.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtEndDoc.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtLoan.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtPage.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtPath.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtFileNumber.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtDate.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtLaF.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xHead.txtComm.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.lblLine.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.cboDesc.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtAmount.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtPayee.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtBorrower.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtSeller.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtPBorrower.Text.Trim.Replace("'", "\'") + "'," + _
"'" + xCont.txtPSeller.Text.Trim.Replace("'", "\'") + "')"
MyDB.ExecQuery(sSQL, "wellsfargo")
End If
Next
MsgBox("Record successfully modified!", MsgBoxStyle.Information, Me.Text)

Usually not too much sense to check - exception will be thrown if something was going wrong.
You can wrap it into stored procedure and check ##rowcount variable.
Or really just make new select to read changing data.

Related

run two or more queries on one button click

I want to insert data in two different table on button click. So there are 2 insert queries with different credentials. The first insert query working properly but second is not executing. Here what I tried.
Try
Dim str1 As String = "INSERT INTO yogaClasses (`yogaID`,`name`, `category`, `websiteName`, `email`, `phone1`, `phone2`, `mobileNumber`, `buildingName`, `streetName`, `landmark`, `areaName`, `city`, `State`, `zipCode`, `address`, slotTime1From, `slotTime1To`, `slotTime2From`, `slotTime2To`, fees, `overview`, `establishment`, `newBatchStart`, `yogaType`, `facilities`, payment, `status`, `username`, `password`) values ('" + ID + "','" + name + "', '" + businessCategory + "', '" + website + "', '" + email + "', '" + phoneNo1 + "', '" + phoneNo2 + "', '" + mobileNumber + "', '" + building + "', '" + street + "', '" + landpoint + "', '" + area + "', '" + city + "', '" + stateName + "', '" + zipCode + "', '" + fulladdress + "', '" + slot1A + "', '" + slot1B + "', '" + slot2A + "', '" + slot2B + "', '" + feesPay + "', '" + about + "', '" + foundYear + "', '" + startnewBatch + "', '" + selectedYoga + "', '" + selectedFacility + "', '" + payments + "', 'active', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
Try
Dim str2 As String = "INSERT INTO yogaAgeGroup (`6-15`, `16-20`, `21-25`, `26-30`, `31-35`, `35+`, `yogaID`) values('" + ageup1.Text + "', '" + ageup2.Text + "', '" + ageup3.Text + "', '" + ageup4.Text + "', '" + ageup5.Text + "', '" + ageup6.Text + "', '" + TextId.Text + "')"
Dim str3 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str2
command.Connection = con
adapter.SelectCommand = command
con.Open()
str3 = command.ExecuteReader
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
The second query not executing. What I am doing wrong in this? Or Is it possible to execute both query in one?
Problem (in your 1st query)
con.Close()
Response.Redirect("business-added.aspx")
Move this line after second query con.Close()
Response.Redirect("business-added.aspx")
Because this line will redirect you to another page, so the rest of code won't be execute

Edit Update not working on MS Access?

I'm new to MS Access. This is a basic stuff. I'm doing an edit button in MS Access forms, but I keep getting runtime errors. Here it is the code:
CurrentDb.Execute " UPDATE FLIGHT SET " & _
"STD= ' " & Me.Text3 & " ' " & _
",Destination = ' " & Me.Text5 & " ' " & _
",Remark = ' " & Me.Text7 & " ' " & _
",ETD = ' " & Me.Text9 & " ' " & _
",ATD = ' " & Me.Text11 & " ' " & _
",OFBL = ' " & Me.Text13 & " ' " & _
",CAR= ' " & Me.Text15 & " ' " & _
",Nature = ' " & Me.Text17 & " ' " & _
",REG_N0 = ' " & Me.Text19 & " ' " & _
"WHERE FLIGHT_NR = " & Me.Text0
flightsubform.Form.Requery
Is the Field FLIGHT_NR a integer field (1,145) or a text field (KQ145)?
If its a integer field you might need to change your Where statement to capture Me.Text0 as an integer as below:
" WHERE FLIGHT_NR = " & int(Me.Text0)
If its a text field you might need to add quotes around your Me.Text0 value to capture it as text:
" WHERE FLIGHT_NR = " & " ' " & Me.Text0 & " ' "
Edit:
Change your code for debugging as follows:
My_SqlText = " UPDATE FLIGHT SET " & _
"STD= ' " & Me.Text3 & " ' " & _
",Destination = ' " & Me.Text5 & " ' " & _
",Remark = ' " & Me.Text7 & " ' " & _
",ETD = ' " & Me.Text9 & " ' " & _
",ATD = ' " & Me.Text11 & " ' " & _
",OFBL = ' " & Me.Text13 & " ' " & _
",CAR= ' " & Me.Text15 & " ' " & _
",Nature = ' " & Me.Text17 & " ' " & _
",REG_N0 = ' " & Me.Text19 & " ' " & _
" WHERE FLIGHT_NR = " & " ' " & Me.Text0 & " ' "
Debug.print My_SqlText 'Will print it to immediate window for inspection
CurrentDb.Execute My_SqlText
UPDATE FLIGHT SET STD= ' 4:55:00 PM ' ,Destination = ' ATH ' ,Remark = ' DEP ' ,ETD = ' ' ,ATD = ' 5:15:00 PM ' ,OFBL = ' 5:05:00 PM ' ,CAR= ' A3 ' ,Nature = ' J ' ,REG_N0 = ' ZA_A309 ' WHERE FLIGHT_NR = ' A3 847 '
UPDATE FLIGHT SET STD= ' 4:55:00 PM ' ,Destination = ' ATH ' ,Remark = ' DEP ' ,ETD = ' ' ,ATD = ' 5:15:00 PM ' ,OFBL = ' 5:05:00 PM ' ,CAR= ' A3 ' ,Nature = ' J ' ,REG_N0 = ' ZA_A309 ' WHERE FLIGHT_NR = ' A3 847 '

Vb.net and MySQL issue

When I click on save, I get the message:
You have an error in your SQL syntax;Check the manual that corresponds to your mySQL Server version for the right Syntax to use near 'idDrug=21' at line 21
Here is my code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim i As Integer
Dim xid As Integer
Dim xQTY(0) As Integer
Dim xQTY_ID(0) As Integer
Dim xCount As Integer
Dim xCounter_ID(0) As Integer
'Dim sqlstrx(5) As String
xid = 0
If lstitems.Items.Count > 0 Then
If Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO orders (CustID, Cust_Name, order_date) " & _
"VALUES (" & txtcustid.Text & ", " _
& "'" & txtcustname.Text & "', " _
& "'" & Format(dttoday.Value, "yyyy-MM-dd") & "')"
ExecuteSQLQuery(sqlSTR)
sqlSTR = "SELECT * FROM orders ORDER BY order_no DESC"
ExecuteSQLQuery(sqlSTR)
xid = sqlDT.Rows(0)("order_no")
For i = 0 To lstitems.Items.Count - 1
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, Unit_Cost, qty, totalcost) " & _
"VALUES (" & xid & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& "'" & lstitems.Items(i).SubItems(2).Text & "', " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(3).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
Next
Else
'delete first
For i = 0 To UBound(deleteID)
ExecuteSQLQuery("DELETE FROM Orders_detail WHERE order_no =" & txtorderno.Text & " AND idDrug =" & deleteID(i))
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity +" & Delete_QTY(i) & _
" WHERE idDrug =" & deleteID(i)
ExecuteSQLQuery(sqlSTR)
Next
For i = 0 To UBound(deleteID)
ReDim deleteID(i)
deleteID(i) = 0
Next
del = 0
'--
'If lstitems.Items.Count > 0 Then
For i = 0 To lstitems.Items.Count - 1
'MsgBox(stockID & " " & lstitems.Items(i).Text)
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " AND idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
ReDim Preserve xQTY(i), xQTY_ID(i)
xQTY(i) = sqlDT.Rows(0)("QTY")
'xQTY_ID(i) = sqlDT.Rows(0)("Item_ID")
End If
'MsgBox(sqlDT.Rows(0)("QTY"))
Next
For i = 0 To lstitems.Items.Count - 1
'MsgBox(xQTY_ID(i))
If lstitems.Items(i).Index <= (UBound(xQTY)) Then
If CDbl(lstitems.Items(i).SubItems(4).Text) < xQTY(i) Then
'MsgBox(xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text))
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE Order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockBalances SET ItemQuantity = ItemQuantity + " & (xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
ElseIf CDbl(lstitems.Items(i).SubItems(4).Text) > xQTY(i) Then
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE Stockbalances SET ItemQuantity = ItemQuantity - " & (CDbl(lstitems.Items(i).SubItems(4).Text) - xQTY(i)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
End If
End If
Next
' End If
'search for new item
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " ORDER BY Order_Dtl ASC"
ExecuteSQLQuery(sqlSTR)
xCount = sqlDT.Rows.Count
For i = 0 To sqlDT.Rows.Count - 1
ReDim Preserve xCounter_ID(i)
xCounter_ID(i) = sqlDT.Rows(i)("idDrug")
' xCount = i + 1
Next
'check
If lstitems.Items.Count > xCount Then
For i = 0 To lstitems.Items.Count - 1
If i > UBound(xCounter_ID) Then
'MsgBox(lstitems.Items(i).Text)
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, price, qty, totalcost) " & _
"VALUES (" & txtorderno.Text & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(0).Text & "', " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& lstitems.Items(i).SubItems(2).Text & ", " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(4).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
Next
End If
End If
Else
MsgBox("Can't save without details !!", MsgBoxStyle.Exclamation, xTitlename)
Exit Sub
End If
MsgBox("Record has been saved !!", MsgBoxStyle.Information, xTitlename)
sqlSTR = "SELECT distinct orders.order_no AS 'Order No.', Cust_Name as 'Customer Name', order_date AS 'Date', sum(totalcost) AS 'TOTAL DUE' FROM orders_detail " & _
"INNER JOIN orders ON orders_detail.order_no = orders.order_no " & _
"WHERE order_date ='" & Format(dttoday.Value, "yyyy-MM-dd") & "' GROUP BY orders.order_no, Cust_Name, order_date"
FillListView(ExecuteSQLQuery(sqlSTR), FrmORDERLIST.lstorder, 0)
Me.Close()
End Sub
It is impossible to fix all of your code and to be precise what is the exact cause of your error.
Suffice to say that you never should do a database application using that kind of string concatenation approach. Any of your text fields could cause the error because it contains single quotes or any of your date items could cause the error because it is not formatted how the database requires. (Same for decimals and other floating point values).
To solve this problems (and to avoid the dangerous Sql Injection scenarion) exists the parameterized queries approach.
So, just an example on what you need to do for every line of your sql commands
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, " & _
"Unit_Cost, qty, totalcost) VALUES (" & _
"#id, #iddrug, #dname,#unit, #qty, #total)"
Using cmd = new MySqlCommand(sqlStr, connection)
cmd.Parameters.AddWithValue("#id", xid)
cmd.Parameters.AddWithValue("#idrug", Convert.ToInt32(lstitems.Items(i).Text))
cmd.Parameters.AddWithValue("#dname", lstitems.Items(i).SubItems(1).Text)
cmd.Parameters.AddWithValue("#unit", lstitems.Items(i).SubItems(2).Text)
cmd.Parameters.AddWithValue("#qty", Convert.ToDecimal(lstitems.Items(i).SubItems(3).Text ))
cmd.Parameters.AddWithValue("#total", Convert.ToDecimal(lstitems.Items(i).SubItems(4).Text))
cmd.ExecuteNonQuery()
End Using
Notice how, in a parameterized query, you could specify the datatype of the value passed for the parameter using the Convert.ToXXXXX method. In this way the framework code could prepare the appropriate formatting of your values to be passed to the database engine.
Not to mention the now readable query text.

How to 'insert' data into database via VB

Stuggling a bit here. Trying to develop the code to link user input into my database, in the form of a book record. for example the user would be asked to enter their name address etc. But the code I have used does not seem to execute because I continually get the same error.
Line 12: Dim con As New SqlConnection
Line 13: Dim inscmd As New SqlCommand
Line 14: con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database.My.MySettings.Database1ConnectionString1").ConnectionString
Line 15: con.Open()
Line 16: inscmd.CommandText = ("insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "")
It is line 14 that contains the error but I dont know why. This is my code;
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
Dim con As New SqlConnection
Dim inscmd As New SqlCommand
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database.My.MySettings.Database1ConnectionString1").ConnectionString
con.Open()
inscmd.CommandText = ("insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "")
Print(inscmd.CommandText)
inscmd.Connection = con
inscmd.ExecuteNonQuery()
con.Close()
inscmd.Parameters.Clear()
MsgBox("Your booking has been successfully")
con.Close()
End Sub
Hopefully this will help you ( insert your code where need to )
Dim con As New SqlConnection
Dim myConString As String = getSQLString() ' GET YOUR CON String
' my function looks like this when returned
"Server=ServerExactLocationPath;Database=DataBase;User Id=UserName;Password=Password;"
Dim objcommand As SqlCommand = New SqlCommand
'con.ConnectionString = myConString
With objcommand
.Connection = con
Dim cmdText As String = ""
cmdText = "Insert into SitesStatus (SiteNumber,StatusName,Date,ByUser) values ('" & site & "','" & status & "','" & System.DateTime.Today.ToString("MM/dd/yyyy") & "','" & dbUiInitials & "')"
'PUT YOUR INSERT ABOVE
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
objcommand.ExecuteNonQuery()
con.Close()
Catch ex As Exception
End Try
Return Nothing
insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "
should be
insert into booking values('" + txtfirstname.Text + "', '" + txtSurname.Text + "', '" + txtAddressline1.Text + "', '" + txtAddressline2.Text + "', '" + txtPostcode.Text + "', " + txtTime.Text + "', '" + txtPeople.Text + "', '" + txtDropoff1.Text + "', '" + txtDropoff2.Text + "', '" + txtDropoffpost.Text + "')"
You should use the connection string wizard in the Project Settings window. Then try the test connection button, Make sure the type of the setting is ConnectionString
You should be able to get the connection string using this syntax if things are set up right.
con.ConnectionString = my.Settings.Database1ConnectionString1
strSQL = "INSERT INTO user_account_details" & _
"(lastname,firstname,middlename,usertype,reg_date_time,status)" & _
" VALUES ( " & _
" '" & txtLName.Text & "', " & _
" '" & txtFName.Text & "' , " & _
" '" & txtMName.Text & "' , " & _
" '" & cboUserType.Text & "' , " & _
" '#" & Now & "#', " & _
" 'Inactive' " & _
")"

MS Access 2010 VBA Multiple Else If Issues

I have an MS Access form where the user can select up to four criteria to filter the records returned by a report. In the VBA, I'm trying to build my filter string dynamically based on which fields, if any, the user chose to filter by. The below code is giving me a "Block If without End If" error. What am I doing wrong here?
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!sop) = False) Then
strFilter = "sop_number = '" & frm!sop & "'"
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!revision) = False) Then
strFilter = "revision_number = '" & frm!revision & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If IsNull(frm!dept) = False Then
strFilter = "department = '" & frm!dept & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
End If
Any advice you could give me to improve this code would be appreciated.
That code avoids " AND " at the beginning of strFilter. However the logic is challenging to follow and it uses multiple variations on the same basic themes.
Use a simpler approach. You're interested in the values contained in 4 form controls:
frm!employee
frm!sop
frm!Revision
frm!dept
Examine each of them in turn and, for any which contain a value, add a segment starting with " AND " to strFilter. Afterwards, if strFilter contains any text, you know it starts with " AND " so you can simply discard the first 5 characters.
strFilter = vbNullString ' <- make it explicit
If Len(Trim(frm!employee) & vbNullString) > 0 Then
strFilter = strFilter & _
" AND Trainee_First_Name & ' ' & Trainee_Last_Name = '" & _
frm!employee & "'"
End If
If Len(Trim(frm!sop) & vbNullString) > 0 Then
strFilter = strFilter & " AND sop_number = '" & frm!sop & "'"
End If
If Len(Trim(frm!Revision) & vbNullString) > 0 Then
strFilter = strFilter & " AND revision_number = '" & _
frm!Revision & "'"
End If
If Len(Trim(frm!dept) & vbNullString) > 0 Then
strFilter = strFilter & " AND department = '" & frm!dept & "'"
End If
If Len(strFilter) > 0 Then
' discard " AND " from beginning of string
strFilter = Mid(strFilter, 6)
End If
MsgBox "strFilter ->" & strFilter & "<-"
The issue is that your else... if clause aren't terminated with end if. You either need to use ElseIf or
Else
If ...
End If
Else...
I've modified your code below to use the latter syntax. Notice the End If lines below.
Note: You don't need **, that's just to call attention to it in your code block!
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!sop) = False) Then
strFilter = "sop_number = '" & frm!sop & "'"
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
**End If**
Else
If (IsNull(frm!revision) = False) Then
strFilter = "revision_number = '" & frm!revision & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
**End If**
Else
If IsNull(frm!dept) = False Then
strFilter = "department = '" & frm!dept & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
**End If**
End If