0

I have this code for getting how many results there are in results there are in a column:

$result = "SELECT name FROM users";

echo $result;

How can I display a certain number of a specific string? For example, I want to search for the name "Andrew" in the column "name". There are 20 results for "Andrew". How can I echo out "20"?

1
  • I didn't do the downvoting but, as a heads up, I'm sure the person did it because this is a very "Google-able" question. Googling "count results in sql" would have returned you the answer, quite possibly even linking to a question already posted on SO. Commented Apr 2, 2015 at 20:39

2 Answers 2

2

You would COUNT them:

$result = "SELECT COUNT(`name`) AS `NameCount` FROM `users` WHERE `name` = 'Andrew'";

For all names you could do this:

SELECT `name`, count(`name`) AS `NameCount`
FROM `users`
GROUP BY `name`

Which would result in something like this:

name    |    NameCount
----------------------
Andrew  |           20
Bob     |            6
Carol   |          125
Sign up to request clarification or add additional context in comments.

Comments

0

If you will use Mysqli, you can use $num_rows. Somelithing like:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

also, you can use mysql count() function like:

$result = "SELECT count(*), name FROM users";

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.