Page 1 of 1

how to display query results using php in a html table

Posted: Tue Apr 12, 2016 3:59 am
by maxelcat
Hi - I am really stuck on what I am sure is a simple question!

I have to create a table of results for school children. It has a number of sets of grades that are called assessblock_id - which correspond to different times of the year.

------------------------------
subject | Nov | Jan| Mar|
Speaking | P2ic| P9a | H1b
Listening | P3 | H1 | H3
etc

I query the database which retuns arrays like this:

Code: Select all

Array ( [assessment_id] => 47 [pupil_id] => 288 [assessblock_id] => 13 [Speaking] => P2ic [Listening] => P2ib...
If there was only one column of results it would be dead easy.

Code: Select all

$query1 = "SELECT * FROM assessments WHERE pupil_id=288 AND assessblock_id='15'";
$result = $conn->query($query1);
    if ($result->num_rows > 0) {

        ?>
        <table border="1" cellspacing="0" cellpadding="0">
            <tr><th>Subject</th><th>grade</th></tr>
    <?php 
        while($row = $result->fetch_assoc()) {
            foreach ($subjectListArray as $subject){
                 $sub = str_replace(" ", "_", $subject);
                 echo '<tr><td>'.$subject.'</td><td>'.$row[$sub].'</tr>';
            }
        }// endwhile
        echo '</table>';
    }//endif
Which produces two columns.

If the names of the subjects wnet along the top rather than down the side I think icould do it.

Please, How can I add in extra columns given that i get one set of results ($row) at a time and they have to go down.

I'd really appreciate any help / pointers on who to do this.

Re: how to display query results using php in a html table

Posted: Tue Apr 12, 2016 4:32 pm
by Christopher
You might want to fill in a two dimensional array that uses Speaking, Listening, ... as keys for the main array, and Jan, Feb, Mar as keys for each sub-array. Then generate the output from that array. That would also let you separate your Model code from the Presentation code generating the HTML.