superUntitled
superUntitled

Reputation: 22527

php: count number of times a string appears in an mySql array

* edit * I asked this question as a php question, without the tag of mySql (which has been added by another SO member --> not a big deal to me, but just saying). I am sorry for any confusion the inclusion of the ?extraneous? detail that the array was from a mySql query!

I am hoping to keep the queried data from the SELECT * to loop through using PHP in an array. I thought, in order to keep this code simple, that PHP could count the number of times a string occurs in a particular position in an array. * /edit *

I would like to find out how many times a string appears in a particular column from a mySql query result.

For example, lets say I have a table 'automobiles' and their is a column 'type' in that table. The column 'type' has values such as 'sedan', 'van', 'suv' etc.

If I query everything from the table like this:

$query = "SELECT *
            FROM automobiles";

and then insert the queried values into an array:

$the_array = mysql_fetch_array($query);

and then try to quantify the number of times a string occurs like this:

$count = array_count_values($the_array);
print_r($count);

not only does this not work, but the data would be inaccurate because the values would be based on the entire table, not on the automobile 'type' column alone.

Upvotes: 0

Views: 2200

Answers (3)

rackemup420
rackemup420

Reputation: 1567

or you can go

$query = ("SELECT * FROM automobiles WHERE type='TYPE'");
$total_count = mysql_num_rows($query);
echo $total_count;

Upvotes: 0

sagi
sagi

Reputation: 5737

You can do this with a simple SQL aggregation:

SELECT type, COUNT(*) FROM automobiles GROUP BY type

Upvotes: 1

ceejayoz
ceejayoz

Reputation: 180004

$query = "SELECT `type`, COUNT(*) `count` FROM `automobiles` GROUP BY `type`";

Upvotes: 5

Related Questions