How to insert customer details into Orders table - sql

I have an assignment to build a basic database driven e-commerce site. I have a home page, a products page, an orders page, an order confirm page, a shopping cart page and a view current orders page. The site uses an Access database with three tables.
A Customer table, with all of the customer details, (FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode)
A Products table, with all the product information, (ProductID, ProductName, Price, ProductType, Images, ProductDescription).
And an Orders table which contains CustomerID and ProductID.
I'm trying to create an INSERT statement on the orders page so that when the customer inserts their details and presses the submit button the customers table will have a new record inserted. I also want this to create an entry in the orders table and redirect the client to the order confirm page which will display the details of the order.
Here is my code which runs when the submit button is clicked on the order form.
EDIT I've fixed the error with the missing apostrophe. Attempting to insert using two sql commands as I've been told that access databases can't handle two at once. Still getting an error though.
Protected Sub btnAddRecord_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strEmailAdd As String
Dim intCardNo As String
Dim strCardEx As String
Dim intSortCode As String
Dim strDeliveryAdd As String
Dim strPostCode As String
Dim intProductID As Integer
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strEmailAdd = tbxEmailAdd.Text
intCardNo = tbxCardNo.Text
strCardEx = tbxCardEx.Text
intSortCode = tbxSortCode.Text
strDeliveryAdd = tbxDeliveryAdd.Text
strPostCode = tbxPostcode.Text
intProductID = ddlProduct.SelectedValue
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("KingToots.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "INSERT INTO Orders(ProductID) " & "Values ('" & intProductID & "');"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customer.* FROM Customer ORDER BY Customer.CustomerID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxEmailAdd.Text = ""
tbxCardNo.Text = ""
tbxCardEx.Text = ""
tbxSortCode.Text = ""
tbxDeliveryAdd.Text = ""
tbxPostcode.Text = ""
End Sub

You're missing the closing quotes at the end of this line:
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & ");"
About the obvious SQL injection problem, switching to parameters would be the best way to do it (and you'd never have your original issue if you did, parameters don't use quotes), but at the very least run a replace on your strings to replace ' with '' so your program doesn't just die if you get a customer called O'Neil.

He is correct, you don't want to do this you will get sql injection. But here is the solution to your problem anyway.
The problem is not in the last sql statement but in the previous one.
'" & strPostCode & " is missing the last single quote.
it should read:
'" & strPostCode & "');

Related

Why is it when I update a table in MS Access using Excel userform, data that need to updated is not visible?

I am creating a userform to update student attendance details. When updating a table in MS Access via Excel userform, the data is not updated. Instead it shows 0 or -1 on attendanceStatus column and nothing in the Excuse columnthis is a picture of my ClassDate table after attempting to update for student IT01 and IT02.
My userform contains values for courseCode, subject, classDate, studentID, name, attendance status, and excuse. Therefore, I will be using the values of classDate, courseCode, and studentID to find the attendance of the student whom I want to update. This is my attempt for the Userform update button to update the attendanceStatus and Excuse column in the MS Access ClassDate table.
Private Sub CommandButton1_Click()
Dim cnt As ADODB.Connection
Dim db_path As String
Dim db_str As String
db_path = "C:\Users\Lenovo\Documents\BIT\SEM4\SAD\StudentAttendanceMonitoring\attendance1.accdb;"
Set cnt = New ADODB.Connection
db_str = "provider=Microsoft.ACE.OLEDB.12.0; data source=" & db_path
cnt.Open (db_str)
insert_str = "update Classdate set attendanceStatus = '" & cmbUpdateStatus.Value & "' and Excuse = '" & txtUpdateExcuse.Value & "' where classDate = '" & cmbUpdateDate.Value & "' and courseCode = '" & cmbUpdateCourseCode.Value & "' and studentID = '" & cmbUpdateStudentID.Value & "'"
Debug.Print insert_str
cnt.Execute (insert_str)
MsgBox "Updated sucessfully", vbInformation
Set cnt = Nothing
End Sub
Should be a comma to separate field update expressions, not and.
insert_str = "update Classdate set attendanceStatus = '" & cmbUpdateStatus.Value & _
"', Excuse = '" & txtUpdateExcuse.Value & _
"' where classDate = '" & cmbUpdateDate.Value & _
"' and courseCode = '" & cmbUpdateCourseCode.Value & _
"' and studentID = '" & cmbUpdateStudentID.Value & "'"

