I don't know what is the error in the sql syntax

-1

I am implementing a login form using C# and MySQL, The user should enter his/her username and password then select if he/she is a student, instructor or admin. then I want to check if entered values are correct , here is my code:

connection.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from @userType where username=@user and password=@pass";
cmd.Parameters.AddWithValue("@userType", userType);
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);

cmd.Connection = connection;
MySqlDataReader login = cmd.ExecuteReader();

But the query didn't work ! the error message :

MySql.Data.MySqlClient.MySqlException, HResult=0x80004005, Message=You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''student' where username='noor123' and password='123456'' at line Source=MySql.Data

what is the error ?

c#
mysql
asked on Stack Overflow Apr 2, 2019 by Noor • edited Apr 2, 2019 by Mighty Badaboom

2 Answers

2

The SQL query generated by that code is:

Select * from 'student' where username="noor123" and password="123456"

The table can't be inside '' as that's not correct SQL syntax.

You can't use the parameter for the table name, do this instead, this way you won't get '' for the table name:

connection.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from " + userType.ToString() + " where username=@user and password=@pass";
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);

cmd.Connection = connection;
MySqlDataReader login = cmd.ExecuteReader();
answered on Stack Overflow Apr 2, 2019 by Oscar Arranz • edited Apr 2, 2019 by Oscar Arranz
0

If this is just an assignment and not a real-world program then do the following.

  1. Make sure variables userType, user and pass are of type String.
  2. Make sure that userType represents a syntactically correct table or view name.
  3. Update this line cmd.CommandText = $"Select * from {userType} where username=@user and password=@pass";
  4. Remove this line cmd.Parameters.AddWithValue("@userType", userType);

I believe that should help. I didn't check myself.

However in real world you shouldn't program it this way. There are many security considerations when dealing with authentication/authorization not mentioning the possibility for sql injection. If this is a real project then I recommend you to read appropriate materials regarding the subject.


User contributions licensed under CC BY-SA 3.0