Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Parameters not adding values

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;
}
like image 1000
Ben Avatar asked Jul 23 '26 17:07

Ben


2 Answers

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;
}
like image 72
John Woo Avatar answered Jul 26 '26 07:07

John Woo


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.

like image 27
Manuel Avatar answered Jul 26 '26 07:07

Manuel