VBA + SQL Server - Get Last ID Inserted

Hope you can help - I'm having issues getting the last ID after INSERT.
So the environment - Access 2016, SQL Server and VBA
Dim db As DAO.Database
Dim RS As New ADODB.Recordset
Dim sql As String
I have theses declared and then private sub.
Private Sub CreateOrderHeader()
Dim CustomerID As Integer
Dim OrderDate As String
Dim OrderStatus As String
Dim OrderValue As Double
Dim OrderNotes As String
Dim OrderPostageID As String
Dim OrderAddressID As String
Dim OrderBatchID As Integer
Dim OrderPayment As String
Dim OrderCourierID As String
Dim OrderAgentID As Integer
Dim OrderOutstanding As Double
CustomerID = tbxCusID
OrderDate = Format(Now)
OrderStatus = "InProcess"
OrderValue = txtTotal.value
OrderNotes = tbxNotes.value
OrderPostageID = txtPostage.Column(0)
If tbxCustomerAddress = tbxDeliveryAddress Then
OrderAddressID = 3 'default customers address
Else
'NEED TO GET CUSTOMER ADDRESS TO DO
End If
OrderBatchID = cmbBatch.Column(0)
OrderPayment = sPayMethod
OrderCourierID = cbxShipping.Column(0)
OrderAgentID = 0
OrderOutstanding = txtTotal.value
Dim testvar As String
sql = "INSERT INTO dbo_OrderHeader " _
& "(OrdCusID, OrdDate, OrdStatus, OrdValue, OrdNotes, OrdPostageID, OrdDelAddID,OrdBatchID,OrdPaymentMethod, OrdCourierID,ordAgentID, OrdOutstanding,OrdSource) " _
& " VALUES ('" & CustomerID & "' ,'" & OrderDate & "', '" & OrderStatus & "', '" & OrderValue & "', '" & OrderNotes & "', '" & OrderPostageID & "','" & OrderAddressID & "','" & OrderBatchID & "','" & OrderPayment & "','" & OrderCourierID & "','" & OrderAgentID & "','" & OrderOutstanding & "', 1)"
DoCmd.RunSQL (sql)
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
MsgBox ("Succes - OrderHeader" & " '" & IDT & "' ")
End Sub
I was expecting a result from this code:
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
But that gives me "0" as result.
Can you help please.
Thanks
You can try this :
Set db = CurrentDB
db.Execute(sql)
IDT = db.OpenRecordset("SELECT ##IDENTITY")(0)
Set db = Nothing
NOTE
Don't execute your insert query like DoCmd.RunSQL (sql) Instead follow the above approach.

Run time 3134 error MS Access SQL

