error database: Syntax error in INSERT INTO statement - ms-access

I'm having difficulties with my library system. I get an error that states "error database: Syntax error in INSERT INTO statement". I'm using Access for the data base.
Here's my code:
Public Class Form7
Private Sub Form7_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Text = "Registration"
sqlCon.Close()
sqlCon.Close()
clear()
End Sub
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Split(Me.Text, " - ")(1) = "Edit" Then
sqlSTR = "Select * From BookRegister WHERE id = " & globalID
ExecuteSQLQuery(sqlSTR)
If sqlDr.Read Then
TextBox1.Text = sqlDr(1)
TextBox2.Text = sqlDr(2)
TextBox3.Text = sqlDr(3)
TextBox4.Text = sqlDr(4)
TextBox5.Text = sqlDr(5)
TextBox6.Text = sqlDr(6)
TextBox7.Text = sqlDr(7)
TextBox7.Text = sqlDr(8)
End If
End If
End Sub
Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox2.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox3.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox4.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox5.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox6.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox7.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox8.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO BookRegister(ISBN, Title, Author, Volume, Pages, Publisher, Section, Year_Published) " & _
"VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "'" & _
",'" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & ")"""
ExecuteSQLQuery(sqlSTR)
MsgBox("New record has been saved.", MsgBoxStyle.Information)
clear()
Else
sqlSTR = "UPDATE BookRegister SET ISBN ='" & TextBox1.Text & "', " & _
"title='" & TextBox2.Text & "', " & _
"author='" & TextBox3.Text & "', " & _
"volume='" & TextBox4.Text & "', " & _
"pages='" & TextBox5.Text & "', " & _
"publisher='" & TextBox6.Text & "', " & _
"section='" & TextBox7.Text & "', " & _
"year_published='" & Format("yyyy", TextBox8.Text) & "', " & _
" WHERE id =" & globalID
ExecuteSQLQuery(sqlSTR)
MsgBox("Record has been updated !!", MsgBoxStyle.Information)
clear()
globalID = 0
edit = False
Me.Close()
End If
FillListView(Form6.ListView1, ExecuteSQLQuery("select * from bookregister"))
End Sub
Private Sub clear()
Textbox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class

It looks like you are missing a final single quote at the end of your INSERT statement, and then appending an extraneous double quote after the closing parenthesis, i.e.,
& "','" & TextBox8.Text & ")"""
should be
& "','" & TextBox8.Text & "')"

Related

How to save edited data record in access form as a new record?

