The official name of the module is Construction and Databases. It is part of the Interaction subject matter area in the Multimedia Design and Communications programme. This module is read in the 3rd semester.
The module has an extent of 10 ECTS-points. A full work year, normally considered to be 1680 work hours corresponds to 60 ECTS. In other words this module will demand your attention for approximately 280 hours. Hours, not lessons. Only 67.5 of those hours are scheduled as lessons, including projects. The rest is your responsible homework!
The obligatory prerequisite for participating is completion of the first two semesters of the programme.
The module participates in a lottery about being part of a viva, an oral exam based on 48 hours synopsis work. This means that about one quarter of you will face a viva in this subject.
The first thing on the agenda will be placing the technology of databases on the architectural map of your programme, ie of the world wide web. Take a look at the client/server-model at Appendix A, The Client/Server Model. With respect to the less theoretically inclined among you, I have decided to do this module as a two track course. There will be a practical track and a theoretical track in parallell. The flip side of this decision is that we are scheduled for many sessions of only two lessons in stead of the habitual 4 that we mostly use. The will be exceptions, though.
This implies that you in the practical track will be facing subject and things that you will only later face theoretically. This is called abstraction, and experience tells me that you can do it.
This introduction is incidentally also an Introduction to the concept of a Content Mangement System also known as CMS, and therefor arguably most useful for your future careers.
A development project for a web based site, system or whatever you may call it, always starts with some kind of request, requirements from a client. This is by pure mindwork, no computer necessary. This semantic work produces a model of the information involved. We use a tool called Entity-Relationship modelling for this. It may look as follows:
The ER Model is purely semantic. We need to transform it into something logical, that may be understood by a computer. For this we use the Relational Model. Is has a language in which we express operations. This language is SQL, Structured Query Language, it translates the ER Modelling entities and relationships into tables with the attributes found in the ER model. It looks as follows:
drop database cms0;
create database cms0;
use cms0;
create table root (
id int not null primary key auto_increment,
name varchar(32) not null,
slogan varchar(64) not null
) engine=innodb;
create table image (
id int not null primary key auto_increment,
filename varchar(32) not null,
caption varchar(64) not null
) engine=innodb;
create table usesaslogo (
rid int not null,
iid int not null,
primary key(rid),
unique(iid),
foreign key(rid) references root(id),
foreign key(iid) references image(id)
) engine=innodb;
create table page (
id int not null auto_increment,
linktext varchar(16) not null,
headline varchar(32) not null,
content blob not null,
rid int not null,
primary key(id),
foreign key(rid) references root(id)
) engine=innodb;
create table uses (
pid int not null,
iid int not null,
primary key(pid,iid),
foreign key(pid) references page(id),
foreign key(iid) references image(id)
) engine=innodb;
create table navi (
fraid int not null,
tilid int not null,
sort int not null,
type char(1) not null,
primary key(fraid,tilid),
foreign key(fraid) references page(id),
foreign key(tilid) references page(id)
) engine=innodb;
The final step into the computer, the transformation into a physical database is done by letting an SQL interpretor, a part of an RDBMD, read and interpet the SQL. Having the physical manifestation of the database we have an empty structure. We still need one useful ingredient in order to call it a database. We need data. Data is brought into the database by another part of SQL used for data manipulation. An example corresponding with the diagram, and the data structure:
insert into root (name, slogan) values('Muller''s Magic Manipulation', 'We Work Wonders');
insert into image (filename, caption) values ('mmmlogo.gif', 'Logo');
insert into image (filename, caption) values ('mmmlogo1.png', 'Logo');
insert into usesaslogo values(1,1);
insert into page (rid,linktext,headline,content) values(1, 'Home', 'The Story of the Logo', 'Cras facilisis justo ac nisi dignissim dapibus. Curabitur nec erat sem. Donec lectus magna, ullamcorper vel ullamcorper vitae, scelerisque vel nulla. Nam vel lorem sem. Donec cursus euismod nisi, sit amet scelerisque nulla varius eu. Integer massa leo, fermentum sed blandit euismod, rhoncus at elit. Nunc eu odio elit. Nam fringilla ullamcorper mauris, eget varius magna imperdiet nec. In hac habitasse platea dictumst. Aliquam erat volutpat. Aliquam id diam tellus, sed auctor turpis. Mauris mi eros, cursus vel aliquam ornare, suscipit vitae libero. Phasellus fermentum ultrices dapibus. Suspendisse est ipsum, varius eget scelerisque at, auctor eget elit.');
insert into page (rid,linktext,headline,content) values(1, 'Sales', 'MMM Sales', 'We horse around piching snake oil hither and dither');
insert into page (rid,linktext,headline,content) values(1, 'Accounting', 'MMM Admin', 'The department for creative book keeping, It has a stated target of avoiding taxes and other PITA formalia, aka red tape. Internally WE ARE the red tape.');
insert into page (rid,linktext,headline,content) values(1, 'Secret', 'MMM ?', 'If anyone knows what we do it''s Dogbert, ask him');
insert into page (rid,linktext,headline,content) values(1, 'Secret1', 'The Answer','42');
insert into navi values(1, 2, 10, 'A');
insert into navi values(1, 3, 90, 'A');
insert into navi values(1, 4, 20, 'A');
insert into navi values(2, 5, 40, 'B');
It is magic! This magic, and the logics behind it, you will learn in this semester.
I promised you CMS, and I almost forgot. Therefore "One more thing."
A Content Management System is a bundle of programs manging the content, and display of your data. The data you have so far been to write directly into html files, are now removed from html files and put into a database. Every time someone requests a page, a PHP program fetches the content from the database, and builds the page for the user to see.
An example to illustrate:
Example 1. A CMS Display Program. File: index.php
<?php
include "myDbFuncs.inc.php";
$page = 1;
$site = 1;
if (isset ($_GET['site']))
$site = $_GET['site'];
if (isset ($_GET['page']))
$page = $_GET['page'];
$sql = "";
$sql .= "select root.id, name, slogan, filename, headline, content";
$sql .= " from root";
$sql .= " left outer join usesaslogo";
$sql .= " on rid = root.id";
$sql .= " left outer join image";
$sql .= " on image.id = iid";
$sql .= " left outer join page";
$sql .= " on page.id = " . $page;
$sql .= " and page.rid = root.id";
$sql .= " where";
$sql .= " root.id = " . $site;
$res = myQuery($sql);
$obj = mysql_fetch_object($res); // assigns column names as object vars
$sql = ""; // read links
$sql .= "select fraid, tilid, linktext";
$sql .= " from navi";
$sql .= " join page";
$sql .= " on page.id = tilid";
$sql .= " where type = 'A'";
$sql .= " and rid = " . $site;
$sql .= " order by sort;";
$nav = myQuery($sql);
$title = "PHP Workshop Case - " . $obj->slogan;
include "xhtmlTop.inc.php";
?>
<link rel="stylesheet" type="text/css" href="phpWorkshop.css"/>
<?php
include "xhtmlNeck.inc.php";
print("<div id='body'>\n");
printf("<div id='logo'><img src='%s' alt='%s'/></div>\n",
$obj->filename, $obj->slogan);
printf("<div id='name'><h1>%s</h1></div>\n", $obj->name);
print("<div id='nav'>\n<ul>");
while ($navobj = mysql_fetch_object($nav)) {
printf("<li><a href='%s?site=%s&page=%s'>%s</a></li>\n",
$_SERVER['PHP_SELF'], $site, $navobj->tilid, $navobj->linktext);
} // print the link
print("<li><a href='./login.php'>Admin login</a></li>\n");
print("<li><a href='./logout.php'>Logoff</a></li>\n");
print("</ul>\n</div>\n"); // end list and nav
printf("<div id='content'>\n<h2>%s</h2>\n<p>%s</p>\n</div>\n",
$obj->headline, $obj->content);
print("</div>\n"); // end wrapper
include "xhtmlFoot.inc.php";
?>
Example 2. Local Params, Specific for Database. File: myDbParms.inc.php
<?php $host = "localhost"; $user = "nobody"; $password = "test"; $database = "cms0"; ?>
Example 3. General Functions, General. File: myDbFuncs.inc.php
<?php
include "myDbParms.inc.php";
function myConnect($host, $user, $password, $database) {
try {
if (! $dbConnection = mysql_connect($host, $user, $password))
throw new Exception("Ingen forbindelse opnået til MySQL-server.");
if (! mysql_select_db($database, $dbConnection))
throw new Exception("Ingen forbindelse opnået til MySQL-databasen.");
}
catch (Exception $e) {
die($e->getMessage());
}
return $dbConnection;
}
function myQuery($query) {
try {
if (! $result = mysql_query($query))
throw new Exception("Database query failed!<br />".$query);
}
catch (Exception $e) {
die($e->getMessage());
}
return $result;
}
$dbh = myConnect($host, $user, $password, $database);
?>
http://localhost/deformation.org/mdu/code/PHPWorkshopDb/index.php?site=1&page=1 . This link is for the teachers demonstration purposes only. Get the stylesheet here. It is useless to try it from your internet connection. It should start out with something similar to:
Practically we shall work with PHP and the database programming language SQL. The paedagogical abstraction I have mentioned means that you will use SQL before you really know it in any detail. First we will use the PHP/SQL combination on a sample database we will fetch quite legally from the MySQL website.
We will check the validity of the download and installation by means of SQL. Upon that done succesfully we will do some recap of pure PHP, and finally move on to the combination of the two.
The necessary prerequisites for all this you will find in Appendix B, Setting Up 3 Tier Client Server Environment
While installing the RDBMS we saw in the section called “Daily use of MySQL”, that we must connect to the server before we can read a database. Quite the parallel to opening a text file before you can read it. We must do the same if we wish to access the database through a PHP-program.
For this particular purpose, I shall now give you a present, two PHP include files that you from now on will be able to use in all php database programs using MySQL. You will find them at the bottom of this section.
The first include file is pretty straight forward. It defines and assigns some values to some variables. No new PHP in that, if you remember what a variable is. The second include file defines a function that performs a connect to a database. After defineing the function it is executed. The result on successful execution is that we have an open database. This process is an exact replica of an open of a text file, something that you practised in your 2nd semester.
Practically speaking this means that as of now this include file must be in all PHP programs accessing databases. See how in the section called “Assignment 0.0”. The only thing that will vary from one program to the next will be the concrete name of the database. Unless you work with the same database all thee time. This name is held in the first include file.
Now please read the following two includes, you have seen them before, they are omnipotent, you will need them again and again. Having studied them, do the section called “Assignment 0.0”, which you will find at the end of the lesson.
<?php $host = "localhost"; $user = "nobody"; $password = "test"; $database = "cms0"; ?>
<?php
include "myDbParms.inc.php";
function myConnect($host, $user, $password, $database) {
try {
if (! $dbConnection = mysql_connect($host, $user, $password))
throw new Exception("Ingen forbindelse opnået til MySQL-server.");
if (! mysql_select_db($database, $dbConnection))
throw new Exception("Ingen forbindelse opnået til MySQL-databasen.");
}
catch (Exception $e) {
die($e->getMessage());
}
return $dbConnection;
}
function myQuery($query) {
try {
if (! $result = mysql_query($query))
throw new Exception("Database query failed!<br />".$query);
}
catch (Exception $e) {
die($e->getMessage());
}
return $result;
}
$dbh = myConnect($host, $user, $password, $database);
?>
In the section called “Assignment 0.0” we saw indirectly,
by not receiving an error message that we have
a working connection to the specified database.
What's next? What do we want it for?
The natural choice would be reading the database.
How? We say that we select
from the database or to be more precise, we select
from a database table.
A select is the database equivalent of
a file fread or fgets.
Text by nature is relatively unstructured. It is a sequence of characters. A text file therefore is not strictly structureed as opposed to a database which is highly structured. A database consists of tables. Tables have columns and rows. Order and structure above all. This gives us some possibilitites that we did not have with text files.
The database equivalent of a text file line is a
row. This is what we get by issuing a
select.
The structural element gives us the choice of
reading a whole row
from a table, or perhaps only certain columns from
the rows in question.
This is a possibility we don't have with text files
without considerable programming. To read a row from the city table
we issue a
select * from city;
The character * is a so called
wild card meaning
all columns from the
relevant table. Do we want only some of the columns
we write
select name, countrycode, population
from city;
for example. Now please do the section called “Assignment 0.1”
This exercise must be done in class, while I am watching you!
Write a PHP program that will create a page such as the following
This will serve as a refresher of your PHP skills so laboriously achieved in your 2nd semester. The program must have connect to the sample database. Nothing more at first. Keep the code we will reuse it. In order not to harms you I'll give most of the code. Do yourself a favor, key it in, don't copy and paste. Fill in the required code according to the above image, or something similar.
<?php
// setup necessary variables
// prepare eg. open files, connect to database
include "myDbFuncs.inc.php";
$page = 1; // example
$site = 1; // example
include "xhtmlTop.inc.php";
?>
<link rel="stylesheet" type="text/css" href="phpWorkshop.css"/>
<?php
include "xhtmlNeck.inc.php";
// build page layout
// populate with read data, no static data
print("<div id='body'>\n"); // wrapper if necessary
// content - fill with data read from database
print("</div>\n"); // end wrapper
include "xhtmlFoot.inc.php";
?>
This is a practical exercise!
Read the section called “Daily use of MySQL” for instruction
in MySQL daily use.
If you crave GUIs alse where they offer no added value
you may wish to use
http://localhost/phpmyadmin.
Once you have access, please connect to the world
database and test manually the two select
declarations shown here:
select * from city;
and
select name, countrycode, population from city;
If you do the assignment in class, confer with the teacher. If you do it at home, make a screen dump and mail it.