Jaky Jaky - 2 months ago 6
MySQL Question

How to display data from MySQL

So today i created a script of Online Time Table and it's working fine and user or me can add new time-table row by using some data and my end result is like.

This is my sql query (Please don't warn me to use MySQLi or PDO, i know about them too, but this is a private application and i can write unsafe codes thought.)

$date = date("d/m/y");
$sql = "SELECT * FROM `s_timetable` WHERE `date` = '$date'";
$res = mysql_query($sql) or die(mysql_error());

while ($fetch_data = mysql_fetch_array($res)) {
echo "<tr>";
echo "<td>" .$fetch_data['batch_info']. "</td>";
echo "<td>" .$fetch_data['class_info']. "</td>";
echo "<td>" .$fetch_data['subject_info']. "</td>";
echo "<td>" .$fetch_data['teacher_info']. "</td>";
echo "</tr>";
}
?>


but after querying this to database, I got lots of results with same value, how can i show them as group.

Example:
LDC batch
-
08:09
-
science
-
Ashok B.


LDC batch
-
09-10
-
English
-
Jaky


LDC batch
-
10-11
-
Maths
-
Bella



Now how i can display these data as table, with title of
LDC batch
as that repeat in all and then
time
subject
and
teacher
info with table bosy

Answer

One option here is to present a 3 column HTML table containing the time, subject, and teacher data for each batch. When the batch type changes in the result set, a new row can be printed as a header.

$header = "";
while ($fetch_data = mysql_fetch_array($res)) {
    if ($header = "" || $header != $fetch_data['batch_info']) {
        echo "<tr><td colspan=\"3\">".$fetch_data['batch_info']."</td></tr>";
        $header = $fetch_data['batch_info'];
    }
    echo "<tr>";
    echo "<td>" .$fetch_data['class_info']. "</td>";
    echo "<td>" .$fetch_data['subject_info']. "</td>";
    echo "<td>" .$fetch_data['teacher_info'].  "</td>";
    echo "</tr>";
 }

Update:

As @apokryfos pointed out, you should order your result set by the batch_info column to ensure that records belonging to the same batch are always adjacent. So your query might become:

SELECT *
FROM s_timetable
WHERE date = '$date'
ORDER BY batch_info