Sort the result set by the grouping field, remember the previous value, and print the name only when it changes. This is a presentation rule, so all database rows are still available to the page.
<?php
$stmt = $pdo->query(
'SELECT name, subject, mark FROM student_mark ORDER BY name, subject'
);
$previousName = null;
foreach ($stmt as $row) {
$name = $row['name'] === $previousName ? '—' : $row['name'];
echo '<tr>';
echo '<td>' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . htmlspecialchars($row['subject'], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . (int) $row['mark'] . '</td>';
echo '</tr>';
$previousName = $row['name'];
}
?>
mysql_query()/mysql_fetch_array() API. Keep it only for understanding older code; use PDO or MySQLi for current PHP.$q=mysql_query("select * from student_mark order by name ");
$name="";
echo "<table width='200' border='0' cellspacing='1' cellpadding='0'>";
while($nt=mysql_fetch_array($q)){
if($name<>$nt['name']){
echo "<tr ><td> $nt[name]</td><td>$nt[subject]</td><td> $nt[mark] </td></tr>";
}else{
echo "<tr ><td> ------</td><td>$nt[subject]</td><td> $nt[mark] </td></tr>";
}
$name=$nt['name'];
}
echo "</table>";
Download the full script for displaying recordsAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Suranga Bandara | 14-08-2015 |
| $sql = mysql_query("SELECT DISTINCT table1.id, table2.id, table2.name FROM table1, table2 WHERE id=id GROUP BY name"); Use `DISTINCT` and `GROUP BY name`.. If not every time repeat data. Cheers !!! | |