I am facing a little issue now. My issue is that currently when i made edit to the current record in my subform and click on "update" it will overwrite my previous record which i do not want.
Instead, I would like to add my edited data record from the subform and insert it into the subform as a new record with the same PO number as the one that i am editing.
Below are my code:
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO mxd " & _
"(ID,Fabrication,Width,FinishedGoods,Colour, " & _
"LabDipCode,GrossWeight,NettWeight, " & _
"Lbs,Loss,Yds,Remarks,POType,ComboName,GroundColour)" & _
" VALUES(" & Me.txtID & ",'" & Me.txtFabrication & "','" & _
Me.txtWidth & "','" & Me.txtFinishedGood & "','" & _
Me.txtColour & "','" & Me.txtLabDipCode & "','" & _
Me.txtGrossweight & "','" & _ Me.txtNettweight & "','" & _
Me.txtLbs & "','" & Me.txtLoss & "','" & _ Me.txtYds & "','" & _
Me.txtRemarks & "','" & Me.cboPoType "','" & _
Me.txtGroundColour & "','" & Me.txtComboName & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE mxd " & _
" SET ID = " & Me.txtID & _
", Fabrication = '" & Me.txtFabrication & "'" & _
", Width = '" & Me.txtWidth & "'" & _
", FinishedGoods = '" & Me.txtFinishedGood & "'" & _
", Colour = '" & Me.txtColour & "'" & _
", LabDipCode = '" & Me.txtLabDipCode & "'" & _
", GrossWeight = '" & Me.txtGrossweight & "'" & _
", NettWeight = '" & Me.txtNettweight & "'" & _
", LBS = '" & Me.txtLbs & "'" & _
", Loss = '" & Me.txtLoss & "'" & _
", Yds = '" & Me.txtYds & "'" & _
", Remarks = '" & Me.txtRemarks & "'" & _
", POType = '" & Me.cboPoType & "'" & _
", ComboName = '" & Me.txtComboName & "'" & _
", GroundColour = '" & Me.txtGroundColour & "'" & _
" WHERE ID = " & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
FormMxdSub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtID = ""
Me.txtFabrication = ""
Me.txtWidth = ""
Me.txtFinishedGood = ""
Me.txtColour = ""
Me.txtLabDipCode = ""
Me.txtGrossweight = ""
Me.txtNettweight = ""
Me.txtLbs = ""
Me.txtLoss = ""
Me.txtYds = ""
Me.txtRemarks = ""
Me.cboPoType = ""
Me.txtKeywords = ""
Me.txtComboName = ""
Me.txtGroundColour = ""
'focus on ID text box
Me.txtID.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtID for reset new
Me.txtID.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM mxd " & _
"where ID = " & Me.FormMxdSub.Form.Recordset.Fields("ID")
'refresh data in list
Me.FormMxdSub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there is exists data in list
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'get data to text box control
With Me.FormMxdSub.Form.Recordset
Me.txtID = .Fields("ID")
Me.txtFabrication = .Fields("Fabrication")
Me.txtWidth = .Fields("Width")
Me.txtFinishedGood = .Fields("FinishedGoods")
Me.txtColour = .Fields("Colour")
Me.txtLabDipCode = .Fields("LabDipCode")
Me.txtGrossweight = .Fields("GrossWeight")
Me.txtNettweight = .Fields("NettWeight")
Me.txtLbs = .Fields("Lbs")
Me.txtLoss = .Fields("Loss")
Me.txtYds = .Fields("Yds")
Me.txtRemarks = .Fields("Remarks")
Me.cboPoType = .Fields("POType")
Me.txtComboName = .Fields("ComboName")
Me.txtGroundColour = .Fields("GroundColour")
'store id of student in Tag of txtID in case id is modified
Me.txtID.Tag = .Fields("ID")
'change caption of button add to update
'Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
You can use the RecordsetClone to create a dupe of the current record. Much faster and cleaner and no Tag is needed:
Private Sub btnCopy_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
If Me.NewRecord = True Then Exit Sub
Set rstInsert = Me.RecordsetClone
Set rstSource = rstInsert.Clone
With rstSource
If .RecordCount > 0 Then
' Go to the current record.
.Bookmark = Me.Bookmark
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "SomeFieldToExclude" Then
' Leave field blank.
ElseIf .Name = "SomeOtherFieldToExclude" Then
' Leave field blank.
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
' Go to the new record and sync form.
.MoveLast
Me.Bookmark = .Bookmark
.Close
End With
End If
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
Of course, if you place the button on the main form, replace in the code Me with a reference to the subform: Me!NameOfYourSubformControl.Form

I want to insert and retrieve data under one button event in vb.net with sql database

Here i am trying to register student's detail. and at the same time i want to retrieve a unique user id from connected SQL server and that's where i got stuck!
I want to know what i am doing wrong here!
Everything stored in the SQL server is correct and i have make an auto increment code in SQL!
so why its not inserting and retrieving the data simultaneously
Imports MySql.Data.MySqlClient
Public Class Form3
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;persistsecurityinfo=True;database=bcaproject")
Dim cmd As New MySqlCommand
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Then
MessageBox.Show("Information shouldn't be empty...")
Else
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into student(F_name,L_name,Email,Phoneno,Username,Password) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("successfully Registered")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
Form2.Show()
Me.Hide()
End If
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Form2.Show()
Me.Hide()
End Sub
Private Sub TextBox4_KeyPress1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Not IsNumeric(e.KeyChar) Then
tipvalidation.Show("Numeric input required", sender, 5000)
e.KeyChar = Nothing
End If
End If
End Sub
End Class

