Monday, 13 November 2017

SQL injection

using (MySqlConnection objConn = new MySqlConnection(ConnString))
{
   
// string sql = "SELECT UserId FROM User WHERE " + "(email = '" + email + "' AND " + "password = '" + password + "')";//Never use this way, it will leads to SQL injections
    string sql = "SELECT UserID FROM User WHERE email = @email and password = @password "; //This way we r createing SQL statement dynamically
    using (MySqlCommand cmd = new MySqlCommand(sql))
    {
         cmd.Connection = objConn;
         cmd.Parameters.AddWithValue("@email", email);
         cmd.Parameters.AddWithValue("@password", password);  
  try
           {
             cmd.Connection.Open();
             var userId = cmd.ExecuteScalar();
         }
         catch (SqlException sx)
         {
             // Handle exceptions before moving on.
         }
     }
}