Error when takling a user input and seeing if it is in an Sql Database

30 views Asked by At

I'm trying to develop a simple Clock-in/out system where the user inputs their details and it will check if they are in the database before proceeding with the next functions.

this is the code i have tried. When I run the code it throws up the following error "Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'Bobbo'.'" however when i take the ManagerSurname out of the code it works as expected.

SqlConnection connection =  new SqlConnection(ConnectionString);

            connection.Open();

            int ManagerID = int.Parse(tbx_MngNumber.Text);
            string managerSurname = tbxMangSurname.Text;
            string ManagerPhoneNumber = tbxNumber.Text;
            string query = $"SELECT  ManagerFirstName FROM ManagerTable WHERE ManagerID={ManagerID} AND ManagerSurname={managerSurname} AND ManagerPhoneNumber={ManagerPhoneNumber}";
            using (SqlCommand cmd = new SqlCommand(query, connection))
            {
                cmd.Parameters.AddWithValue("@ManagerSurname", managerSurname);
                cmd.Parameters.AddWithValue("@ManagerID", ManagerID);
                cmd.Parameters.AddWithValue("@ManagerPhoneNumber", ManagerPhoneNumber);

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    MessageBox.Show("manager");
                }
                else
                {
                    MessageBox.Show("no");
                }
            }
1

There are 1 answers

0
Suryateja KONDLA On

In this line, the managerSurname and ManagerPhoneNumber are string values and need to be enclosed in quotes in the SQL query. However, it's better to use parameterized queries to avoid these kinds of issues and to protect against SQL injection. You've already added parameters to your command, but you're not using them in your query

string query = "SELECT ManagerFirstName FROM ManagerTable WHERE ManagerID=@ManagerID AND ManagerSurname=@ManagerSurname AND ManagerPhoneNumber=@ManagerPhoneNumber";