Robbob
Robbob

Reputation: 5

Count how many times a value appears in sql query using php

I have created a database and website that will be used by football managers to select their team etc. Once a match has been completed events will be stored in the match_players table. Such events are Goal, Yellow Card, Red Card etc. I have no problem getting this information into php from SQL db.

I need to add up how many times a Goal appears (a '1' is placed in the SQL table) and for what team so that a final score can be displayed. So, for example, if Team A has 1 goal and Team B has 2 then I need to display that. I am trying to count the amount of times that a Goal is registered in the table. Any help will be greatly appreciated.

Upvotes: 0

Views: 5349

Answers (3)

Husman
Husman

Reputation: 6909

Well if you store a 1 each time a goal is scored, your table looks like this:

TeamID  goal
   1     1
   2     1
   1     1
   3     1
   2     1
   2     1
   1     1

So you just want a count of how many times a team appears in that table:

select TeamID, count(*) from table group by TeamID

Will give you

 TeamID | count(*)
     1  |  3
     2  |  3
     3  |  1

Upvotes: 0

DonCallisto
DonCallisto

Reputation: 29912

Why don't you demand this sum to SQL directly?

SELECT SUM(goals)
FROM match_table
WHERE team = 'Barcellona'

This should be much faster also than elaborate all data at "php-level"

If you want this detail for all teams

SELECT team,SUM(goals)
FROM match_table
GROUP BY team

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

You can use MYSQL SUM

select SUM(Goal) from match_players where Team="A"

Or you can get the same for all teams by

select Team,SUM(Goal) from match_players group by Team

Upvotes: 1

Related Questions