3

I am trying to get the row count of my accounts table so that I can login accounts but the MySQL parameters aren't adding the values.

Here is my code:

public int MyMethod(string username, string password)
{
    int count = 0;
    string query = "SELECT * FROM accounts WHERE username = '?user' AND password = '?pass' LIMIT 1;";

    using (MySqlCommand cmd = new MySqlCommand(query, connector))
    {
        cmd.Parameters.Add(new MySqlParameter("?user", username));
        cmd.Parameters.Add(new MySqlParameter("?pass", password));

        count = int.Parse(cmd.ExecuteScalar().ToString());
    }

    return count;
}

4 Answers 4

4

parameter place holder should not be enclosed with single quotes because it forces it to become a value and not a parameter anymore, try this,

public int MyMethod(string username, string password)
{
    int count = 0;
    string query = "SELECT * FROM accounts WHERE username = @user AND password = @pass LIMIT 1;";

    using (MySqlCommand cmd = new MySqlCommand(query, connector))
    {
        cmd.Parameters.Add(new MySqlParameter("@user", username));
        cmd.Parameters.Add(new MySqlParameter("@pass ", password));

        connector.Open(); // don't forget to open the connection
        count = int.Parse(cmd.ExecuteScalar().ToString());
    }

    return count;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I believe you want to do something like this:

SELECT COUNT(*) FROM accounts WHERE username = '?user' AND password = '?pass';

This will get you the number of records that have the specified username and password.

Comments

1

Try to add parameters like this:

cmd.Parameters.AddWithValue("@user", username);
cmd.Parameters.AddWithValue("@pass", password);

Comments

1

try this: @myVariable instead '?myVariable' , SELECT COUNT(*) instead SELECT *

public int MyMethod(string username, string password)
{
  int count = 0;
  string query = "SELECT count(*) FROM accounts WHERE username = @user AND password = @pass LIMIT 1;";

   using (MySqlCommand cmd = new MySqlCommand(query, connector))
   {
      connector.Open(); 
      cmd.Parameters.AddWithValue("@user", username);
      cmd.Parameters.AddWithValue("@pass", password);       
      count = int.Parse(cmd.ExecuteScalar().ToString());
   }

   return count;
}

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.