Combobox ValueMember not working with MySQL

My ComboBox controls display publishername and authorlastname and stores the publisherid and authorid.
When I run my code, it does display publishername and authorlastname with the ValueMember of publisherid and authorid however when the insert query runs it literally tries to insert the words _publisherid_ and _authorid_.
ComboBox Code:
Private Sub addbook_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;userid=root;database=librarydatabase;Convert Zero Datetime=True"
Dim table As New DataTable
Dim da As New MySqlDataAdapter("select * from publishertable", mysqlconn)
da.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "publishername"
ComboBox1.ValueMember = "PublisherId"
Dim pa As New MySqlDataAdapter("select * from authortable", mysqlconn)
pa.Fill(table)
ComboBox2.DataSource = New BindingSource(table, Nothing)
ComboBox2.DisplayMember = "authorlastname"
ComboBox2.ValueMember = "authorid"
End Sub
Insert Code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim reader As MySqlDataReader
Try
conn.Open()
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.ValueMember & "', '" & ComboBox1.ValueMember & "');SET foreign_key_checks = 1"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
MessageBox.Show(query)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
You should be using SelectedValue instead of ValueMember
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.ValueMember & "', '" & ComboBox1.ValueMember & "');SET foreign_key_checks = 1"
should be
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.SelectedValue & "', '" & ComboBox1.SelectedValue & "');SET foreign_key_checks = 1"

DataGridView select multiple row, check each row

