Session 13: Server-Side, Part 1

Harvard Extension School  
Fall 2020

Course Web Site: https://cscie12.dce.harvard.edu/

Topics

  1. David's Project - Nature of America
  2. Building Pages from Parts: An Introduction to PHP
  3. Web Development
  4. PHP Example with Courses from Database
  5. Querying the Database with SQL
  6. Using "View" templates - Model, View, * (MV*) Design Pattern
  7. {{Mustache}} Templates
  8. Improving the Hello! Greeting

Session 13: Server-Side, Part 1, slide1
David's Project - Nature of America, slide2
Progress, slide3
Building Pages from Parts: An Introduction to PHP, slide4
PHP: Hypertext Processor, slide5
Building a Page from Parts, slide6
Iroquois Constitution, slide7
File Includes with PHP, slide8
Parts that Build the Page, slide9
Recommendation: Keep files well-formed, slide10
Web Development, slide11
Dynamic Content, slide12
Dynamic Content: How does it look?, slide13
Web Program Examples, slide14
A Personal Greeting, slide15
A Personal Greeting, slide16
PHP Example with Courses from Database, slide17
FAS Course Data, slide18
Data Table in a Relational Database, slide19
Querying the Database with SQL, slide20
PHP Script to Connect to Database and Get List of Departments, slide21
Turn this into HTML Output, slide22
The entire "departments-simple.php", slide23
Adding another view - Department Course Listings, slide24
courses.php, slide25
Using "View" templates - Model, View, * (MV*) Design Pattern, slide26
PHP Smarty Templates, slide27
Smarty Template for Courses, slide28
{{Mustache}} Templates, slide29
Mustache Departments, slide30
Mustache Courses, slide31
Improving the Hello! Greeting, slide32
Hello! Greeting, Improved, slide33

Presentation contains 33 slides

David's Project - Nature of America

My project report (in progress): Final Project Report - Nature of America

File Structure

./nature-of-america
|-- scripts/
|-- data/
|   `-- nature-of-america.json
|-- images/
|-- styles/
|-- index.html
|-- map.html
|-- stamps.html
`-- stamps
    |-- alpine_tundra.html
    |-- arctic_tundra.html
    |-- great_lakes_dunes.html
    |-- great_plains_prairie.html
    |-- hawaiian_rain_forest.html
    |-- kelp_forest.html
    |-- longleaf_pine_forest.html
    |-- northeast_deciduous_forest.html
    |-- pacific_coast_rain_forest.html
    |-- pacific_coral_reef.html
    |-- sonoran_desert.html
    `-- southern_florida_wetland.html

Progress

Building Pages from Parts: An Introduction to PHP

Review of HTTP Request/Response

simple http transaction

Pages from Parts

simple http transaction

PHP: Hypertext Processor

From the PHP manual:

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

cgi

PHP Example

hello.php

<?php
$greeting = "Hello, World!";
?>
<html lang="en">
<head><title>Hello</title></head>
<body>
<h1><?php echo($greeting) ?></h1>
</body>
</html>

Building a Page from Parts

PRISE

Why?

Techniques

Iroquois Constitution

Iroquois Constitution (also this demonstrates using JavaScript to make the navigation 'work' with an "iamhere" id.)

Iroquois Constitution Zip File containing HTML, CSS, and "Include" files.

Iroquois ConstitutionIroquois Constitution

File Includes with PHP

Iroquois Constitution

<!DOCTYPE html>
<html>
  <head>
    <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
   <?php include("inc/htmlhead.php"); ?>
  </head>
  <body id="part1">
   <?php include("inc/header.php"); ?>
   <?php include("inc/nav.php"); ?>
    <div id="main">
   <?php include("inc/content1.php"); ?>
    </div>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

Files

|-- 1.php
|-- 10.php
|-- 11.php
|-- 12.php
|-- 13.php
|-- 14.php
|-- 15.php
|-- 16.php
|-- 2.php
|-- 3.php
|-- 4.php
|-- 5.php
|-- 6.php
|-- 7.php
|-- 8.php
|-- 9.php
|-- inc
|   |-- content1.php
|   |-- content10.php
|   |-- content11.php
|   |-- content12.php
|   |-- content13.php
|   |-- content14.php
|   |-- content15.php
|   |-- content16.php
|   |-- content2.php
|   |-- content3.php
|   |-- content4.php
|   |-- content5.php
|   |-- content6.php
|   |-- content7.php
|   |-- content8.php
|   |-- content9.php
|   |-- footer.php
|   |-- header.php
|   |-- htmlhead.php
|   |-- nav.php
|   `-- validate.php
|-- js
|   `-- highlightnavigation.js
`-- style.css

