tanzilamohita tanzilamohita - 1 month ago 10
MySQL Question

How to get num of rows in php for a particular value

enter image description hereIn my database table, there are many students from different classes. I want to get the number of students in each class in a table. How can I get this and insert into a table? Here is my code:

<?php

function showSearchResult()
{
require_once('config.php');
connect_db();
$class = '';
$result = mysql_query("SELECT * FROM ipsc_student WHERE class=2");
$num_rows = mysql_num_rows($result);
$rt = "";
$rt.="<div align='center'>
<h1>Report IPSC</h1>
</div>";
$rt.= "<table width='1000' align='center' border= '1'>";
$rt.= "<tr><td><b>SL</b></td>
<td><b>Class</b></td>
<td><b>Total Student</b></td>
</tr>";
for($i =1; $i < 13; $i++){
$rt.="<tr>";
$rt.="<td>$i.</td>";
$rt.="<td>$i</td>";
$rt.="<td>$num_rows</td>";
$rt.="</tr>";
}
echo $rt;
}
showSearchResult();
?>

Answer

You can do group by class on your student table

SELECT `class`, COUNT(`student`) AS total_student FROM `ipsc_student` GROUP BY `class`
Comments