Excepted end of statement error in ASP - asp-classic

When inserting data into a database, the following error occurs
"Excepted end of statement"
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
objConn.Execute sqlstr

Try using single-word identifiers for your first-name and last-name variables:
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
" VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
objConn.Execute sqlstr
Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.
Your second problem is your code's vulnerability to SQL injection.
To help fix that problem, see:
Classic ASP SQL Injection Protection
http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1

You might have single quote in one of the values, resulting in invalid SQL. You have to escape single quotes, though better rewrite your code to use parameters instead.
sqlstr = "INSERT INTO tblContact (Email, FirstName, LastName, Comments) " & _
" VALUES ('" & Replace(Email, "'", "''") & "', '" & Replace(FirstName, "'", "''") & "', '" & Replace(LastName, "'", "''") & "', '" & Replace(Comments, "'", "''") & "')"
objConn.Execute sqlstr

Related

'SQL Problem' when trying to update Database in ASP.NET

i am currently learning the basics in ASP.NET and now at manipulating Database. It doesn't go to the Try section and straight away head to the Catch ex as Exception part which gives me the message box saying "Unsuccessful Operation or SQL problem.
dgvResult.Visible = True
Try
conn.Open()
dd.Connection = conn
dd.CommandText = "update [STUDENT]" &
"set [Matric]= '" & txtMatric.Text & "', " &
"[Name] ='" & txtName.Text & "'," &
"[Address] ='" & txtAddress.Text & "'," &
"[Telephone] ='" & txtTelephone.Text & "'," &
" where [Matric] ='" & txtMatric.Text & "' "
dd.ExecuteNonQuery()
dd.Dispose()
conn.Close()
MsgBox("Data Updated")
Catch ex As Exception
MsgBox("Unsucessful Operation or SQL Problem")
End Try
End Sub
My task is to edit some information in database and save it.

What is wrong with this code asp.net using vb

I am getting this Error
Incorrect syntax near the keyword 'user'.
con.Open()
comm.Connection = con
comm.CommandText = "insert into user (username,firstname,lastname,email,password) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "')"
comm.ExecuteNonQuery()
Response.Write("Data Successfully Saved")
User is reserve key word, so use it like this
"insert into [user]
You need to use square brackets around user as it's a keyword.
By the way, this type of query is vulnerable to SQL injection attacks. (Think about what you can put into your text boxes to drop the entire users table, or how you could convert the first few names and passwords into an e-mail address for the user you're inserting.) You should use parameterised queries instead or stored procedures.

Can someone make this a single query?

So I was just searching how to do an "INSERT INTO" query and found this:
sql="INSERT INTO Customers (ID,firstName,"
sql=sql & "lastName)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("id") & "',"
sql=sql & "'" & Request.Form("firstname") & "',"
sql=sql & "'" & Request.Form("lastname") & "')"
I know it works but I want to make it a single query without all the sql=sql's
You took the route of a quick hack as stated in your comments by doing rhis:
sql="INSERT INTO Customers (ID,firstName,lastName) VALUES ('" & Request.Form("id") & "','" & Request.Form("fistname") & "','" & Request.Form("lastname") & "')"
Let me persist in stating that to prevent several issues (sql injection being one of them) you could leverage the use of paramterized queries.
I assume you have an ADO command somewhere after your sql statement. It is much safer if you use command parameters to send parameters from the website to the query.
command.CommandText = "INSERT INTO Customers (ID,firstName,lastName) VALUES (?,?,?)"
Set param = command.CreateParameter ("id", adInteger, adParamInput)
param.value = Request.Form("id")
command.Parameters.Append param
Set param2 = command.CreateParameter ("firstname", adVarWChar, adParamInput, 50)
param2.value = Request.Form("firstname")
command.Parameters.Append param2
Set param3 = command.CreateParameter ("lastname", adVarWChar, adParamInput, 50)
param3.value = Request.Form("lastname")
command.Parameters.Append param3
command.Execute
Have a look at Command Object Parameters for more background.
You can do like this:
string sql = string.Format("INSERT INTO Customers(Id,FirstName,LastName) VALUES({0},'{1}','{2}')", param0, param1, param2);
It Works! But be careful this way have SQL Injection issues.

sql subquery syntax asp.net

I am trying to excute this sql query
Dim str As String = "UPDATE table1 SET " & _
"number = '" & strc & "'," & _
"code = '" & "123" & "'," & _
"line= '" & dd1.text & "'," & _
"sellr = '" & txtrun.text & "'," & _
"endu= '" & txtex1.value+txtex2.value & "'" & _
"WHERE number IN (select table1.number" & _
"FROM table1 INNER JOIN table2 ON table1.number = table2.number" & _
"WHERE ((table1.username)='" & session("username") & "' AND (table1.pass)='" & session("pass") & "' AND (table2.sellnum)='" & session("sellnum") & "'));"
there is a Syntax error in query expression and this is te first time I am using nested subquery
all the field are getting String values
So if someone can tell me what is the right approach to write this query I will be very grateful
You're missing spaces after table1.number and table2.number fields in the subquery.
I don't know where you're using this query, but you might want to read about SQL injection. When you stick strings together to build SQL, your code may be vulnerable to malicious users who put SQL code into the fields of your application.

Getting primary key after an insert in asp.net (visual basic)

I'm adding a record like this:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
odbconBanking.Close()
The primary key is an autonumber field called UserID. So, how do I get the primary key of the record I just inserted?
Thanks.
I believe a parameterized query would look something like this:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
//Add Params here
cmd.Parameters.Add(new OdbcParameter("#FirstName", firstName))
cmd.Parameters.Add(new OdbcParameter("#LastName", lastName))
//..etc
//End add Params here
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT ##IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
My syntax might be a bit off as I am more accustomed to using the Sql Server library and not the Odbc library, but that should get you started.
"SELECT ##IDENTITY" just after the insertion should work with Microsoft.Jet Provider.
You'll want to add
;select scope_identity();
after your query, and run executeScalar to get the value back.
Also, on a completely unrelated note, you really should change your code to use parameterized queries so you don't get caught with SQL injection attacks, or crashes due to inproperly escaped strings concatenated into your sql statement.
Got it. Here's how the above code looks now:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT ##IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
The simplest way would be to generate your uniqueIdentifier value at the code level, add it to your string and send it to the server.
Dim sql As String, _
myNewUserId as variant
myNewUserId = stGuidGen 'this function will generate a new GUID value)'
sql = "INSERT INTO tblUsers ( userId, LastName)" & _
" VALUES ('" & myNewUserId & "','" & LastName);"
You can check a proposal for the stGuidGen guid generating code here.
This client-side technique is clear, clean and usefull

Resources