Parts that Build the Page

Iroquois Constitution

Starting File (1.php)

<!DOCTYPE html>
<html>
  <head>
    <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
    <?php include("inc/htmlhead.php"); ?>
  </head>
  <body id="part1">
    <?php include("inc/header.php"); ?>
    <?php include("inc/nav.php"); ?>
    <div id="main">
      <?php include("inc/content1.php"); ?>
    </div>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

HTML Head Content - htmlhead.php

<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="js/highlightnavigation.js"> </script>

Header - header.php

<div id="header"><h1>Constitution of the Iroquois Nations</h1></div>

Navigation - nav.php

<div id="navigation">
<ul id="mainnav">
<li id="navpart1"><a href="1.php">The Great Binding Law, Gayanashagowa</a></li>
<li id="navpart2"><a href="2.php">Rights, Duties and Qualifications of Lords</a></li>
<li id="navpart3"><a href="3.php">Election of Pine Tree Chiefs</a></li>
<li id="navpart4"><a href="4.php">Names, Duties and Rights of War Chiefs</a></li>
<li id="navpart5"><a href="5.php">Clans and Consanguinity</a></li>
<li id="navpart6"><a href="6.php">Official Symbolism</a></li>
<li id="navpart7"><a href="7.php">Laws of Adoption</a></li>
<li id="navpart8"><a href="8.php">Laws of Emigration</a></li>
<li id="navpart9"><a href="9.php">Rights of Foreign Nations</a></li>
<li id="navpart10"><a href="10.php">Rights and Powers of War</a></li>
<li id="navpart11"><a href="11.php">Treason or Secession of a Nation</a></li>
<li id="navpart12"><a href="12.php">Rights of the People of the Five Nations</a></li>
<li id="navpart13"><a href="13.php">Religious Ceremonies Protected</a></li>
<li id="navpart14"><a href="14.php">The Installation Song</a></li>
<li id="navpart15"><a href="15.php">Protection of the House</a></li>
<li id="navpart16"><a href="16.php">Funeral Addresses</a></li>
</ul>
</div>

Footer - footer.php

<div id="footer">
Text form prepared by Gerald Murphy (The Cleveland Free-Net - aa300). Distributed by the Cybercasting Services Division of the National Public Telecomputing Network. Rendered into HTML by <a href="mailto:jon.roland@the-spa.com">Jon Roland</a> of the Constitution Society.  (NPTN). Permission is hereby granted to download, reprint, and/or otherwise redistribute this file, provided appropriate point of origin credit is given to the preparer(s), the National Public Telecomputing Network and the Constitution Society.
<div class="note">
<p>Additional information about the Iroquois nations and their constitution are available:</p>
<ul>
<li><a href="http://www.sixnations.org/">Haudenosaunee:  People Building a Long House</a></li>
<li><a href="http://www.tuscaroras.com/graydeer/influenc/page1.htm">The Influence of the Great Law of Peace on the the United States constitution:  an Haudenosaunee (Iroquois) Perspective</a></li>
<li><a href="http://www.ratical.org/many_worlds/6Nations/index.html">The Six Nations:  Oldest Living Participatory Democracy on Earth</a></li>
<li><a href="http://www.carnegiemuseums.org/cmnh/exhibits/north-south-east-west/iroquois/">The Iroquois nations of the Northeast</a></li>
<li><a href="http://www.iroquoismuseum.org/">Iroquois Indian Museum</a></li>
</ul>
</div>
<p>
  <?php include("validate.php"); ?>
</p>
</div>

Recommendation: Keep files well-formed

Don't do this: Breaking a page in half

This technique is not recommended. The first include file contains the top "half" of the page; the content follows; the second include file contains the bottom "half" of the page. In this technique, the html ,body, and perhaps other elements are started in the "top half" and their end tags are in "bottom half." The page delivered to the browser does validate, but the individual parts on the server are not well-formed, which can cause some confusion when editing a file.

<?php include("header-tophalf.html"); ?>
  Lorem ipsum dolor sit amet, consectetuer adipiscing ...
<?php include("footer-bottomhalf.html"); ?>

ssi

Keeping things well-formed

<!DOCTYPE html>
<html>
  <head>
    <title>Lecture Notes</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="header">
      <?php include("inc/header.php") ?>
    </div>
    <div id="navigation">
      <?php include("inc/nav.php") ?>
    </div>
    <div id="main">
      Lorem ipsum dolor sit amet, consectetuer adipiscing ...
    </div>
  </body>
