Reputation: 93
There are many students in my table with different classes. I want to print different class one time and print the number of students of that class. I can print the class. But couldn't print the number of students for each class. How can I do this? For example:
In my database: Desired Output:
Class Name Class Num. of Students
2 John 1 2
2 Snow 2 3
3 Jara 3 1
1 Peter
1 Nira
2 Jerin
Here is my code:
$q = "SELECT * FROM ipsc_student group by class";
$rs = mysql_query($q);
$numOfRows=mysql_num_rows($rs);
$rt = "";
$sl = 0;
while($row=mysql_fetch_assoc($rs)){
$sl++;
$rt.="<tr>";
$rt.="<td>$sl</td>";
$rt.="<td>".$row['class']."</td>";
$rt.="<td>$numOfRows</td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="</tr>";
}
echo $rt;
Upvotes: 1
Views: 451
Reputation: 334
Try this
$q = "SELECT class, count(*) as NUM FROM ipsc_student GROUP BY class";
$rs = mysql_query($q);
$numOfRows=mysql_num_rows($rs);
$rt = "";
$sl = 0;
while($row=mysql_fetch_assoc($rs)){
$sl++;
$rt.="<tr>";
$rt.="<td>$sl</td>";
$rt.="<td>".$row['class']."</td>";
$rt.="<td>".$row['NUM']."</td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="<td></td>";
$rt.="</tr>";
}
echo $rt;
Upvotes: 1