开发者

How to parse results from MySQL Table with PHP using row data?

Typically when I make calls into a mysql db, I reference a column for values I need. In this particular instance however, I need to retrieve a set of rows and parse with PHP accordingly. The example is this:

Table format

ID   |   Level
-----------------
1    |    1
2    |    2
3    |    2
4    |    3
5    |    4
6    |    4

I am ultimately trying to retrieve all possible levels and count the number of results by those levels. A simple GROUP BY, COUNT() will do the trick:

'Select Level, Count(*) as counter FROM table GROUP BY Levels ORDER BY Levels ASC'

开发者_开发技巧Which will return:

table_new

Level  | Count
--------------
1     |   1
2     |   2
3     |   1
4     |   2

The problem I face though is when retrieving these results with PHP, I am not quite sure how to set a variable, say 'level1' and set it to the value returned in the count column.

I assume the logic would follow:

while ($row = $stmt->fetch()) {
   $count_level = $row['counter']
}

(but then I would need to create counts for each level type. Any suggestions?


$level = array();
while ($row = $stmt->fetch()) {
   $level[$row['level']] = $row['counter']
}

then you have $level array and $level[1], $level[2] etc variables

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