Zack Tanner
Zack Tanner

Reputation: 2590

Dynamic Table Issue

I'm trying to create a table, with data represented like so:

Skills   | Project #1 | Project #2 | Project #3
Skill #1    Grade         Grade        Grade
Skill #2    Grade         Grade        Grade

Essentially, the columns that begin with Project are dynamic, and grabbed through an SQL query and stored in an array.

The skills are also dynamic and stored in arrays. And then the grades for each skill should reflect the grade received for the project it is in.

All of this data is available in the DB. I can grab the skill, project, and grade in one query.

I'm trying to figure out how to make this work. Right now, I can only figure out how to get the skills and projects to show. I have no idea how to make them match up with the appropriate grade, though. Here's what I have

         $sql = "select skills.name as skillName, projects.name, projects_assessments.assessment  from skills
              INNER JOIN projects_assessments
              ON skills.id = projects_assessments.skillID
              INNER JOIN projects
              ON projects_assessments.projectID = projects.id
              WHERE projects_assessments.studentID = '{student}'
              AND skills.teacher = '{teacher}'";
        $result = mysql_query($sql) or die (mysql_error());
        while($row=mysql_fetch_array($result)) {
            $projects[] = $row['name'];
            $skills[] = $row['skillName'];
        }
        echo "<table><tr><th>Skill</th>";
        $projects = array_unique($projects);
        foreach($projects as $project) {
            echo "<th>$project</th>";
        }
        echo "
        </tr>";
        foreach($skills as $skill) {
            echo "<tr><td>$skill</td></tr>";
        }
        echo "
        </table>

This returns:

    Skills   | Project #1 | Project #2 | Project #3
   Skill #1                   
   Skill #2                  

Essentially what I need now is to match the grade for each skill. That data is stored in $row['assessment'].

Thanks for any help!

Upvotes: 1

Views: 78

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

Just build the table in a two-dimensional array:

$table = array();
while ($row = mysql_fetch_array($result)) {
    $table[$row['skillName']][$row['name']] = $row['assessment'];
}

$firstRow = current($table);
// draw columns based on $firstRow

foreach ($table as $skillName => $projectList) {
    // start row
    foreach ($projectList as $assessment) {
        // start column with $assessment as value
    }
}

Important

Make sure to order the rows properly:

ORDER BY skillName, name;

Upvotes: 1

Related Questions