Classic ASP functions for database queries and SQL injection protection

By · July 28, 2014 · 0 comments

If writing database queries in SQL in Classic ASP for SQL Server, rather than using ADO or parameterised queries, you can use these functions to correctly format your data and protect against SQL injection.

Numeric fields

ForceNumeric ensures that only numeric values are passed.

Function ForceNumeric(sngValue)
If IsNull(sngValue) Then
ForceNumeric = 0
ElseIf sngValue = "" Or Not IsNumeric(sngValue) Then
ForceNumeric = 0
Else
ForceNumeric = CSng(sngValue)
End If
End Function

String fields

Quotes adds single quotes around the string, and escapes single quotes within the string.

Function Quotes(strValue)
If IsNull(strValue) Then
Quotes = "null"
Else
Quotes = "'" & Replace(strValue, "'", "''") & "'"
End If
End Function

Date fields

FormatDateSql adds quotes and formats dates to a SQL friendly format (yyyy-mm-dd). If not a valid date or a null value then it returns "null".

FormatDateTimeSql does the same except it adds the time too, down to seconds.

Function FormatDateSql(datValue)
If IsNull(datValue) Then
FormatDateSql = "Null"
ElseIf datValue = "" Then
FormatDateSql = "Null"
ElseIf IsDate(datValue) Then
FormatDateSql = Quotes(Year(datValue) & "-" & Right("0" & Month(datValue), 2) & "-" & Right("0" & Day(datValue), 2))
Else
FormatDateSql = "Null"
End If
End Function

Function FormatDateTimeSql(datValue)
If IsNull(datValue) Then
FormatDateTimeSql = "Null"
ElseIf datValue = "" Then
FormatDateTimeSql = "Null"
ElseIf IsDate(datValue) Then
FormatDateTimeSql = Quotes(Year(datValue) & "-" & Right("0" & Month(datValue), 2) & "-" & Right("0" & Day(datValue), 2) & " " & Right("0" & Hour(datValue), 2) & ":" & Right("0" & Minute(datValue), 2) & ":" & Right("0" & Second(datValue), 2))
Else
FormatDateTimeSql = "null"
End If
End Function

Boolean fields

CBit returns 1 or 0 to represent true or false.

Function CBit(booleanvalue)
If booleanvalue Then
CBit = 1
Else
CBit = 0
End If
End Function
Read more...
Classic ASP

Get the latest posts delivered to your inbox.

Comments

There are no comments yet. Be the first to leave a comment!

Leave a Comment

All comments are moderated and rel="nofollow" is in use. Avatars are sourced from gravatar.com – a globally recognised avatar.

Type the numbers from the picture above

About me
John Avis ...mostly about web development and programming, with a little bit of anything else related to the Internet, computers and technology.

profile for John at Stack Overflow, Q&A for professional and enthusiast programmers
Subscribe

Get the latest posts delivered to your inbox. *