</html>

Web Development

LanguageFrameworks/Platforms
JavaScript Node, Angular, Backbone, Ember
PHPLaravel, Symfony, CodeIgniter, CakePHP
CMS: WordPress, Drupal, Joomla, Concrete5, GetSimple
PythonDjango, Flask, Zope, Plone
RubyRails

Dynamic Content

Dynamic Content: How does it look?

Web Program Examples

Markup or content is embedded within a program; program embedded into markup

first.pl - Perl

first.pl

#!/usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello, World!</h1></body></html>";

first.py - Python

first.py

#!/usr/bin/python
print "Content-type: text/html\n\n";
print "<html><head><title>Hello World!</title></head>";
print "<body><h1>Hello, World!</h1></body></html>";

first.php - PHP

first.php

<?php
echo('<html><head><title>First PHP</title></head><body>');
echo('<h1>Hello!</h1>');
echo('</body></html>');
?>

second.php - PHP

second.php
program statements within markup

<?php
      $title = "Hello World!";
?>
<!DOCTYPE html>
  <head>
    <meta charset="utf-8" />
    <title><?php echo($title) ?></title>
  </head>
  <body>
    <h1><?php echo($title) ?></h1>
  </body>
</html>

A Personal Greeting

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
    <h1>Hello, <?php echo($name) ?>!</h1>
  </body>
</html>

A Personal Greeting

Without a "name", present the user a form. With a name, provide a greeting.

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Greeting Page</title>
  </head>
  <body>
    <?php
    if ($name) {
      echo("<h1>Hello, $name!</h1>");
    } else {
      echo('<h1><label for="input_name">Enter name:</label></h1>');
      echo('<form method="get">');
      echo('<input type="text" name="name" id="input_name"/>');
      echo('<br /><input type="submit" />');
      echo('<br /><input type="reset" />');
    }
?>
  </body>
</html>
    

PHP Example with Courses from Database

courses

courses

FAS Course Data

Course Data in a Spreadsheet

course data loaded in a spreadsheet

Data Table in a Relational Database

RDBMS = Relational Database Management System

Course Data in RDBMS Table

Course data for Faculty of Arts & Sciences is in a mysql database on cscie12students (username: class; database name: coursecatalog)

SQL:

describe courses

Terminal:

cscie12students$ mysql -u class coursecatalog
Welcome to the MySQL monitor.  Commands end with ; or \g.

mysql> describe courses;
+------------------------------+--------------+------+-----+---------+-------+
| Field                        | Type         | Null | Key | Default | Extra |
+------------------------------+--------------+------+-----+---------+-------+
| acad_year                    | year(4)      | YES  |     | NULL    |       |
| cat_num                      | int(9)       | YES  |     | NULL    |       |
| offered                      | char(1)      | YES  |     | NULL    |       |
| department_code              | varchar(15)  | YES  |     | NULL    |       |
| department_short             | varchar(80)  | YES  |     | NULL    |       |
| department_long              | varchar(200) | YES  |     | NULL    |       |
| course_group_code            | varchar(10)  | YES  |     | NULL    |       |
| course_group_long            | varchar(200) | YES  |     | NULL    |       |
| num_int                      | int(9)       | YES  |     | NULL    |       |
| num_char                     | varchar(15)  | YES  |     | NULL    |       |
| term_pattern_code            | int(5)       | YES  |     | NULL    |       |
| fall_term                    | char(1)      | YES  |     | NULL    |       |
| spring_term                  | char(1)      | YES  |     | NULL    |       |
| term                         | varchar(100) | YES  |     | NULL    |       |
| title                        | text         | YES  |     | NULL    |       |
| course_type                  | varchar(100) | YES  |     | NULL    |       |
| course_level_code            | char(1)      | YES  |     | NULL    |       |
| course_level                 | varchar(200) | YES  |     | NULL    |       |
| credit_code                  | int(5)       | YES  |     | NULL    |       |
| credit                       | varchar(50)  | YES  |     | NULL    |       |
| instructor_approval_required | char(1)      | YES  |     | NULL    |       |
| meeting_time                 | text         | YES  |     | NULL    |       |
| faculty_text                 | text         | YES  |     | NULL    |       |
| description                  | text         | YES  |     | NULL    |       |
| prerequisites                | text         | YES  |     | NULL    |       |
| notes                        | text         | YES  |     | NULL    |       |
+------------------------------+--------------+------+-----+---------+-------+
26 rows in set (0.00 sec)

