System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'

don 0 Reputation points
2023-06-04T15:29:54.3133333+00:00

I am trying to make a simple web that gets your your username,email, etc... and stores it in a sql database (usersDB.mdf) the table name is(users)
But I am getting a error saying

System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'

here is my table:

CREATE TABLE [dbo].[users] (
    [uname]  NCHAR (50)  NOT NULL,
    [pass]   NCHAR (50)  NOT NULL,
    [fName]  NCHAR (50)  NOT NULL,
    [lName]  NCHAR (50)  NOT NULL,
    [YBorn]  INT         NOT NULL,
    [phone]  INT         NULL,
    [prefix] NCHAR (10)  NOT NULL,
    [Email]  NCHAR (100) NOT NULL,
    [Gender] NCHAR (50)  NOT NULL,
    [Admin]  NCHAR (3)   NULL,
    PRIMARY KEY CLUSTERED ([uname] ASC)
);


here is my client side code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="registration.aspx.cs" Inherits="web.registration" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script>
        function Don() {

            var uname = document.getElementById("uname").value;
            if (uname.length < 2) {
                document.getElementById("Muname").value = "the user name is to short";
                document.getElementById("Muname").style.display = "inline";
                return false;

            }
            else
                document.getElementById("Muname").style.display = "none";

            var pass = document.getElementById("pass").value;
            var verpass = document.getElementById("VerPass").value;
            if (pass != verpass) {
                document.getElementById("Mpass").value = "verification password must be the same as password";
                document.getElementById("Mpass").style.display = "inline";
                return false;

            }
            else
                document.getElementById("Mpass").style.display = "none";
            
            var email = document.getElementById("Email").value;
            var size = email.length;
            var atSign = email.indexOf('@');
            var dotSign = email.indexOf('.', atSign);

            var msg = "";
            if (size < 6 || size > 30)
                msg = "the email is too short or too long";
            else if (atSign == -1)
                msg = "the email must contain an @ character";
            else if (atSign != email.lastIndexOf('@'))
                msg = "@ can't be more than once in the email";
            else if (atSign < 2 || email.lastIndexOf('@') == size - 1)
                msg = "@ can't be placed at the start or at the end of the email";
            else if (email.indexOf('.') == 0 || email.lastIndexOf('.') == size - 1)
                msg = "dot can't be placed at the start or at the end of the email";
            else if (dotSign <= atSign + 1)
                msg = "dot needs to be at least two characters away from @";
            else if (!isQuot(email))
                msg = "the email can't contain quotation marks";
            else if (!isHebrew(email))
                msg = "email can't contain Hebrew letters";
            else if (!isValidString(email))
                msg = "email can't contain prohibited characters/symbols";

            if (msg != "") {
                document.getElementById("MEmail").value = msg;
                document.getElementById("MEmail").style.display = "inline";
                return false;
            } else {
                document.getElementById("MEmail").style.display = "none";
            }

            function isQuot(email) {
                var quot = '\"', quot1 = "\'";
                if (email.indexOf(quot) != -1 || email.indexOf(quot1) != -1) {
                    return false;
                }
                return true;
            }

            function isHebrew(email) {
                var len = email.length;
                var i = 0, ch;
                while (i < len) {
                    ch = email.charAt(i);
                    if (ch >= 'א' && ch <= 'ת') {
                        return false;
                    }
                    i++;
                }
                return true;
            }

            function isValidString(email) {
                var badChr = "$%^&*()-![]{}<>?";
                var len = email.length;
                var i = 0, pos, ch;
                while (i < len) {
                    ch = email.charAt(i);
                    pos = badChr.indexOf(ch);
                    if (pos != -1)
                        return false;
                    i++;
                }
                return true;
            
            }
            var YBorn = document.getElementById("YBorn").value;
            var msg = "";
            if (isNaN(YBorn))
                msg = "year of birth must contain only numbers";
            else {
                if (YBorn < 1900)
                    msg = "year of birth must be 4 digits long and bigger then 1900";
            }
            if (msg != "") {
                document.getElementById("MYBorn").value = msg;
                document.getElementById("MYBorn").style.display = "inline";
                msg = "";
                return false;
            }
            else
                document.getElementById("MYBorn").style.display = "none";
            return true;
        }
    </script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">   
    <form id="form1" runat="server" onsubmit="return Don()">
                <h1 style="color:white">Register</h1>
        <br />
        <br />
        
        <style>

            .input-group {
                position: relative;
            }

            .input {
                border: solid 1.5px #9e9e9e;
                border-radius: 1rem;
                background: #212121;
                padding: 1rem;
                font-size: 1rem;
                color: #f5f5f5;
                transition: border 150ms cubic-bezier(0.4,0,0.2,1);
            }

            .user-label {
                position: absolute;
                left: 15px;
                color: #e8e8e8;
                pointer-events: none;
                transform: translateY(1rem);
                transition: 150ms cubic-bezier(0.4,0,0.2,1);
            }

            .input:focus, input:valid {
                outline: none;
                border: 1.5px solid #1a73e8;
            }

                .input:focus ~ label, input:valid ~ label {
                    transform: translateY(-50%) scale(0.8);
                    background-color: #303030;
                    padding: 0 .2em;
                    color: #2196f3;
                }
        </style>

        <div class="input-group">
            <input  type="text" name="uname" id="uname" autocomplete="on" class="input">
            <label for="uname" class="user-label">userName</label>
            <input type="text" id="Muname" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>
        </div>

        <br />
        <br />
        <div class="input-group" >
            <input  type="password" name="pass" id="pass" class="input">
            <label for="pass" class="user-label">Password</label>
             <input type="text" id="Mpass" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>
        </div>
         <div class="input-group" >
            <input  type="password" name="VerPass" id="VerPass" class="input">
            <label for="pass" class="user-label">verification password</label>
        </div>
        <br />
        <br />
        <div class="input-group">
            <input required="" type="text" name="fName" id="fName" class="input">
            <label for="fName" class="user-label">First Name</label>
             <%--<input type="text" id="MfName" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>--%>
        </div>
        <br />
        <br />
        <div class="input-group">
            <input required="" type="text" name="lName" id="lName"  class="input">
            <label for="lName" class="user-label">Last Name</label>
             <%--<input type="text" id="MlName" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>--%>
        </div>
        <br />
        <br />
        <div class="input-group">
            <input  type="text" name="Email" id="Email"  class="input">
            <label for="Email" class="user-label">Email</label>
             <input type="text" id="MEmail" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>
        </div>
        <br />
        <br />
        <label for="YBorn" style="color: #2196f3">Year of Born: </label>
        <input type="number" name="YBorn" id="YBorn" style="border: solid 1.5px #9e9e9e; border-radius: 1rem; background-color: #212121; color: white; font-size: 1rem; padding: 0.5rem;" />
         <input type="text" id="MYBorn" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>
        <br />
        <br />
        <script>
            function showTextBox(value) {
                var textBox = document.getElementById("Gender");
                if (value === "other") {
                    textBox.style.display = "block";
                } else {
                    textBox.style.display = "none";
                }
            }
        </script>
        <style>
            .cont {
                display: flex;
                align-items: center;
                transform: scale(1);
            }

            input[type="radio"] {
                height: 1.2rem;
                width: 1.2rem;
                margin: 5px;
                display: inline-block;
                appearance: none;
                position: relative;
                background-color: #303030;
                border-radius: 15%;
                cursor: pointer;
                overflow: hidden;
            }

                input[type="radio"]::after {
                    content: '';
                    display: block;
                    height: 0.7rem;
                    width: .3rem;
                    border-bottom: .22rem solid #a0ffe7;
                    border-right: .22rem solid #a0ffe7;
                    opacity: 0;
                    transform: rotate(45deg) translate(-50%, -50%);
                    position: absolute;
                    top: 45%;
                    left: 21%;
                    transition: .25s ease;
                }

                input[type="radio"]::before {
                    content: '';
                    display: block;
                    height: 0;
                    width: 0;
                    background-color: #00C896;
                    border-radius: 50%;
                    opacity: .5;
                    transform: translate(-50%, -50%);
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transition: .3s ease;
                }

                input[type="radio"]:checked::before {
                    height: 130%;
                    width: 130%;
                    opacity: 100%;
                }

                input[type="radio"]:checked::after {
                    opacity: 100%;
                }

            span {
                font-size: 2rem;
            }
            #Submit1 {
                height: 29px;
            }
        </style>
        <div style="color: white">
            <p style="color:#2196f3">Gender:<br />
            <label class="cont">
                <br />
                <input type="radio" name="Gender" value="Male" onclick="showTextBox(this.value)" checked>Male
                <br/>
            </label>
            <label class="cont">
                <input type="radio" name="Gender" value="Female" onclick="showTextBox(this.value)">Female<br>
            </label>
            <label class="cont">
                <input type="radio" name="Gender" value="Nonbinary" onclick="showTextBox(this.value)">Nonbinary<br>
            </label>
            <label class="cont">
                <input type="radio" name="Gender" value="Transgender" onclick="showTextBox(this.value)">Transgender<br>
            </label>
            <label class="cont">
                <input type="radio" name="Gender" value="other" onclick="showTextBox(this.value)">Other<br>
            </label>

            <input type="text" id="Gender" name="Gender" style="display: none; border: solid 1.5px #9e9e9e; border-radius: 1rem; background: #212121  ; color: white; font-size: 1rem; padding: 0.5rem;">
        </div>
        <br />
        <br />
        <label for="prefix">prefix: </label>
        <select name="prefix" id="prefix" style="border: solid 1.5px #9e9e9e; border-radius: 1rem; background-color: #212121; color: white; font-size: 1rem; padding: 0.5rem;">
            <option value="050">050</option>
            <option value="051">051</option>
            <option value="052">052</option>
            <option value="053">053</option>
            <option value="054">054</option>
            <option value="055">055</option>
            <option value="056">056</option>
            <option value="057">057</option>
            <option value="058">058</option>
            <option value="059">059</option>
        </select>

        <label for="phone">phone: </label>
        <input type="number" name="phone" id="phone" style="border: solid 1.5px #9e9e9e; border-radius: 1rem; background: #212121; color: white; font-size: 1rem; padding: 0.5rem;" />
         <input type="text" id="Mphone" size="30" style="display:none;background-color:none;font-weight:bold;color:red" disabled="disabled"/>
        <br />
        <br />
        <link href="css%20files/StyleSheet1.css" rel="stylesheet" />
        <button class="shadow__btn" id="submit" name="submit" type="submit" value="submit" <%--onclick="Page_Load(form2)"--%>>
            submit
        </button>

        <link href="css%20files/clear%20botton.css" rel="stylesheet" />
        <button class="btn" type="reset">clear</button>
        <br />
        <br />
        <nav>
        <a href="login.aspx">already have an account? login</a>
        </nav>
        <br />
        <br />
    <h3><%=sqlMsg %></h3>
    <h3><%=msg %>
        </h3>




    </form>
 
  
