Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Spring 2020

## Mustache Departments

### Mustache Template

mustache-dept.php

### PHP

    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    $i=0;
    while ($row = $result->fetch_assoc()) {
      $results[$i++] = $row;
    }

    $template_data['departments'] = $results;

    // Process with Mustache Template
    include('lib/Mustache.php');

    $m = new Mustache;
    $template_file = 'mustache_templates/departments.html';
    $template_contents = file_get_contents($template_file);
    echo $m->render($template_contents, $template_data);

    // Free resultset and close connection
    $result->free();
    $mysqli->close();
    ?>

### Mustache Template

mustache_templates/departments.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Departments</title>
        <link rel="stylesheet" href="site.css" type="text/css"/>
      </head>
      <body>
       <h1>Faculty of Arts &amp; Sciences</h1>
       <h2>Departments</h2>
    <ul>
    {{#departments}}
         <li>
           <a href="mustache-courses.php?department_code={{department_code}}">{{department_short}}</a>
         </li>
    {{/departments}}
    </ul>
      </body>
    </html>

Copyright © David Heitmeyer