Querying the Database with SQL

select [field names]
from   [table name]
where  [condition]

Selecting Fields from a Course

SQL Input:

select
    cat_num, department_short, num_int, title, faculty_text
from
    courses
where
    cat_num = 22304
mysql> select cat_num, department_short, num_int, title, faculty_text  from courses where cat_num = 22304 ;
+---------+------------------+---------+--------------------------------------+-------------------------+
| cat_num | department_short | num_int | title                                | faculty_text            |
+---------+------------------+---------+--------------------------------------+-------------------------+
|   22304 | Astronomy        |      17 | Galactic and Extragalactic Astronomy | Daniel James Eisenstein |
+---------+------------------+---------+--------------------------------------+-------------------------+
1 row in set (0.01 sec)

Selecting List of Departments

SQL Input:

select distinct department_code, department_short from courses

Terminal Output:

mysql> SELECT distinct department_code, department_short FROM courses order by department_short ;
+-----------------+----------------------------------------------------------+
| department_code | department_short                                         |
+-----------------+----------------------------------------------------------+
| AAAS            | African and African American Studies                     |
| AMER            | American Studies                                         |
| ANTH            | Anthropology                                             |
| URBP            | Architecture, Landscape Architecture, and Urban Planning |
| ABEA            | Asian Studies Programs                                   |
| ASTR            | Astronomy                                                |
| BSDM            | Biological Sciences in Dental Medicine                   |
| BSPH            | Biological Sciences in Public Health                     |
| BIPH            | Biophysics                                               |
| BIST            | Biostatistics                                            |
| CELT            | Celtic Languages and Literatures                         |
| CHPB            | Chemical and Physical Biology                            |
| CHBI            | Chemical Biology                                         |
| CHEM            | Chemistry and Chemical Biology                           |
| CPLT            | Comparative Literature                                   |
| DRAM            | Dramatic Arts                                            |
| E&PS            | Earth and Planetary Sciences                             |
| EALC            | East Asian Languages and Civilizations                   |
| ECON            | Economics                                                |
| DEAS            | Engineering and Applied Sciences                         |
| ENGH            | English                                                  |
| ESPP            | Environmental Science and Public Policy                  |
| EXPO            | Expository Writing                                       |
| FOLK            | Folklore and Mythology                                   |
| FRSP            | Freshman Seminars                                        |
| GEN ED          | General Education                                        |
| GERM            | Germanic Languages and Literatures                       |
| GLOBHLTH        | Global Health and Health Policy                          |
| GOVM            | Government                                               |
| HPOL            | Health Policy                                            |
| HIST            | History                                                  |
| HLIT            | History and Literature                                   |
| HAA             | History of Art and Architecture                          |
| HSCI            | History of Science                                       |
| HSEM            | House Seminars                                           |
| HEB             | Human Evolutionary Biology                               |
| HUM             | Humanities                                               |
| LSCI            | Life Sciences                                            |
| LING            | Linguistics                                              |
| MATH            | Mathematics                                              |
| MDSC            | Medical Sciences                                         |
| MDST            | Medieval Studies                                         |
| MEST            | Middle Eastern Studies                                   |
| MBB             | Mind, Brain, and Behavior                                |
| MCB             | Molecular and Cellular Biology                           |
| MUSC            | Music                                                    |
| NELC            | Near Eastern Languages and Civilizations                 |
| NEURO           | Neurobiology                                             |
| NODEPT          | No Department                                            |
| BIOE            | Organismic and Evolutionary Biology                      |
| PHIL            | Philosophy                                               |
| PSCI            | Physical Sciences                                        |
| PHYS            | Physics                                                  |
| PSYC            | Psychology                                               |
| RSEA            | Regional Studies - East Asia                             |
| ROML            | Romance Languages and Literatures                        |
| REECA           | Russia, Eastern Europe, and Central Asia                 |
| SLAV            | Slavic Languages and Literatures                         |
| SPOL            | Social Policy                                            |
| SOST            | Social Studies                                           |
| SOCL            | Sociology                                                |
| SAST            | South Asian Studies                                      |
| SPCN            | Special Concentrations                                   |
| STAT            | Statistics                                               |
| SCRB            | Stem Cell and Regenerative Biology                       |
| WMGS            | Studies of Women, Gender, and Sexuality                  |
| SBIO            | Systems Biology                                          |
| CLAS            | The Classics                                             |
| RELG            | The Study of Religion                                    |
| UKRA            | Ukrainian Studies                                        |
| VES             | Visual and Environmental Studies                         |
+-----------------+----------------------------------------------------------+
71 rows in set (0.00 sec)

