Mustache Departments
Mustache Template
PHP
<?php
// use Dotenv to load database info from .env file
// DB_HOST, DB_USER, DB_PW, DB_NAME
// host, user, password, database name
require_once('vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();
// Connecting, selecting database
$mysqli = new mysqli($_ENV['DB_HOST'],$_ENV['DB_USER'],$_ENV['DB_PW'],$_ENV['DB_NAME']);
if ($mysqli->connect_errno) {
echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
}
// Performing SQL query
$query = <<<ENDQUERY
SELECT DISTINCT
department,
department_code
FROM ext_courses
ORDER BY department
ENDQUERY;
$result = $mysqli->query($query);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$template_data['departments'] = $rows;
// 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);
// cleanup query result and close connection
$mysqli->close();
?>
Mustache Template
mustache_templates/departments.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Harvard Extension School - Departments</title>
<link rel="stylesheet" href="styles/site.css" />
</head>
<body>
<h1>Harvard Extension School</h1>
<h2>Departments</h2>
<ul>
{{#departments}}
<li>
<a href="mustache-courses.php?department_code={{department_code}}">{{department}}</a>
</li>
{{/departments}}
</ul>
<footer>
<p><a href="./">PHP/mysql example list</a></p>
<p>This is a learning example to demonstrate PHP and mysql for the courses CSCI E-12 and CSCI S-12 taught by David
Heitmeyer. <br />
The real <a href="https://courses.dce.harvard.edu/">Harvard Extension School course search</a> is at: <a
href="https://courses.dce.harvard.edu/">courses.dce.harvard.edu</a>
</p>
</footer>
</body>
</html>