Nyrre
Nyrre

Reputation: 28

Incorrect syntax near the keyword 'add'

I have a project in school and and I need to connect my registration page with a database. I have this code:

if (Request.Form["submit"] != null)
{
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];
    string Passwod = Request.Form["Passwod"];
    string email = Request.Form["email"];
    string add = Request.Form["add"];

    string RegStatus;

    if ((fName == "") || (lName == "") || (Passwod == "") || (email == "") || (add == ""))
    {
        RegStatus = ("missing data or wrong data");
    }
    else
    {
        string selectQuery = "SELECT * FROM " + "[Users]";
        selectQuery += " WHERE ";
        selectQuery += " email = '" + Request.Form["email"] + "'";

        if (MyAdoHelper.IsExist(selectQuery))
        {
            RegStatus = ("email does not exists");
        }
        else
        {
            string insertQuery = "INSERT INTO [Users] (fName,lName,Passwod, email,add) VALUES ('";
            insertQuery += fName + "', '" + lName +"','" + Passwod + "', '" + email + "','" + add +"')";
            Response.Write(insertQuery);
            MyAdoHelper.DoQuery(insertQuery);
            RegStatus = ("Registeration was successful "); 
        }
    }

    Response.Write(RegStatus);
    Response.End();
}

The error I get after filling the data (after running) is:

System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'add'.

source error:

public static void DoQuery(string sql)
    {
        SqlConnection conn = ConnectToDb();
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn); 
        com.ExecuteNonQuery(); //* it says the error is in this line. //*
        com.Dispose();
        conn.Close();
    }

Upvotes: 1

Views: 1953

Answers (1)

apomene
apomene

Reputation: 14389

add is a keyword on SQL. If you have a field named like this you must use brackets:

INSERT INTO [Users] (fName,lName,Passwod, email,[add]) VALUES... 

Also, as already commented, it is very important to use parameters and not string concatenation:

Upvotes: 4

Related Questions