PHP Script to Connect to Database and Get List of Departments

#!/usr/bin/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);

// iterating through results
while ($row = $result->fetch_assoc()){
  echo $row['department_code'];
  echo "\t";
  echo $row['department_short'];
  echo "\n";
}
?>

Output

Turn this into HTML Output

<?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);

// iterating through results
echo "<ul>\n";
while ($row = $result->fetch_assoc()) {
  echo "<li>";
    echo $row['department_short'];
    echo "</li>\n";
 }
echo "</ul>\n";
?>

The entire "departments-simple.php"

<!DOCTYPE html>
<html>
 <head>
  <title>Departments</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<h2>Departments</h2>

<?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);


// iterating through results
echo "<ul>\n";
while ($row = $result->fetch_assoc()) {
  echo "<li>";
    echo $row['department_short'];
    echo "</li>\n";
 }
echo "</ul>\n";

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

?>

 </body>
</html>

Adding another view - Department Course Listings

Create another PHP file that displays course information based upon a department_code parameter.

Need to link to to courses.php:

Modify the department listing to include the hyperlink:

<!DOCTYPE html>
<html>
 <head>
  <title>Departments</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<h2>Departments</h2>
<?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);

// Printing results in HTML
echo "<ul>\n";
while ($row = $result->fetch_assoc()) {
  echo "<li>";
  echo "<a href=\"courses.php?department_code=$row[department_code]\">$row[department_short]</a>";
  echo "</li>\n";
}
echo "</ul>\n";

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

?>

</body>
</html>

courses.php

<!DOCTYPE html>
<html>
 <head>
  <title>FAS Courses</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<p><a href="departments.php">Return to Department List</a></p>
<h2>Department <?php echo $_GET['department_code'] ?></h2>
<?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;
  }
$dept_code = $_GET['department_code'];
$sqlescaped_dept_code = $mysqli->real_escape_string($dept_code);

// Performing SQL query
$query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
$query .= ' from courses where department_code = ';
$query .= "'".$sqlescaped_dept_code."'";
$query .= ' order by course_group_long, num_int, num_char, title';

$result = $mysqli->query($query);

// Printing results in HTML
     echo "<table cellspacing='0' cellpadding='0'>\n";
$i = 0;
     while ($row = $result->fetch_assoc()) {
       $class = $i++ % 2 ? 'evenrow' : 'oddrow' ;
       echo "\t<tr class='$class'>\n";
       echo "<td class='abbrev'>$row[course_group_long] $row[num_int] $row[num_char]</td>";
       echo "<td class='long'><strong>$row[title]</strong><br/>";
       echo "<span class='faculty'>$row[faculty_text]</span>";
       echo "<p class='description'>$row[description]</p></td>";
       echo "\t</tr>\n";
     }
echo "</table>\n";

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

</body>
</html>

Using "View" templates - Model, View, * (MV*) Design Pattern

Variations: Controller, Presenter, ViewModel, Whatever

MVC

MVC design pattern separates:


You can adopt this design pattern regardless of language or server-architecture. Some frameworks make using MV* possible, some make it easy, some insist on it.

PHP Smarty Templates

smarty

The template (departments.tpl):

<!DOCTYPE html>
<html>
 <head>
  <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>
  {foreach from=$dept item=d}
  <li>
      <a href="smarty-courses.php?department_code={$d.department_code}">{$d.department_short}</a>
  </li>
  {/foreach}
  </ul>
</body>
</html>

Get the departments: smarty-dept.php

<?php
/* ==================================================
    Database Stuff
   ================================================== */
/// 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;
}

/* ==================================================
    Smarty Template Stuff
   ================================================== */
   require('/usr/local/lib/php/Smarty/Smarty.class.php');

   // create object
   $smarty = new Smarty;

   $smarty->template_dir = './smarty_templates';
   $smarty->compile_dir = '/tmp/smarty/templates_c';
   $smarty->cache_dir = '/tmp/smarty/cache';
   $smarty->config_dir = './smarty_configs';


   // assign some content. This would typically come from
   // a database or other source, but we'll use static
   // values for the purpose of this example.
   $smarty->assign('dept', $results);

   // display it
   $smarty->display('departments.tpl');