</asp:Content>

Here is my server side code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace web
{
    public partial class registration : System.Web.UI.Page
    {
        public string st = "";
        public string msg = "";
        public string sqlMsg = "";
        public string formMsg = "";
        public string sqlSelect;
        protected void Page_Load(object sender, EventArgs e)
        {

            string fileName = "usersDB.mdf";
            string tableName = "users"; 

            if (Request.Form["submit"] != null)
            {
                string uname = Request.Form["uname"];
                string pass = Request.Form["pass"];
                string fName = Request.Form["fName"];
                string lName = Request.Form["lName"];
                string YBorn = Request.Form["YBorn"];
                if (YBorn is null)
                { YBorn = "0"; }
                string phone = Request.Form["phone"];
                if (phone is null)
                { phone = "0"; }
                //int pn = int.Parse(phone);
                string prefix = Request.Form["prefix"];
                string Email = Request.Form["Email"];
                string Gender = Request.Form["Gender"];
                string Admin = Request.Form["Admin"];
                if (Admin is null)
                    Admin = "NO";
                sqlSelect = $"SELECT * FROM {tableName} WHERE uname = '{uname}'";

                if (Helper.IsExist(fileName, sqlSelect))
                {
                    msg = "User name is already taken";
                    sqlMsg = sqlSelect; 
                }
                else
                {
                    string sqlInsert =$"INSERT INTO {tableName}";
                    sqlInsert += $"VALUES ('{uname}','{pass}','{fName}','";
                    sqlInsert +=$"{lName}','{YBorn}','";
                    sqlInsert +=$"{phone}','{prefix}','";
                    sqlInsert +=$"{Email}','{Gender}','{Admin}')";
                    sqlMsg = sqlInsert;
                    Helper.DoQuery(fileName, sqlInsert);
                    msg = "!account created successfully!";
                    Session["uname"] = uname;

                }
            }
            

        }
        
    }
}
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,307 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2023-06-04T16:42:06.7733333+00:00

    Bad things usually happen when creating an SQL statement with string concatenation without parameters.

    The following is a basic example

    • Placing data operations in its own class is recommended
    • Using Parameters via .Add over .AddWithValue is best
    • I excluded error handling for clarity, the Open method and ExecuteScalar should be in a try/catch
    • Once ExecuteScalar has executed (in this case for SQL-Server) we assign the primary key to the entity customer
    • Note the CommandText is using C# 11 raw string literals, if using an earlier version of C# use @""
    internal class DataOperations
    {
        public static void AddCustomer(Customer customer)
        {
    
            using var cn = new SqlConnection("TODO");
    
            // insert new record, get new primary key
            using var cmd = new SqlCommand
            {
                Connection = cn,
                CommandText =
                    """
                        INSERT INTO dbo.Customer (CompanyName, ContactName, ContactTypeIdentifier, GenderIdentifier) 
                        VALUES (@CompanyName,  @ContactName,  @ContactTypeIdentifier,  @GenderIdentifier);
                        SELECT CAST(scope_identity() AS int);
                        """
            };
    
    
            cmd.Parameters.Add("@CompanyName", SqlDbType.NChar).Value =
                customer.CompanyName;
    
            cmd.Parameters.Add("@ContactName", SqlDbType.NChar).Value =
                customer.ContactName;
    
            cmd.Parameters.Add("@ContactTypeIdentifier", SqlDbType.Int).Value =
                customer.ContactTypeIdentifier;
    
            cmd.Parameters.Add("@GenderIdentifier", SqlDbType.Int).Value =
                customer.GenderIdentifier;
    
            cn.Open();
    
            customer.Identifier = Convert.ToInt32(cmd.ExecuteScalar());
        }
    }
    
    // belongs in its own file
    internal class Customer
    {
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public int ContactTypeIdentifier { get; set; }
        public int GenderIdentifier { get; set; }
        public int Identifier { get; set; }
    }
    
    
    
    0 comments No comments