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 ?
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();
If this is just an assignment and not a real-world program then do the following.
cmd.CommandText = $"Select * from {userType} where username=@user and password=@pass";
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