I am trying to select all rows by a button or select different rows with ctrl+click.
But even if I have selected multiple rows, it only checks the first row. Then it rereads it again instead of going to the next row.
I'm not sure either where to put the multiselect code.
Originally, you're only supposed to just click a row then check if conditions are satisfied. However it was requested that you can do multiple and check each row if condition is satisfied.
Here is my code:
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
Dim i As Integer
i = DataGridView1.CurrentRow.Index
_subjectno = DataGridView1.Item(0, i).Value
_title = DataGridView1.Item(1, i).Value
_unit = DataGridView1.Item(2, i).Value
_pre = DataGridView1.Item(3, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.MultiSelect = True
DataGridView1.SelectAll()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim selectedItems As DataGridViewSelectedRowCollection = DataGridView1.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
add()
Next
End Sub
Sub add()
Try
If IS_EMPTY(txtSno) = True Then Return
cm = New MySqlCommand("select * from tblenroll where subjectnumber like '" & _subjectno & "' and remarks <> 'Failed' and studentno like '" & txtSno.Text & "'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
MsgBox("Subject is already taken.", vbExclamation)
dr.Close()
Return
Else
dr.Close()
End If
If _pre = "NONE" Or _pre = "2ND YR STANDING" Or _pre = "3RD YR STANDING" Or _pre = "4TH YR STANDING" Or _pre = "5TH YR STANDING" Then
cm = New MySqlCommand("insert into tblenroll (studentno, subjectnumber, ay,semester,dateenrolled, curriculum) values ('" & txtSno.Text & "','" & _subjectno & "','" & txtAY.Text & "','" & txtSem.Text & "','" & Now & "','" & txtCurriculum.Text & "')", cn)
cm.ExecuteNonQuery()
MsgBox(_subjectno & " successfully added.", vbInformation)
LoadEnrolled()
Else
cm = New MySqlCommand("select * from tblenroll where studentno like '" & txtSno.Text & "' and subjectnumber like '" & _subjectno & "' and ay like '" & txtAY.Text & "'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
MsgBox("Subject is already taken.", vbExclamation)
dr.Close()
Return
Else
dr.Close()
End If
Dim strok As Boolean = False
Dim strArr() As String
Dim count As Integer
Dim strpre As String = _pre
strArr = strpre.Split(", ")
For count = 0 To strArr.Length - 1
cm = New MySqlCommand("select * from tblenroll as e inner join tblsubject as s on e.subjectnumber = s.subjectno where s.subjectno like '%" & Trim(strArr(count)) & "%' and studentno like '" & txtSno.Text & "' and remarks like 'Passed'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
dr.Close()
strok = True
Else
MsgBox("Unable to enroll this subject. Pre-requisite " & strArr(count) & ".", vbExclamation)
dr.Close()
Return
End If
Next
If strok = True Then
cm = New MySqlCommand("insert into tblenroll (studentno, subjectnumber, ay, semester, dateenrolled, curriculum) values ('" & txtSno.Text & "','" & _subjectno & "','" & txtAY.Text & "','" & txtSem.Text & "','" & Now & "','" & txtCurriculum.Text & "')", cn)
cm.ExecuteNonQuery()
MsgBox(_subjectno & " successfully added.", vbInformation)
LoadEnrolled()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
Thank you so much!
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
For Each selectedItem As DataGridViewRow In DataGridView1.SelectedRows
_subjectno = selectedItem.Cells(0).Value
_title = selectedItem.Cells(1).Value
_unit = selectedItem.Cells(2).Value
_pre = selectedItem.Cells(3).Value
add()
Next
End Sub

Some values do not store in the database

i have this code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If txtCode.Text <> "878" Then
If ((txtCode.Text <> "") And (txtRefNo.Text <> "") And (txtPayee.Text <> "") And (txtOffice.Text <> "") And (txtAddress.Text <> "") And (txtParticulars.Text <> "") And (txtPPA.Text <> "") And (txtAmount.Text <> "")) Then
Try
If IsNumeric(txtAmount.Text) = False Then
MsgBox("Amount value should be in correct number format! e.g: 10000.00 or 10,000.00", MsgBoxStyle.Exclamation)
Exit Sub
End If
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.DateTimeNow = String.Format("{0:yyyy/MM/dd}", DateTime.Now)
Dim Reader As MySqlDataReader
Dim Amount As Double = Double.Parse(txtAmount.Text)
Reader = modGlobalFunctions.executeQuery("SELECT * FROM obligations " & _
"WHERE ref_no='" & txtRefNo.Text & "'")
If Reader.HasRows Then
MessageBox.Show("Could not insert duplicate entries for REFERENCE NO.!", "Form Validations", MessageBoxButtons.OK, MessageBoxIcon.Error)
Reader.Close()
modGlobalFunctions.Connection.Close()
Else
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.executeNonQuery("INSERT INTO obligations (resp_id, year_id, expenditure_id, ref_no, payee, office, address, particulars, ppa, amount, date_entered, date_edited, signature1, position1, signature2, position2) " & _
"VALUES ('" & RespCenterId & "', " & _
"'" & YearId & "', " & _
"'" & txtExpId.Text & "', " & _
"'" & modGlobalFunctions.addslashes(txtRefNo.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPayee.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtOffice.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtAddress.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtParticulars.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPPA.Text) & "', " & _
"'" & Amount & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & Signature1 & "', " & _
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "')")
MsgBox("Record has been added!", MsgBoxStyle.Information)
modGlobalFunctions.Connection.Close()
Me.Close()
Dispose()
frmObligations.MdiParent = frmMain
frmObligations.Show()
frmObligations.obligationLoadGrid()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MsgBox("Please fill up all form fields!", MsgBoxStyle.Exclamation)
modGlobalFunctions.Connection.Close()
End If
modGlobalFunctions.Connection.Close()
Else
If ((txtCode.Text <> "") And (txtRefNo.Text <> "") And (txtPayee.Text <> "") And (txtOffice.Text <> "") And (txtAddress.Text <> "") And (txtParticulars.Text <> "")) Then
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.DateTimeNow = String.Format("{0:yyyy/MM/dd}", DateTime.Now)
Dim Reader As MySqlDataReader
Reader = modGlobalFunctions.executeQuery("SELECT * FROM obligations " & _
"WHERE ref_no='" & txtRefNo.Text & "'")
If Reader.HasRows Then
MessageBox.Show("Could not insert duplicate entries for REFERENCE NO.!", "Form Validations", MessageBoxButtons.OK, MessageBoxIcon.Error)
Reader.Close()
modGlobalFunctions.Connection.Close()
Else
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.executeNonQuery("INSERT INTO obligations (resp_id, year_id, expenditure_id, ref_no, payee, office, address, particulars, date_entered, date_edited, signature1, position1, signature2, position2) " & _
"VALUES ('" & RespCenterId & "', " & _
"'" & YearId & "', " & _
"'" & txtExpId.Text & "', " & _
"'" & modGlobalFunctions.addslashes(txtRefNo.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPayee.Text) & "', " & _
"'" & odGlobalFunctions.addslashes(txtOffice.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtAddress.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtParticulars.Text) & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & Signature1 & "', " & _
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "')")
MsgBox("Record has been added! You can now add project title!", MsgBoxStyle.Information)
frmProject.MdiParent = frmMain
frmProject.Show()
frmProject.Label2.Text = txtRefNo.Text
Me.Enabled = False
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MsgBox("Please fill up all form fields!", MsgBoxStyle.Exclamation)
modGlobalFunctions.Connection.Close()
End If
modGlobalFunctions.Connection.Close()
End If
End Sub
What do you think is the problem why Signature1, Position1, Signature2 and Position2 doesn't store in the database. It works fine before until i put the if code because of the category... by the way here's the code for signature1, position1, signature2 and position2:
Signature1:
Private Sub cbSignatory1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT person_id FROM persons WHERE person_name='" & cbSignatory1.Text & "'")
If Reader.HasRows Then
While Reader.Read
Signature1 = Reader("person_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Signature2:
Private Sub cbSignatory2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT person_id FROM persons WHERE person_name='" & cbSignatory2.Text & "'")
If Reader.HasRows Then
While Reader.Read
Signature2 = Reader("person_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Position1:
Private Sub cbPosition1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT position_id FROM positions WHERE position_name='" & cbPosition1.Text & "'")
If Reader.HasRows Then
While Reader.Read
Position1 = Reader("position_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Position2:
Private Sub cbPosition2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT position_id FROM positions WHERE position_name='" & cbPosition2.Text & "'")
If Reader.HasRows Then
While Reader.Read
Position2 = Reader("position_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
any suggestions?
I bet Person_ID and position_id are numeric types in your database. Right? The reason it's not inserting because you wrapped it with single quotes:
"'" & Signature1 & "', " & _ // <== here
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "'
Numeric values are not wrap with single quotes. One more thing, I suggest you use Command and parameters to avoid SQL Injection.
Example based on your code:
Dim sqlStatement AS String = "INSERT INTO obligations (resp_id, year_id, expenditure_id, "
sqlStatement &= "ref_no, payee, office, address, particulars, ppa, amount, date_entered, "
sqlstetement &= "date_edited, signature1, position1, signature2, position2) "
sqlstetement &= "VALUES (#resp_id, #year_id, #expenditure_id, "
sqlStatement &= "#ref_no, #payee, #office, #address, #particulars, #ppa, #amount, #date_entered, "
sqlstetement &= "#date_edited, #signature1, #position1, #signature2, #position2) "
Using xConn AS New MySQLConnection(connStrHere)
Using xComm AS New MySQLCommand()
With xComm
.Connection = xConn
.CommandType = CommandType.Text
.CommandText = sqlStatement
.Parameter.AddWithValue("#resp_id", RespCenterId)
.Parameter.AddWithValue("#year_id", YearId)
.Parameter.AddWithValue("#expenditure_id", txtExpId.Text)
' continue with other parameters
' .....
' until you reach the last parameters '
.Parameter.AddWithValue("#signature1", Signature1)
.Parameter.AddWithValue("#position1", Position1)
.Parameter.AddWithValue("#signature2", Signature2)
.Parameter.AddWithValue("#position2", Position2)
End With
Try
xConn.Open()
xComm.ExecuteNonQuery()
MsgBox("Record has been added!", MsgBoxStyle.Information)
Catch ex AS MySQLException
MsgBox(e.Message, MsgBoxStyle.Exclamation)
Finally
xConn.Open()
End try
End Using
End Using