简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM