1
Connection c = new Connection();
public string checkIfExists(string Name)
    {
        string sql = "SELECT * FROM users WHERE name = '" + name + "'";
        c.Execute(sql);

        return "";
    }

The c.Execute(sql) is calling a SqlCommand function to execute the sql query.

I want to know how to count the number of rows retrieved by this query.

Ignore the return.

Rafael Duarte
  • 569
  • 6
  • 21
  • 5
    You have a SQL injection vulerability. – SLaks May 18 '17 at 16:40
  • Possible duplicate of [Capturing count from an SQL query](https://stackoverflow.com/questions/4668911/capturing-count-from-an-sql-query) – Burgi Dec 05 '17 at 18:33

2 Answers2

9
  1. Make sure your SQL is protected from SQL injection attack by parameterizing it
  2. Rewrite SQL to return COUNT
  3. Use ExecuteScalar to retrieve the answer

The query should look like this:

var sql = "SELECT COUNT(*) FROM users WHERE name = @Name";
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • since the name of his method is checkIfExists, it would probably be better to just grab the indexed key and call `.HasRows`. It would be a little faster and clearly define what he wants (assuming what he says he wants doesn't actually match his method name, since it doesn't return a bool either). – Dispersia May 18 '17 at 17:07
  • 1
    @Dispersia That is certainly true. I wanted OP to concentrate on the basics, though, so that he could eliminate a critical vulnerability and get an answer to his query first, and worry about the performance later. Good chances are, he'll find performance of this solution acceptable, and wouldn't worry about optimizing it any further. – Sergey Kalinichenko May 18 '17 at 17:17
  • 1
    This is true, was just food for thought more for the OP, since his method naming and return types don't even really match up :) – Dispersia May 18 '17 at 17:27
  • The @Name will get the name variable received in the method or do I have to create a parameter? – Rafael Duarte May 19 '17 at 10:00
  • @RafaelDuarte You need to create a parameter, and set its value to method's parameter `Name` (C# naming conventions suggest lower case for `n` in `name`). Follow the first link in the answer for info on how to work with parameters. There's more than one way; different answers from that linked Q&A show code examples. – Sergey Kalinichenko May 19 '17 at 10:14
3

Here is Sam SQL query:

SELECT COUNT(1) FROM nazvaniyami
SQL query with condition:

SELECT COUNT(1) FROM nazvaniyami WHERE condition
Implementation in PHP:

$a = mysql_query("SELECT COUNT(1) FROM navaneetham");
$b = mysql_fetch_array( $a );
echo $b[0]; // prints the number of rows

Likewise, it is possible to add a condition. Then the code prints the number of rows in the table satisfying the condition. Thank you for your attention, with you was Maxim

Maks Orlov
  • 31
  • 4