Private Sub AddItemButton_Click()
Dim db As Database
Set db = CurrentDb
Dim Item As String
Dim Rate As String
Dim AltRate As String
Dim Reason As String
Dim ApporvedBy As String
Dim Company As String
Dim JobID As String
Me.JobID2 = Me.JobID
db.Execute "INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, Company, JobID) VALUES ('" & Me.ItemAppendCBO & "', " & Me.RateAppend & ", " & Me.AltRateAppend & ", '" & Me.ReasonAppend & "', '" & Me.ApprovedByAppend & "', '" & Me.Customer & "', " & Me.JobID2 & ")"
Me.AltRate2.Value = Null
End Sub
You should use string literals for your Queries
Dim sqlQuery As String
sqlQuery = "INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, " & _
"Company, JobID) VALUES ('" & Me.ItemAppendCBO & "', " & Me.RateAppend & ", " & Me.AltRateAppend & ", '" & Me.ReasonAppend & "', '" & _
Me.ApprovedByAppend & "', '" & Me.Customer & "', " & Me.JobID2 & ")"
db.Execute sqlQuery
It makes it a lot easier to debug
INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, Company, JobID)
VALUES('Some Item', 100, 343, 'Reason A', 'John', 'Jane Doe', Null)
Chances are you are inadvertently passing 1 or more null values to non-nullable fields. Also be careful about the data types. You may need to use CStr(), CInt(), CLong, CDate() or ... to cast your data into the right format If a field can be left blank us NZ().
NZ(Me.RateAppend, True)

Time Format Issues

Wondering if someone can help me with this please. I'm getting the following error message when adding data to an access database.I know it's a time issue function but I don't know how to fix it so I can add data to the database in the required format. One or more values are prohibited by the validation rule 'Time()' set for 'tblmph'. Enter a value that the expression for this field can accept.
Public Sub Add_Data()
con.Open()
Dim rs As New OleDb.OleDbCommand("Insert into tblmph(ID,ThisDate,TimeStart,TimeFinish,Notes) " _
& "values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" _
& TextBox4.Text & "', '" & TextBox5.Text & "')", con)
rs.ExecuteNonQuery()
con.Close()
Display_Data()
End Sub
The columns are formatted as follows
ID = Auto Number-Long Integer
ThisDate = Short Date
TimeStart = Medium Time, Default Value = Time()
TimeFinish = Medium Time, Default Value = Time()
Notes = Memo
Do not insert the value of ID. If it is truly an auto-number, Access will automatically assign a value to the newly inserted row. Trying to insert a value into the field will cause an error and prevent the insert from working.
Change your Dim statement to:
Dim rs As New OleDb.OleDbCommand( "Insert into tblmph( ThisDate, TimeStart, TimeFinish, Notes ) values ( '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" & TextBox4.Text & "', '" & TextBox5.Text & "' ) ", con)

Updating Access Database using UPDATE SQL statement in VBA

Can someone take a look a the stSQL string and help me fix the syntax error I am getting associated with the UPDATE statement?
Run-time error '-2147217900 (8004e14)': Syntax error in UPDATE statement.
I have a rudimentary understanding of SQL and don't seem to understand where I have gone wrong.
I want to update the fields of Table 1 if the FileName UserForm value matches a FileName field in the Access Db.
Thanks
Public Sub UpdateDatabaseEntry()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim FileName As String
Dim Nickname As String
Dim RecipientName As String
Dim RecipientRelationship As String
Dim Summary As String
Dim Noteworthy As String
Dim PreparedBy As String
FileName = UserForm1.FileNameTextBox.Text
Nickname = UserForm1.NicknameTextBox.Text
RecipientName = UserForm1.RecipientNameTextBox.Text
RecipientRelationship = UserForm1.RecipientRelationshipComboBox.Text
Summary = UserForm1.SummaryTextBox.Text
Noteworthy = UserForm1.NoteworthyCheckBox.Value
PreparedBy = UserForm1.PreparedByTextBox.Text
stDB = "Data Source= E:\MyDb.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
//Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
//SQL Statement telling database what to do
stSQL = "UPDATE Table1" & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "', " & _
"WHERE FileName= '" & FileName & "'"
cn.Execute stSQL
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
At least one problem is caused by lack of spaces in the query. So your query started UPDATE Table1set.
stSQL = "UPDATE Table1 " & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "'" & _
"WHERE FileName= '" & FileName & "'"
If this doesn't fix the problem. Then edit your question with the value of stSQL after the variable substitution.
EDIT:
As TS points out, another problem is the , before the where (fixed above).