I have a fully working Classic ASP paypal integration (yay!)
I set up my variables and call the express checkout like this:
paymentAmount = RS_OrderHeader01("PaymentAmount")
currencyCodeType = "GBP"
paymentType = "Sale"
solutionType = "Mark"
OrderDescription = "My order description"
returnURL = "http://www.myurl.co.uk/transactioncomplete.asp"
cancelURL = "http://www.myurl.co.uk/transactioncancelled.asp"
Set resArray = CallShortcutExpressCheckout (paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
That all works fine apart from the fact that there is no description being passed across. I would also like to add individual items from my basket to the final transaction in paypal.
The integration I am using is from a download from the Paypal site that hinges around this 'include' file:
<%
' ===================================================
' PayPal API Include file
'
' Defines all the global variables and the wrapper functions
'-----------------------------------------------------------
Dim gv_APIEndpoint
Dim gv_APIUserName
Dim gv_APIPassword
Dim gv_APISignature
Dim gv_Version
Dim gv_BNCode
Dim gv_ProxyServer
Dim gv_ProxyServerPort
Dim gv_Proxy
'----------------------------------------------------------------------------------
' Authentication Credentials for making the call to the server
'----------------------------------------------------------------------------------
SandboxFlag = true
'------------------------------------
' PayPal API Credentials
' Replace <API_USERNAME> with your API Username
' Replace <API_PASSWORD> with your API Password
' Replace <API_SIGNATURE> with your Signature
'------------------------------------
gv_APIUserName = "myusername"
gv_APIPassword = "1404738820"
gv_APISignature = "AFcWxV21CRCpSSRl31AuDrEW4a9MiULwvS8UDzCPvE28G8"
'-----------------------------------------------------
' The BN Code only applicable for partners
'----------------------------------------------------
gv_BNCode = "PP-ECWizard"
'----------------------------------------------------------------------
' Define the PayPal URLs.
' This is the URL that the buyer is first sent to do authorize payment with their paypal account
' change the URL depending if you are testing on the sandbox
' or going to the live PayPal site
'
' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
'------------------------------------------------------------------------
if SandboxFlag = true Then
gv_APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="
Else
gv_APIEndpoint = "https://api-3t.paypal.com/nvp"
PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="
End If
gv_Version = "93"
'WinObjHttp Request proxy settings.
gv_ProxyServer = "127.0.0.1"
gv_ProxyServerPort = "808"
gv_Proxy = 2 'setting for proxy activation
gv_UseProxy = False
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
' paymentAmount: Total value of the shopping cart
' currencyCodeType: Currency code value the PayPal API
' paymentType: PaymentType has to be one of the following values: Sale or Order or Authorization
' returnURL: The page where buyers return to after they are done with the payment review on PayPal
' cancelURL: The page where buyers return to when they cancel the payment review on PayPal
' Returns:
' The NVP Collection object of the SetExpressCheckout call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function CallShortcutExpressCheckout( paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------------------------------------------
' Make the API call to PayPal
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallShortcutExpressCheckout = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
' paymentAmount: Total value of the shopping cart
' currencyCodeType: Currency code value the PayPal API
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' returnURL: the page where buyers return to after they are done with the payment review on PayPal
' cancelURL: the page where buyers return to when they cancel the payment review on PayPal
' shipToName: the Ship to name entered on the merchant's site
' shipToStreet: the Ship to Street entered on the merchant's site
' shipToCity: the Ship to City entered on the merchant's site
' shipToState: the Ship to State entered on the merchant's site
' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
' shipToZip: the Ship to ZipCode entered on the merchant's site
' shipToStreet2: the Ship to Street2 entered on the merchant's site
' phoneNum: the phoneNum entered on the merchant's site
' Returns:
' The NVP Collection object of the SetExpressCheckout call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function CallMarkExpressCheckout(paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL, shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & Server.URLEncode("ADDROVERRIDE") & "=1" & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTONAME") & "=" & Server.URLEncode(shipToName) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTREET") & "=" & Server.URLEncode(shipToStreet) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTREET2") & "=" & Server.URLEncode(shipToStreet2) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOCITY") & "=" & Server.URLEncode(shipToCity) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTATE") & "=" & Server.URLEncode(shipToState) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE") & "=" & Server.URLEncode(shipToCountryCode) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOZIP") & "=" & Server.URLEncode(shipToZip) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOPHONENUM") & "=" & Server.URLEncode(phoneNum) & _
"&"& server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------
' Make the API call to PayPal to set the Express Checkout token
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallMarkExpressCheckout = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API and makes the API call.
'
' Inputs:
' token: The token value returned by the SetExpressCheckout call
' Returns:
' The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function GetShippingDetails( token )
'---------------------------------------------------------------------------
' At this point, the buyer has completed authorizing the payment
' at PayPal. The function will call PayPal to obtain the details
' of the authorization, incuding any shipping information of the
' buyer. Remember, the authorization is not a completed transaction
' at this state - the buyer still needs an additional step to finalize
' the transaction
'---------------------------------------------------------------------------
'---------------------------------------------------------------------------
' Build a second API request to PayPal, using the token as the
' ID to get the details on the payment authorization
'---------------------------------------------------------------------------
nvpstr="&TOKEN=" & token
'---------------------------------------------------------------------------
' Make the API call and store the results in an array.
' If the call was a success, show the authorization details, and provide
' an action to complete the payment.
' If failed, show the error
'---------------------------------------------------------------------------
set resArray = hash_call("GetExpressCheckoutDetails",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("PAYERID") = resArray("PAYERID")
End If
set GetShippingDetails = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API and makes the call.
'
' Inputs:
' finalPaymentAmount: The final total of the shopping cart including Shipping, Handling and other fees
' Returns:
' The NVP Collection object of the DoExpressCheckoutPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function ConfirmPayment( finalPaymentAmount )
'------------------------------------------------------------------------------------------------------------------------------------
'---- Use the values stored in the session from the previous SetEC call
'------------------------------------------------------------------------------------------------------------------------------------
token = SESSION("token")
currCodeType = SESSION("currencyCodeType")
paymentType = SESSION("PaymentType")
payerID = SESSION("PayerID")
nvpstr = "&" & Server.URLEncode("TOKEN") & "=" & Server.URLEncode(token) & "&" &_
Server.URLEncode("PAYERID")&"=" &Server.URLEncode(payerID) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_AMT") &"=" & Server.URLEncode(finalPaymentAmount) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_CURRENCYCODE")& "=" &Server.URLEncode(currCodeType)
'-------------------------------------------------------------------------------------------
' Make the call to PayPal to finalize payment
' If an error occured, show the resulting errors
'-------------------------------------------------------------------------------------------
set ConfirmPayment = hash_call("DoExpressCheckoutPayment",nvpstr)
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the DoDirectPayment API and makes the call.
'
' Inputs:
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' paymentAmount: Total value of the shopping cart
' creditCardType Credit card type has to one of the following values: Visa or MasterCard or Discover or Amex or Switch or Solo
' creditCardNumber Credit card number
' expDate Credit expiration date
' cvv2 CVV2
' firstName Customer's First Name
' lastName Customer's Last Name
' street Customer's Street Address
' city Customer's City
' state Customer's State
' zip Customer's Zip
' countryCode Customer's Country represented as a PayPal CountryCode
' currencyCode Customer's Currency represented as a PayPal CurrencyCode
'
' Returns:
' The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function DirectPayment( paymentType, paymentAmount, creditCardType, creditCardNumber, expDate, cvv2, firstName, lastName, street, city, state, zip, countryCode, currencyCode )
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
nvpstr = "&PAYMENTACTION=" & paymentType & _
"&AMT=" & paymentAmount &_
"&CREDITCARDTYPE=" & creditCardType &_
"&ACCT=" & creditCardNumber & _
"&EXPDATE=" & expDate &_
"&CVV2=" & cvv2 &_
"&FIRSTNAME=" & firstName &_
"&LASTNAME=" & lastName &_
"&STREET=" & street &_
"&CITY=" & city &_
"&STATE=" & state &_
"&ZIP=" & zip &_
"&COUNTRYCODE=" & countryCode &_
"&CURRENCYCODE=" & currencyCode
nvpstr = URLEncode(nvpstr)
'-------------------------------------------------------------------------------------------
' Make the call to PayPal to finalize payment
' If an error occured, show the resulting errors
'-------------------------------------------------------------------------------------------
set DirectPayment = hash_call("DoDirectPayment",nvpstr)
End Function
'----------------------------------------------------------------------------------
' Purpose: Make the API call to PayPal, using API signature.
' Inputs:
' Method name to be called & NVP string to be sent with the post method
' Returns:
' NVP Collection object of Call Response.
'----------------------------------------------------------------------------------
Function hash_call ( methodName,nvpStr )
Set objHttp = Server.CreateObject("WinHTTP.WinHTTPRequest.5.1")
nvpStrComplete = "METHOD=" & Server.URLEncode(methodName) & "&VERSION=" & Server.URLEncode(gv_Version) & "&USER=" & Server.URLEncode(gv_APIUserName) & "&PWD=" & Server.URLEncode(gv_APIPassword) & "&SIGNATURE=" & Server.URLEncode(gv_APISignature) & nvpStr
nvpStrComplete = nvpStrComplete & "&BUTTONSOURCE=" & Server.URLEncode( gv_BNCode )
Set SESSION("nvpReqArray")= deformatNVP( nvpStrComplete )
objHttp.open "POST", gv_APIEndpoint, False
WinHttpRequestOption_SslErrorIgnoreFlags=4
objHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300
If gv_UseProxy Then
'Proxy Call
objHttp.SetProxy gv_Proxy, gv_ProxyServer& ":" &gv_ProxyServerPort
End If
objHttp.Send nvpStrComplete
Set nvpResponseCollection =deformatNVP(objHttp.responseText)
Set hash_call = nvpResponseCollection
Set objHttp = Nothing
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"hash_call")
SESSION("nvpReqArray") = Null
Else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: Formats the error Messages.
' Inputs:
'
' Returns:
' Formatted Error string
'----------------------------------------------------------------------------------
Function ErrorFormatter ( errDesc, errNumber, errSource, errlocation )
ErrorFormatter ="<font color=red>" & _
"<TABLE align = left>" &_
"<TR>" &"<u>Error Occured!!!</u>" & "</TR>" &_
"<TR>" &"<TD>Error Description :</TD>" &"<TD>"&errDesc& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error number :</TD>" &"<TD>"&errNumber& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error Source :</TD>" &"<TD>"&errSource& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error Location :</TD>" &"<TD>"&errlocation& "</TD>"& "</TR>" &_
"</TABLE>" &_
"</font>"
End Function
'----------------------------------------------------------------------------------
' Purpose: Convert nvp string to Collection object.
' Inputs:
' NVP string.
' Returns:
' NVP Collection object created from deserializing the NVP string.
'----------------------------------------------------------------------------------
Function deformatNVP ( nvpstr )
On Error Resume Next
Dim AndSplitedArray,EqualtoSplitedArray,Index1,Index2,NextIndex
Set NvpCollection = Server.CreateObject("Scripting.Dictionary")
AndSplitedArray = Split(nvpstr, "&", -1, 1)
NextIndex=0
For Index1 = 0 To UBound(AndSplitedArray)
EqualtoSplitedArray=Split(AndSplitedArray(Index1), "=", -1, 1)
For Index2 = 0 To UBound(EqualtoSplitedArray)
NextIndex=Index2+1
NvpCollection.Add URLDecode(EqualtoSplitedArray(Index2)),URLDecode(EqualtoSplitedArray(NextIndex))
Index2=Index2+1
Next
Next
Set deformatNVP = NvpCollection
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"deformatNVP")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: URL Encodes a string
' Inputs:
' String to be url encoded.
' Returns:
' Url Encoded string.
'----------------------------------------------------------------------------------
Function URLEncode(str)
On Error Resume Next
Dim AndSplitedArray,EqualtoSplitedArray,Index1,Index2,UrlEncodeString,NvpUrlEncodeString
AndSplitedArray = Split(nvpstr, "&", -1, 1)
UrlEncodeString=""
NvpUrlEncodeString=""
For Index1 = 0 To UBound(AndSplitedArray)
EqualtoSplitedArray=Split(AndSplitedArray(Index1), "=", -1, 1)
For Index2 = 0 To UBound(EqualtoSplitedArray)
If Index2 = 0 then
UrlEncodeString=UrlEncodeString & Server.URLEncode(EqualtoSplitedArray(Index2))
Else
UrlEncodeString=UrlEncodeString &"="& Server.URLEncode(EqualtoSplitedArray(Index2))
End if
Next
If Index1 = 0 then
NvpUrlEncodeString= NvpUrlEncodeString & UrlEncodeString
Else
NvpUrlEncodeString= NvpUrlEncodeString &"&"&UrlEncodeString
End if
UrlEncodeString=""
Next
URLEncode = NvpUrlEncodeString
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"URLEncode")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: Decodes a URL Encoded string
' Inputs:
' A URL encoded string
' Returns:
' Decoded string.
'----------------------------------------------------------------------------------
Function URLDecode(str)
On Error Resume Next
str = Replace(str, "+", " ")
For i = 1 To Len(str)
sT = Mid(str, i, 1)
If sT = "%" Then
If i+2 < Len(str) Then
sR = sR & _
Chr(CLng("&H" & Mid(str, i+1, 2)))
i = i+2
End If
Else
sR = sR & sT
End If
Next
URLDecode = sR
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"URLDecode")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: It's Workaround Method for Response.Redirect
' It will redirect the page to the specified url without urlencoding
' Inputs:
' Url to redirect the page
'----------------------------------------------------------------------------------
Function ReDirectURL( token )
On Error Resume Next
payPalURL = PAYPAL_URL & token & "&useraction=commit"
response.clear
response.status="302 Object moved"
response.AddHeader "location", payPalURL
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"ReDirectURL")
else
SESSION("Message") = Null
End If
End Function
%>
As I have a fully working implementation I am reluctant to embrace a different solution (and go through a whole load more development).
I have a sneaking suspicion that the 'CallShortcutExpressCheckout' is nothing more that a glorified call to SetExpressCheckout with some very specific parameters set and that it need modification or replacing with a direct call to SetExressCheckout?
Has anyone got some sample classic ASP code?
c
I think you can add to the nvpstr more fields.
You can add also a field like "L_PAYMENTREQUEST_0_NUMBER0" to indentify your product/service id/code the user still paying for. (just a suggestion)
I've rebuild one function, but need to be tested if is working right.
Anyway this is an idea:
Function CallShortcutExpressCheckout( title, description, paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("L_PAYMENTREQUEST_0_NAME0") & "=" & Server.URLEncode(title) & _
"&" & Server.URLEncode("L_PAYMENTREQUEST_0_DESC0") & "=" & Server.URLEncode(description) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------------------------------------------
' Make the API call to PayPal
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallShortcutExpressCheckout = resArray
End Function
Related
`Option Compare Database
Option Explicit
Dim argcount As Integer
Dim mysql As String, msg As String, mysource As String, mycriteria As String, mysource1 As String, mysql1 As String
Private Sub AddtoWhere(FieldValue As Variant, FieldName As String, mycriteria As String, argcount As Integer)
' Create criteria for WHERE clause.
If FieldValue <> "" Then
' Add "and" if other criterion exists.
If argcount > 0 Then
mycriteria = mycriteria & " and "
End If
' Append criterion to existing criteria.
' Enclose FieldValue and asterisk in quotation marks.
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
' Increase argument count.
argcount = argcount + 1
End If
End Sub
Private Sub Search_Click()
Dim Search As String
here:
argcount = 0
' Initialize SELECT statement.
mysql = "SELECT * FROM tbltab WHERE "
mycriteria = ""
mysql1 = "SELECT * FROM tblTemp WHERE "
mycriteria = ""
' Use values entered in text boxes in form header to create criteria for WHERE clause.
AddtoWhere cboProduct, "ABC1", mycriteria, argcount
AddtoWhere cboSource, "ABC2", mycriteria, argcount
AddtoWhere cboPType, "ABC3", mycriteria, argcount
'If no criterion specifed, stop the search.
'you'll be glad you did if there are thousands of Persons maybe.
If mycriteria = "" Then
mycriteria = True
End If
' Create SELECT statement.
mysource = mysql & mycriteria
mysource1 = mysql1 & mycriteria
Dim strval As String
'set the recordsource of the subform to the resultset
Me!sfrmCap.Form.RecordSource = mysource
Me!sfrmCapTemp.Form.RecordSource = mysource1
Exit_cmdsearch_Click:
Exit Sub
Err_cmdsearch_Click:
DoCmd.Hourglass False
DoCmd.Echo True
MsgBox Err.Description & " Person Search Command Cancelled", vbInformation, "Person Search Command Cancelled"
Resume Exit_cmdsearch_Click
End Sub
`I have a form in which there are 2 subform. I have a search button which when click search record using combo box values but in one combo box it display just related record not the complete search.
Can anyone help me in this.
Thank you.
In AddtoWhere() you assemble your WHERE clause, adding new conditions like this:
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
If you are unsure about what this actually does, you can put a breakpoint on the line (double clicking in the margin in front of the line) and see for yourself while executing the program.
If you do, you'll find out that a new condition like this will be added:
Source Like "Pre 2017 Source1*"
The * (encoded with Chr(42) in your code) acts as a joker matching any characters, so this condition returns everything that begins with Pre 2017 Source1 - as you can see in the search results.
If you do not want this behaviour, just remove the star from the SQL code and only exact matches will be returned.
Btw.: You should improve that code line like this:
mycriteria = mycriteria & FieldName & " LIKE '" & Replace(FieldValue, "'", "''") & "'"
This removes the unnecessary use of Chr(), replaces double quotes by single quotes as SQL string delimiters as it is recommended, and enables the code to handle values that contain quotes, which would otherwise result in a runtime error.
Here is my table structure:
ID1 - autonumber
TDate - Date/Time
TTime - Date/Time
TID - Text
TMessage - Text
Tcode - text
TMessage value can be 100+ characters. There can be more than 1 TMessage for each TID
Sample input:
TDate TID TTime TMessage
1/9/2014 93378 12:28:28 PM aaaaaaaaaaaa
7/24/2014 02645 12:56:22 PM bbbbbbbbbbbb
7/24/2014 02645 12:56:30 PM cccccccccccc
Output should be:
TDate, TID, TMessage
1/9/2014 93378 aaaaaaaaaa
7/24/2014 02645 bbbbbbbbbb,cccccccccccc (the output can be more than 255 chars.)
This is my query/module (got from Stackoverflow and Allen Brown)
Query (SQL View)
SELECT sub.TDate, sub.TID, ConcatRelated("[TMessage]","RawData2","[TDate] = '" & sub.TDate & "' AND [TID] = '" & sub.TID & "'","[TDate], [TID]") AS concat_Message
FROM (SELECT q.TDate, q.TID FROM RawData2 AS q GROUP BY q.TDate, q.TID) AS sub
ORDER BY sub.TDate, sub.TID;
Function :
Option Compare Database
Public Function ConcatRelated(strField As String, _
strTable As String, _
Optional strWhere1 As Date, _
Optional strWhere2 As String, _
Optional strOrderBy1 As Date, _
Optional strOrderBy2 As String, _
Optional strSeparator = ", ") As Variant
On Error GoTo Err_Handler
'Purpose: Generate a concatenated string of related records.
'Return: String variant, or Null if no matches.
'Arguments: strField = name of field to get results from and concatenate.
' strTable = name of a table or query.
' strWhere = WHERE clause to choose the right values.
' strOrderBy = ORDER BY clause, for sorting the values.
' strSeparator = characters to use between the concatenated values.
'Notes: 1. Use square brackets around field/table names with spaces or odd characters.
' 2. strField can be a Multi-valued field (A2007 and later), but strOrderBy cannot.
' 3. Nulls are omitted, zero-length strings (ZLSs) are returned as ZLSs.
' 4. Returning more than 255 characters to a recordset triggers this Access bug:
' http://allenbrowne.com/bug-16.html
Dim rs As DAO.Recordset 'Related records
Dim rsMV As DAO.Recordset 'Multi-valued field recordset
Dim strSql As String 'SQL statement
Dim strOut As String 'Output string to concatenate to.
Dim lngLen As Long 'Length of string.
Dim bIsMultiValue As Boolean 'Flag if strField is a multi-valued field.
'Initialize to Null
ConcatRelated = Null
'Build SQL string, and get the records.
strSql = "SELECT " & strField & " FROM " & strTable
If strWhere1 <> vbNullString And strWhere2 <> vbNullString Then
strSql = strSql & " WHERE " & strWhere1 And strWhere2
End If
If strOrderBy1 <> vbNullString And strOrderBy2 <> vbNullString Then
strSql = strSql & " ORDER BY " & strOrderBy1 And strOrderBy2
End If
Set rs = DBEngine(0)(0).OpenRecordset(strSql, dbOpenDynaset)
'Determine if the requested field is multi-valued (Type is above 100.)
bIsMultiValue = (rs(0).Type > 100)
'Loop through the matching records
Do While Not rs.EOF
If bIsMultiValue Then
'For multi-valued field, loop through the values
Set rsMV = rs(0).Value
Do While Not rsMV.EOF
If Not IsNull(rsMV(0)) Then
strOut = strOut & rsMV(0) & strSeparator
End If
rsMV.MoveNext
Loop
Set rsMV = Nothing
ElseIf Not IsNull(rs(0)) Then
strOut = strOut & rs(0) & strSeparator
End If
rs.MoveNext
Loop
rs.Close
'Return the string without the trailing separator.
lngLen = Len(strOut) - Len(strSeparator)
If lngLen > 0 Then
ConcatRelated = Left(strOut, lngLen)
End If
Exit_Handler:
'Clean up
Set rsMV = Nothing
Set rs = Nothing
Exit Function
Err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "ConcatRelated()"
Resume Exit_Handler
End Function
Currently, this is the output:
TDate TID Concat_Message
1/9/2014 93378 #Error
7/24/2014 02645 #Error
7/24/2014 04533 #Error
Question 1 - What could be the reason for the Error? How to solve it?
Question 2 - Can I just create a table manually with Memo field so I can store the result of the Query to this table?
I am trying to filter a form that emails only the current record. I have tried to do the me.filter command but cannot seem to get the syntax correct. I have provided the code below. The Current Date field is a date field and the Discover, Tail, and FleetID fields are text fields. I was told to put in the me.filter code the primary keys of the table that the form is linked to so the pdf that is produced does not print all the records linked to the form. Please let me know if you see something with my code. Thanks in advance :)
On Error GoTo errhandle
Me.Filter = "CurrentDate= #" & Me!CurrentDate & "#" And "Discover= '" & Me!Discover & "'" And "Tail= '" & Me!Tail & "'" And "FleetID= '" & Me!FleetID & "'"
Me.FilterOn = True
DoCmd.SendObject acSendForm, "frmETIC", acFormatPDF, "email address", "", "", "Recovery Report", "Attached is the submitted Recovery Report"
exitErr:
Exit Sub
errhandle:
If Err.Number <> 2501 Then
MsgBox ("Email cancelled!")
End If
Resume exitEr
All those And-operators are meant to be for the filtering, so they need to be inside the filter-string. Otherwise they are used as boolean operators in VBA, which will cause a type mismatch error when used on strings.
Another issues with your code is the date in the filter string. You will not get the desired result unless the date is formatted properly for use in a SQL criteria.
Replace the line Me.Filter = ... with the following to fix both problems.
Me.Filter = "CurrentDate= #" & Format(Me!CurrentDate, "yyyy\-mm\-dd") & "# AND Discover= '" & Me!Discover & "' AND Tail= '" & Me!Tail & "' AND FleetID= '" & Me!FleetID & "'"
If this filter string does not return the expected results, put a Debug.Print Me.Filter on the next line. This will print the actual filter string into the Immediate Window and allow you to see if it contains the expected values. For further debugging create a new Query in Access, switch to SQL View and enter SELECT * FROM yourTable WHERE filterStringOutput as SQL. Run the query. If it does not return the expected records, remove the criteria one by one to find the one that is causing problems.
Can anyone point me to an example of an Access form which can create multiple records (in a single table) based on one form?
To expand: we're recording information about time spent on a project on a given date. We've had a request for a single form that would allow a user to enter data for 5 (or 7) days of a given week on a single form. He/she would pick a week from a calendar control, a project from a listbox, then enter up to 7 numbers for the hours spent that week.
I did check questions 5294128, which doesn't seem applicable, and question 8070706, which seems to imply that this can only be done in VBA (not using the GUI). Any alternatives?
Thanks.
Something on these lines should suit. This is an unbound form with a subform.
You can get the form type from the form wizard
To work properly, you will need a little code, say:
Private Sub cmdGo_Click()
Dim rs As DAO.Recordset
Dim sSQL As String
Dim sSDate As String
Dim sEDate As String
sSDate = "#" & Format(Me.txtStartDate, "yyyy/mm/dd") & "#"
sEDate = "#" & Format(Me.txtStartDate + Me.txtNoDays, "yyyy/mm/dd") & "#"
sSQL = "SELECT * FROM MyTable WHERE DataDate Between " & sSDate _
& " AND " & sEDate
Set rs = CurrentDb.OpenRecordset(sSQL)
If rs.RecordCount < Me.txtNoDays Then
AddRecords sSDate, sEDate
End If
Me.DataSubform.Form.RecordSource = sSQL
End Sub
Sub AddRecords(sSDate, sEDate)
''Uses counter table with integers from 0 to
''highest required number
''Another useful table is a calendat table, which would
''save some work here.
sSQL = "INSERT INTO MyTable (DataDate) " _
& "SELECT AddDate FROM " _
& "(SELECT " & sSDate _
& " + [counter.ID] AS AddDate " _
& "FROM [Counter] " _
& "WHERE " & sSDate _
& "+ [counter.ID] Between " & sSDate _
& " And " & sEDate & ") a " _
& "WHERE AddDate NOT In (SELECT DataDate FROM MyTable)"
CurrentDb.Execute sSQL, dbFailOnError
End Sub
I'm just getting my head around insert statements today after getting sick of cheating with Dreamweaver's methods to do this for so long now (please don't laugh).
One thing I'm trying to figure out is how to get the ID value of a newly inserted record so I can redirect the user to that page if successful.
I have seen some examples which talk about stored procedures, but they're double dutch for me at the moment and I'm yet to learn about these, let alone how to use these from within my web pages.
Summary
How do I, using my code below retrieve the record ID for what the user has just inserted.
Workflow
Using a HTML form presented on an ASP page (add.asp), a user will submit new information which is inserted into a table of a database (treebay_transaction).
On pressing submit, the form data is passed to another page (add_sql.asp) which takes the submitted data along with additional information, and inserts it into the required table.
If the insert is successful, the id value of the new record (stored in the column treebay_transaction_id) needs to be extracted to use as part of a querystring before the user is redirected to a page showing the newly inserted record (view.asp?id=value).
Sample code - add_sql.asp
<!--#include virtual="/Connections/IntranetDB.asp" -->
...
<html>
<body>
<%
set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = MM_IntranetDB_STRING
conn.Open ConnectionString
...
sql="INSERT INTO treebay_transaction (treebay_transaction_seller,treebay_transaction_start_date,treebay_transaction_expiry_date,treebay_transaction_title,treebay_transaction_transaction_type,treebay_transaction_category,treebay_transaction_description,treebay_transaction_status)"
sql=sql & " VALUES "
sql=sql & "('" & CurrentUser & "',"
sql=sql & "'" & timestampCurrent & "',"
sql=sql & "'" & timestampExpiry & "',"
sql=sql & "'" & Request.Form("treebay_transaction_title") & "',"
sql=sql & "'" & Request.Form("treebay_transaction_transaction_type") & "',"
sql=sql & "'" & Request.Form("treebay_transaction_category") & "',"
sql=sql & "'" & Request.Form("xhtml1") & "',"
sql=sql & "'3')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
%>
<h1>Error!</h1>
<p>
...error text and diagnostics here...
</p>
<%
else
' this is where I should be figuring out what the new record ID is
recordID = ??
' the X below represents where that value should be going
Response.Redirect("index.asp?view.asp?id='" & recordID & "'")
end if
conn.close
%>
</body>
</html>
Run this after your execute statement and before you close your connection:
lsSQL = "SELECT ##IDENTITY AS NewID"
Set loRs = loConn.Execute(lsSQL)
llID = loRs.Fields("NewID").value
I pulled it from here:
http://www.kamath.com/tutorials/tut007_identity.asp
Build your sql variable as you have been. Let's make one trip to the DB instead of two. We'll use SCOPE_IDENTITY() right in the same statement(s) as the INSERT to avoid many trips to the database.
Add this when building your SQL statement:
sql=sql & "; SELECT SCOPE_IDENTITY() As NewTreebayTransactionID"
'now execute the insert and receive the ID in one Execute statement.
set newTransactionResults = conn.Execute(sql)
'here is our new ID.
recordID = newTransactionResults("NewTreebayTransactionID")
As soon as that's done:
sanitize your data inputs from your user
use parameterized statements
Set objConn = CreateObject("ADODB.Connection")
set rs = Server.CreateObject("ADODB.Recordset")
objConn.Open "DSN=connectionName"
rs.CursorLocation = 3
rs.Open "treebay_transaction", objConn, 3, 3
rs.AddNew fieldlist,values 'see link bellow to see how to fill this
rs.Update
bookmark = rs.absolutePosition ' First, store the location of you cursor
rs.Requery ' Next, update your recordset with the data from the database
rs.absolutePosition = bookmark ' Finally, change your cursor back
recordID = rs("ID")
rs.AddNew documentation: http://www.w3schools.com/ado/met_rs_addnew.asp
It depends on the database you are using, in SQL Server you can get the ##IDENTITY or SCOPE_IDENTITY() see: http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
But one thing I want to warn you, the code above has SEVERE security vulnerabilities, namely SQL Injection attack, please stay away from concatenating strings that are coming from users, you should use command paramaters.
look to ##IDENTITY, SCOPE_IDENTITY or IDENT_CURRENT
This makes the assumption that your ID field is an IDENTITY INSERT field. Also consider ramifications of the various options listed, as each one acts and performs slightly differently.
http://sqlserverpedia.com/wiki/Functions_-_##IDENTITY,_SCOPE_IDENTITY,_IDENT_CURRENT
With the same transaction :
Const adUseServer = 2
Const adOpenKeyset = 1
Const adLockOptimistic = 3
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open "DSN=connectionName"
Set oRS = Server.CreateObject("ADODB.RecordSet")
oRS.CursorLocation = aduseserver
oRS.CursorType = adopenkeyset
oRS.LockType = adlockoptimistic
oRS.Open "treebay_transaction", oConn
if oRS.eof then
oRS.AddNew
oRS("treebay_transaction_seller") = CurrentUser
...
oRS.Update
recordID = oRS("treebay_transaction_id")
end if
oRS.Close
set oRS = nothing
oConn.Close
Set oConn = Nothing