0

I'm trying to get the IsAdmin Value with SQL query(This query return 1 line or 0). but i get this error {"invalide reading Tentative there are no any data present."} This is my code

        public static bool Login (string iduser, string password, bool IsAdmin)
    {
        bool auth = false;
        string query = string.Format("Select IsAdmin from [user] where iduser = '{0}' AND mdp = '{1}' ;", iduser, password);
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader re = cmd.ExecuteReader();
        auth = re.HasRows;
        if (auth) { IsAdmin = re.GetBoolean(0); } // the error is on this line (this line will alow me to get IsAdmin Value If the user exist)
        con.Close();
        return auth;

    }
3
  • Maybe someone has hacked your site using SQL Injection and deleted all the users? Also, SqlDataReader is IDisposable. Commented Apr 2, 2012 at 21:15
  • This is not an answer to your question, but the way you are making your SQL query is liable to SQL injection attacks. You should always use parameterized queries. Commented Apr 2, 2012 at 21:16
  • Oh this makes me crave to enter a password like '; drop table [user]; -- Commented Apr 3, 2012 at 10:44

2 Answers 2

6

You are open to horrible SQL injection. Your site will be pwned by hackers the very same second you put it online if you don't use parametrized queries.

Like this:

public static bool IsAdmin(string iduser, string password)
{
    using (var conn = new SqlConnection(ConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = @"
            SELECT IsAdmin 
            FROM [user] 
            WHERE iduser = @iduser AND mdp = @mdp;
        ";
        cmd.Parameters.AddWithValue("@iduser", iduser);
        cmd.Parameters.AddWithValue("@mdp", password);
        using (var reader = cmd.ExecuteReader())
        {
            return reader.Read() && reader.GetBoolean(reader.GetOrdinal("IsAdmin"));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to call

re.Read();

to move the reader to the first record before attempting to access the data. re.HasRows does not cause the reader to move to the first record.

Also, definitely use parameterized queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.