/* ==================================================
    Cleanup
   ================================================== */
   // free and close
  $result->free();
  $mysqli->close();
?> 

Smarty Template for Courses

smarty

The template (courses.tpl):

<!DOCTYPE html>
<html>
 <head>
  <title>Departments</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<p><a href="smarty-dept.php">Return to Department List</a></p>
<h2>Department {$department_code}</h2>
<table cellspacing="0" cellpadding="0">
{foreach from=$courses item=course name=courses}
<tr class="{cycle values="row1,row2,row3,row4"}">
<td class="abbrev">{$course.course_group_long} {$course.num_int}{$course.num_char}</td>
<td class="long">
  <strong>{$course.title}</strong><br/>
  <span class="faculty">{$course.faculty_text}</span>
  <p class="description">
    {$course.description}
  </p>
</td>
</tr>
{/foreach}
</table>
</body>
</html>

Get the Courses for the CHEM department: smarty-courses.php?department_code=CHEM

The SQL:

SELECT course_group_long,
              num_int, num_char, term,
              title, description 

smarty-course.php:

<?php
/* ==================================================
    Database Stuff
   ================================================== */
   // 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;
     }
   $dept_code = $_GET['department_code'];
   $sqlescaped_dept_code = $mysqli->real_escape_string($dept_code);

   // Performing SQL query
   $query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
   $query .= ' from courses where department_code = ';
   $query .= "'".$sqlescaped_dept_code."'";
   $query .= ' order by course_group_long, num_int, num_char, title';

   $result = $mysqli->query($query);

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


/* ==================================================
    Smarty Template Stuff
   ================================================== */
   require('/usr/local/lib/php/Smarty/Smarty.class.php');

   // create object
   $smarty = new Smarty;
   // pass the results to the template
   $smarty->assign('courses', $results);
   $smarty->assign('department_code', $_GET['department_code']);

   $smarty->template_dir = './smarty_templates';
   $smarty->compile_dir = '/tmp/smarty/templates_c';
   $smarty->cache_dir = '/tmp/smarty/cache';
   $smarty->config_dir = './smarty_configs';

   // assign some content. This would typically come from
   // a database or other source, but we'll use static
   // values for the purpose of this example.
   $smarty->assign('dept', $results);

   // display it
   $smarty->display('courses.tpl');

/* ==================================================
    Cleanup
   ================================================== */
   // Free resultset
   $result->free();

   // Closing connection
   $mysql->close();
?> 

{{Mustache}} Templates

{{mustache}} is another widely used template system for JavaScript (and other languages!).

mustache

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> 

Mustache Courses

<!DOCTYPE html>
<html>
 <head>
  <title>Courses: {{department_name}}</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<p><a href="mustache-dept.php">Return to Department List</a></p>
<h2>{{department_name}}</h2>
<table cellspacing="0" cellpadding="0">
{{#courses}}
  <tr>
  <td class="abbrev">{{course_group_long}} {{num_int}}{{num_char}}</td>
  <td class="long">
    <strong>{{title}}</strong>
    <br/>
    <span class="faculty">{{faculty_text}}</span>
    <p class="description">
      {{description}}
    </p>
  </td>
  </tr>
{{/courses}}
</table>
</body>
</html>

Improving the Hello! Greeting

We started with

Without a "name", present the user a form. With a name, provide a greeting.

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
    <?php
      if ($name) {
        echo("<h1>Hello, $name!</h1>");
      } else {
        echo('<h1><label for="input_name">Enter name:</label></h1>');
        echo('<form method="get">');
        echo('<input type="text" name="name" id="input_name"/>');
        echo('<br /><input type="submit" />');
        echo('<br /><input type="reset" />');
      }
    ?>
  </body>
</html>

Hello! Greeting, Improved

Three files: one code; two templates

index.php

<?php
$name = $_GET["name"];

// figure out which template is needed
if ($name) {
  $template_file = 'greeting.html';
} else {
  $template_file = 'form.html';
}
$template_contents = file_get_contents($template_file);
$template_data['name'] = $name;

// Process with Mustache Template
include('lib/Mustache.php');
$m = new Mustache;

echo $m->render($template_contents, $template_data);

?>

greeting.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page for {{name}}</title>
  </head>
  <body>
      <h1>Hello, {{name}}!</h1>
  </body>
</html>

form.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
      <h1><label for="input_name">Enter name:</label></h1>
      <form method="get">
      <input type="text" name="name" id="input_name"/>
      <br /><input type="submit" />
      <br /><input type="reset" />
  </body>
</html>