2

I made this form to insert information in database. I don't know where the error coming from. It's not inserting information from input fields to database.

Here's my code:

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim id, name, description, code, cat_industry, cat_theme, cat_occasion, cat_budget As String
        id = product_id.Text
        name = product_name.Text
        description = product_description.Text
        code = item_code.Text
        cat_industry = industry.SelectedValue
        cat_theme = theme.SelectedValue
        cat_occasion = occasion.SelectedValue
        cat_budget = budget.SelectedValue

        Try
            Dim str1 As String = "insert into product (ID, Product_Name, Product_Description, Item_Code, Industry, Theme, Occasion, Budget) values ('" + id + "', '" + name + "', '" + description + "', '" + code + "', '" + cat_industry + "', '" + cat_theme + "', '" + cat_occasion + "', '" + cat_budget + "')"
            con.Open()
            Dim cmd As New SqlCommand(str1, con)
            cmd.ExecuteNonQuery()
            con.Close()
        Catch ex As Exception
            Response.Write(ex)
        End Try
    End Sub
nha
  • 17,623
  • 13
  • 87
  • 133
  • 3
    You're asking for SQL injection with that insert statement. Use parameterized queries instead – Izzy Nov 27 '14 at 10:18
  • 1
    Note that you seem to have edited the original question into a new question, thus losing the context of the original one. Please can you revert the edit and ask a new question if you are now having another issue with `checkboxes`. The original question was about Sql Data Insertion errors. – StuartLC Nov 27 '14 at 10:48

1 Answers1

3

Your column names can't be referenced as Product Name and Product Description with a space - you will need to escape it as [Product Name], [Product Description] etc.

But please refrain from inserting data directly - instead you should be parameterizing your input variables. This has benefits from both a performance and security (Sql Injection) perspective.

 Dim str1 As String = "insert into product (ID, [Product Name], [Product Description], Item_Code, etc) " _
                      " values (@id, @name, @description, @code, etc)"
 con.Open()
 Dim cmd As New SqlCommand(str1, con)
 cmd.Parameters.AddWithValue("@id", id )
 cmd.Parameters.AddWithValue("@name", name )
 ... etc
 cmd.ExecuteNonQuery()
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285