Appendix D. WebDev Tutorials I

Table of Contents
PHP: Tutorial
The Setting, the Context
The Tutorial
PHP: Hello World!
Code, An Introduction to Terminology
PHP: Operators
PHP Variables
PHP: Our First PHP Page
PHP: Arrays and Loops
PHP: Selections
PHP: Iterations
PHP: Three Ways of Printing, Well Five, but …
PHP: Reading Files
PHP: Writing Text Files
PHP: Class
PHP: The Project Outline
PHP: Database Conncetion
PHP: The Form, The Update, and their Connection
HTML5/CSS Basics

PHP: Tutorial

The Setting, the Context

The Question of Life, the Universe, and Everything

As an introduction here is an outline of the World Wide Web architecture. It places the course disciplines in a wider context. The aim is to get a high altitude perspective of the setting for your work in this course.

Figure D.1. Three tier client/server

Please notice that here too, the file systems are local to their respective servers. The server locations are on principle transparent. They are addressed through their URI's. In a development environment, all three tiers may be installed on our own development computer and addressed through the internet loopback URI localhost.


The Tutorial

The purpose is to get the reader started as quickly as possible, since we beleive strongly that the way to learn a new language is to write programs in it. The tutorial does assume a working knowledge of the basic elements of programming; there is no explanation of computers, of compilation, nor of the meaning of an expression like n = n + 1. Although we have tried where possible to show useful programming techniques, the book is not intended to be a reference work on data structures and algorithms; when forced to make a choice, we have concentrated on the language.

The quote above is from the mother of all programming books: The C Programming Language [KR88] by Kernighan and Ritchie. I can only hope to emulate the spirit here. Nothing more. Kernighan and Ritchie are inimitable,

PHP is a server side interpreted programming language and its acronym PHP stands for PHP Home Pages. Interpreted means that it is translated into computer code when the page is requestd by some user. Server side means that it is handled by a web server which calls on the PHP program to do it. After the interpretation, the output of that process is sent to the requesting program, normally a browser.

PHP: Hello World!

<?php
    print("Hello World!\n");

This has nothing to do with the web or even the internet. I shall display the output in two ways:

nml1 phptut  $ php helloworld.php
Hello World!
nml1 phptut  $ 

And in the browser as HelloWorld which produces the following page.

Figure D.2. Hello World Page
Hello World Page

When you examine this close by using view page source it displays the following.

Figure D.3. Hello World Page, Code View
Hello World Page, Code View

Still not much do do with the web, but let me add a bit of markup:

<?php
    print("<h1>Hello World!</h1>\n");

Resulting in the browserpage and its source code

Figure D.4. Hello World Page
Hello World Page

And

Figure D.5. Hello World Page, Code View
Hello World Page, Code View

In other words, the HTML5 markup does not come automatically. Like everything else, you put it into the file, and it is output by PHP

It is essential that PHP pages are served to the browser by a web server, ie with http://localhost/... in the URL, otherwise it is NOT interpreted by the PHP interpreter.

Code, An Introduction to Terminology

In order to understand or speak about anything one needs a vocabulary, words, and grammer, rules. One needs English, or Danish words, and the corresponding grammer to speak either of those two languages. We build sentences from words, and paragraphs from sentences. When you speak about programming, you must first realize that programming is expressed in a programming language. Expressing yourself in a programming language is called coding.

In code, in a programming language, the sentences are called statements. The statements consist of expressions that are built of variable(s) and value(s) combined by operator(s) . In a running program an expression always has a value .

A Statement Dissected

The following is a statement.

$foo = $bar + 42;

This statement consists of several expressions .

42
The literal value   42 is an expression, a literal value expression.
$bar
$bar is a variable expression, colloquially a variable, which, when used, returns the current value of the variable.

In PHP variable names must be prefixed a $, in casu $bar.

$bar + 42
This is an arithmetic expression consisting of the above two expressions joined by an arithmetic operator +.
$foo = $bar + 42
The whole statement is also an assignment expression. The $foo is a variable expression being assigned the value of the aritmetic expression mentioned above. The two expressions are joined by the assignment operator  =.

The way the computer treats a line of code, a statement, is that it processes the codeline left to right. If it is an assignment, it starts immediately to the right of the "=" and then proceeds towards the right. Again, if it is an assignment, the processed right hand side has resulted in a value, which is then assigned to the lefthand variable.

In case an expression contains parenthesis, the innermost will be executed first, then the next, working outwards just like in grammer school arithmetic.

Definition: A program, a script is a series of statements.

A variable name normally starts with a letter from the alphabet, and contains letters or digits after the beginning character. Variable names should be meaningful with respect to what they are used for. If a program is about potatoes and they must be counted, count, or perhaps potatoCount might be good variable names.

If ever at loss for a variable name, programmer folklore uses the so called metasyntactic variable names. Look it up at https://en.wikipedia.org/wiki/Metasyntactic_variable in Wikipedia, or perhaps in http://tools.ietf.org/html/rfc3092, RFC 3092 - Etymology of "Foo". They offer an impressive list of names: foo, bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, and thud, not to mention spam, ham, and eggs.

A Program, a Script

Let me repeat the definition: A program or a script is a series of statements.

Question: How to read a book?

Start in the upper left hand corner on the first page, and read one sentence after the other until there are no more sentences. Then you have finished.

Question: How to execute a program?

Sequences

Start reading the program file, execute one statement after the other until there are no more statements, then the computer finishes execution. Incidentally this has a name. It is called a sequence.

$waldo = 'white';
$fred = 'black';
// is a sequence

$waldo = 'black';
$fred = 'white'; 
// is another sequence
Selections

Let us assume you are writing a webpage for your mobile device. You want a white screen with black text if you read it in the daytime. If you read it at night you prefer to read white text on a black screen. How do you achieve that?

Your program obviously needs a statement to produce black text on a white background, and a statement that produces the opposite. Both should not be executed, just the appropriate one.

Your program must select one of these statements for execution. It is done by asking if it is daytime do black on white, otherwise, else, do white on black. Asking a question means setting up a condition and checking whether the condition evaluates to true or false. In the following example, the condition is in the parenthesis, and, in casu, a compound condition.

if ($baz > 6 && $baz < 18) {
    $waldo = 'white';
    $fred = 'black';
} else {
    $waldo = 'black';
    $fred = 'white'; 
}

This is a complication of course. For each choice we have two ways through the program.

In a helicopter perspective, the if-statement is just one statement in the sequence of statements, and thus executed in turn. It contains however, a selection.

Iterations

What if your page, program, had to flip a coin 10 times in order to check whether you would really get 5 heads, and 5 tails just as the statistician led you to believe?

In order to accomplish just that you must write the code to flip the coin, decide whether to add the result to a counter of heads, or to one of tails, and then do the adding.

$qux = mt_rand();
if ($qux % 2 == 0) {
    $heads = $heads + 1;
} else {
    $tails = $tails + 1;
}

This you must repeat 10 times.

You could naively write the same code ten times. Lots of typing. Lots of typos. You could also employ copy/paste programming with it's entailed risks of repeating errors. Finally, you could also think, write it once, and then make the program execute it ten times. Much less space for error. Much easier to fix an error if it is there only once. .

$count = 0;
while ($count < 10) {
    $qux = mt_rand();
    if ($qux % 2 == 0) {
        $heads = $heads + 1;
    } else {
        $tails = $tails + 1;
    }
    $count = $count + 1; 
}

Just 10 lines of code as opposed to 60 lines of code.

Another complication in excution of the program. No longer sequential execution, but sequential execution, then a section of repetitions, we call them iterations, and only then resuming the sequence. One way through the program? Yes, but you are wearing the asphalt thin in places.

The good news is that all programs are a combination of sequences, selections, and iterations. Nothing more complicated than that.

How To Decide What Way To Go? Conditions

We have already seen selections and iterations based on some kind of question. Conditions we call them. To make our lives as programmers easy, all conditions ask questions that can can be answerd with yes or no, true, or false.

condition
code if true
code if false

Or more abstractly

a
T
F

Or in code

    if ($qux % 2 == 0) {   // condition
        $heads = $heads + 1;    // code if true
    } else {
        $tails = $tails + 1;    // code if false
    }

In order to examine what happens when using conditions, the logicians have invented truth tables. In the following example we have two situations:

a !a
T F
F T

The left column representing

    if ($qux % 2 == 0) {   // condition
        $heads = $heads + 1;    // code if true
    } else {
        $tails = $tails + 1;    // code if false
    }

The right column representing

    if (!($qux % 2 == 0)) {   // condition
        $tails = $tails + 1;    // code if true
    } else {
        $heads = $heads + 1;    // code if false
    }

In the example of day or night we had a compound condition. Two conditions to be examined together, in casu a conjunction, an and. For a conjunction to be true, both the constituents must be true. The a, and b columns represent the two conditions, the a && b column is the truth table for the and situation. This column must be represented in your code.

a b a && b
T T T
T F F
F T F
F F F

The disjunction, the either/or situation has the following truth table. A disjunction is true if either of the constituent conditions is true.

a b a || b
T T T
T F T
F T T
F F F

PHP: Operators

I have just shown a few lines of code, sometimes referred to as loc. One was $foo = $foo + 1;. The + in that statement, the plus in the expression on the right hand side of the equals sign, is called an operator, in casu an arithmetic operator. I'll show the usage of some oeprators and, in comments, hint at what they do:

$foo = 42;                  // = is an assignment operator
$bar = 3.141;               // assign a floating point number (real) to bar
$foo = $foo + 1;            // add 1 to value of foo
                            // and then assign that new value to foo
$foo += 1;                  // equivalent to above, add 1 and assign
$foo = $foo * $bar + 1;     // multiply foo by bar and then add 1 
$foo = 1 + $foo * $bar;     // same as above
                            // normal mathematical precedence rules apply
$baz = 5;                   // let baz be the radius of a circle
$qux = M_PI * 5 ** 2;       // area of circle calculation (PHP V5.6+)
$quux = pi() * pow(5, 2);   // equivalent to above


            
<?php
    $title = 'Is It Monday?';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
        <style>
            section {
                margin-top: 1em;
            }
        </style>
    </head>
    <body>
        <header>
            <h1><?php print($title);?></h1>
        </header>
        <main>
        <?php
            $foo = 42;                  // = is an assignment operator
            printf("foo = %s<br/>\n", $foo);
            $bar = 3.141;               // assign a floating point number (real) to bar
            printf("bar = %s<br/>\n", $bar);
            $foo = $foo + 1;            // add 1 to value of foo
                                        // and then assign that new value to foo
            printf("foo = %s<br/>\n", $foo);
            $foo += 1;                  // equivalent to above, add 1 and assign
            printf("foo = %s<br/>\n", $foo);
            $foo = $foo * $bar + 1;      // multiply foo by bar and then add 1
            printf("foo = %s<br/>\n", $foo);
            $foo = 1 + $foo * $bar;     // same as above
                                        // normal mathematical precedence rules apply
            printf("foo = %s<br/>\n", $foo);
            $baz = 5;                   // let baz be the radius of a circle
            printf("baz = %s<br/>\n", $baz);
            $qux = M_PI * 5 ** 2;       // area of circle calculation (PHP V5.6+)
            printf("qux = %s<br/>\n", $qux);
            $quux = pi() * pow(5, 2);   // equivalent to above
            printf("quux = %s<br/>\n", $quux);


            printf("5/9 = %s<br/>\n", 5 / 9);
            printf("(int)(5/9) = %s<br/>\n", (int)(5 / 9));
            printf("5%%9 = %s<br/>\n", 5 % 9);

            $waldo = "select *";
            printf("<p>%s</p>\n", $waldo);
            $waldo = $waldo . " from country";
            printf("<p>%s</p>\n", $waldo);
        ?>
            <section id="weekday">
        <?php
                $now = time();
                printf("<p>%s</p>\n", strftime("%H:%M:%S", $now));
                printf("<p>%s</p>\n", strftime("%Y-%m-%d", $now));
                $todaysWeekday = strftime("%A", $now);

                print("Is today Monday?");
                $yesno = "Yes";
                if ($todaysWeekday != 'Monday') {
                    $yesno = 'No';
                }
                printf("<p>%s, today is %s</p>", $yesno, $todaysWeekday);
        ?>
            </section>
        </main>
        <?php
            include 'footer.inc.php';
        ?>
    </body>
</html>

View in browser.

PHP Variables

In the previous examples you hav already encountered variables in a couple of cases. The $title that was used to hold a string of text used for the HTML5 title tag as well as for the page header's h1 element. Again in the most recent example, the variable $weekday. It also contains a string.

A variable is assigned a value so that the program/page may remember that value, and reuse it at a later time. The two examples you have seen both used strings as values, but there are other possibilities such as numbers, booleans aka known as truth values. You may regard variables as references to addresses in the program's memory where the value is stored.

If Anna resides on 23675 Main St in Metropolis, you may decide to create

$resident = 'Anna';

this means that whenever the program refers to this variable it will refer to Anna. You don't have to remember the address. They are called variables, these address locations, because you may, at any time, change their values to something else such as

$resident = 'Charlotte'

Whereupon any reference to $resident will yield that value, until the value of the variable might be changed again.

Incidentally when you refer to $resident you say resident, NOT dollar resident.

Data Types

As stated a while ago, variables have types. Strings, numbers, booleans, etc. The variables are not restricted to be of one type only, the values of variables may changed type. It is perfectly feasible for a variable to be used as follows:

$foo = 'Kilroy was here!';
print("<p>%s</p>\n", $foo);     // prints Kilroy was here!

// lines of code

$foo = 42;
$foo = $foo + 1;
print("<p>%s</p>\n", $foo);     // prints 43

From this we learn that PHP is dynamically typed. In some languages variables must be declared to be of a certain type. Not in PHP Some misled programmers find that a flaw. Not so, it just means that they don't get the usage as good as you do :) Variables have types, of course they do, it is just that the types vary with the values currently assigned to the variables.

PHP: Our First PHP Page

A PHP page presenting some markup for our browser in a more normal form.

<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Hello Again World!</title>
    </head>
    <body>
        <header>
            <h1>Hello Again World!</h1>
        </header>
        <main>
            <p>
                I'm back :)
            </p>
        </main>
        <footer>
            <p>
                &copy; nml, 2015
            </p>
        </footer>
    </body>
</html>

View in browser.

PHP? Well, no PHP code, but saved as a PHP file. Legal? Yes, but not necessary, and moreover, the page is still static.

The same page in a somewhat more normal form. It has PHP code, and must consequently be interpreted by PHP.

<?php
    $title = 'Hello Again World!';
    $title = $_GET['head'];
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
    </head>
    <body>
        <header>
            <h1><?php print($title);?></h1>
        </header>
        <main>
            <p>
                I'm back :)
            </p>
        </main>
        <footer>
            <p>
                &copy; nml, 2015
            </p>
        </footer>
    </body>
</html>

View in browser.

Again same page. This time the workload between PHP and plain HTML5 has been shifted towards more PHP. Closer to best practice.

<?php
    $title = 'Hello Again World!';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
    </head>
    <body>
        <header>
            <h1><?php print($title);?></h1>
        </header>
        <main>
            <p>
                I'm back :)
            </p>
        </main>
        <?php
            include 'footer.inc.php';
        ?>
    </body>
</html>

View in browser.

PHP: Arrays and Loops

Let me summarize the ways of creating arrays in PHP. An array is a complex variable with one name and several values. You could say that the name in a manner of speaking points to the start of the array. The array has elements, open ended, and you address the individual elements by indexing them, the index is the distance to the element from the start of the array. You could say that an element has a numeric position and a value. PHP also has so called associative array, where an element has a name and a value

Example D.1. Syntax Etude
<?php
$students = array();        // a new, empty array
$students[] = 'Niels';      // add an element to the front
$students[] = 'Peter';      // add an element in the next index position
print($students[1]."<br/>");        // prints Peter

$alumni[0] = 'Per';         // start a new array
$alumni[1] = 'Pernille';    // add an element in the next index position
print($alumni[0]."<br/>");  // prints Per

$arr = array(5 => 1, 12 => 2);  // key value init of array
$arr[] = 42;                    // an element in next pos (13)
print($arr[12]."<br/>");        // prints 2

$newarr = array('Alberte' => 4711, 'Beatrice' => 4712, 'Charlotte' => 4713);
print($newarr['Beatrice']."<br/>");        // prints 4712

$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
print($array['foo']."<br/>");               // prints bar
print($array[100]."<br/>");                 // prints -100
print($array[-100]."<br/>");                // prints -100
var_dump($array);

$x[-1] = 'wtf';
$x[] = 'abc';
print("<br/>".$x[-1]."<br/>");
var_dump($x);

$todim[] = array(1, 0, 0, 0);
$todim[] = array(0, 1, 0, 0);
$todim[] = array(0, 0, 1, 0);
$todim[] = array(0, 0, 0, 1);
print("<br/>".$todim[1][1]);                        // prints 1
print("<br/>".$todim[2][3]."<br/>");                        // prints 0
var_dump($todim);
echo "<br/>";
print_r($todim);

?>

arrtut0.php


In the following four examples you will see various types of arrays, one dimensional indexed, one dimensional associative, and two dimensional indexed. You will notice various ways of declaring and populating the arrays, and you will see the four loop types of PHP.

Example D.2. arrays1.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <main>
<?php
    $arr1 = array('abc', 'def', 'ghi');
    printf("<p>arr1, print elements<br/>%s, %s, %s</p>\n",
            $arr1[0], $arr1[1], $arr1[2]);
    
    $arr2[0] = 'jkl';
    $arr2[1] = 'mno';
    $arr2[2] = 'pqr';
    print("<p>arr2, for loop:<br/>\n");
    for ($i = 0; $i < count($arr2); $i++) {
        printf("%s<br/>\n", $arr2[$i]);
    }
    print("<p>\n");

    print("<p>arr2, while loop:<br/>\n");
    $i = 0;
    while ($i < count($arr2)) {
        printf("%s<br/>\n", $arr2[$i]);
        $i++;
    }
    print("<p>\n");

    print("<p>arr2, do-while loop:<br/>\n");
    $i = 0;
    do {
        printf("%s<br/>\n", $arr2[$i]);
        $i++;
    } while ($i < count($arr2));
    print("<p>\n");

    print("<p>arr2, foreach loop:<br/>\n");
    foreach ($arr2 as $x) {
        printf("%s<br/>\n", $x);
    }
    print("<p>\n");
?>
        </main>
    </body>
</html>

        

arrays1.php


Example D.3. array2.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <main>
<?php
    $myar[] = 17;
    $myar[] = 42;
    $myar[] = 9;
    $myar[] = 123;
    $myar[] = 31;       // index 4
    $myar[9] = 99;
    
    printf("<p>myar, længde = %s: </p>\n", count($myar));
    
    print("<p>myar, for loop:<br/>\n");
    for ($i = 0; $i < count($myar); $i++) {
        printf("%s<br/>\n", $myar[$i]);
    }
    print("<p>\n");

    print("<p>myar, foreach loop:<br/>\n");
    foreach ($myar as $x) {
        printf("%s<br/>\n", $x);
    }
    print("<p>\n");
?>
         </main>
    </body>
</html>

        

array2.php


Example D.4. array3.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <main>
<?php
    $a = array("h" => 233, "j" => 117, 'k' => "sometext");
    $a['extra'] = 999;
    print("<p>a, associative, foreach loop:<br/>\n");
    foreach ($a as $k => $v) {
        printf("%s: %s<br/>\n", $k, $v);
    }
    print("<p>\n");
    
?>
        </main>
    </body>
</html>

        

array3.php


Example D.5. array4.php
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <main>
<?php
    $a = array("Rubrik1", "Rubrik2", "Rubrik3");
    $b = array('hallo', 'hva', 37);
    $c[] = 'peter';
    $c[] = 'anni';
    $c[] = 'Archie';
    $d[] = $a;
    $d[] = $b;
    $d[] = $c;
    
    print("<table>"
            . "<caption>d, 2-dim, foreach loop:</caption>");
    foreach ($d as $row) {
        print("<tr>\n");
        foreach ($row as $item) {
            printf("<td>%s</td>\n", $item);
        }
        print("</tr>\n");
    }
    print("<table>\n"); 
?>
        </main>
    </body>
</html>

        

array4.php


PHP: Selections

The somewhat mysterious name selection comes from the fact that a program sometimes does this, and sometimes that, depending on something. This or that code means sometimes this code is executed and sometimes that code. The selection of what code should be executed gives name to selections. The decision the program makes is based on something that can be expressed as a condition. A condition is an expression with a value of either true, or false.

We have in programming two ways of selecting code for execution, the if / if-else, or switch

if, else
if ($gadgets >= $lo) {
    print("We have plenty of gadgets in stock.");
} else {
    printf("Less than %d gadgets left. Time to order some more!", $lo);
}
if
if ($gadgets === 21) {
    printf("We have exactly %d gadgets in stock!", $gadgets);
}

or

if ($gadgets >= $lo && $gadgets <= $hi) {
    printf("We have between %d and %d gadgets in stock.", $lo, $hi);
}

or

if ($gadgets >= $lo) {
    if ($gadgets <= $hi) {
        printf("We have between %d and %d gadgets in stock.", $lo, $hi);
    }
}
if, else if, else,
if ($gadgets >= $lo) {
    print("We have plenty of gadgets in stock.");
} else if ($gadgets >= $xlo) {
    printf("Less than %d gadgets left. Time to order some more!", $lo);
} else {
    printf("Panic stations: Less than %d gadgets left! Order more now!", $xlo);
}
switch
a selection such as
if ( $userAction == "open" ) {
    // Open the file
} elseif ( $userAction == "save" ) {
    // Save the file
} elseif ( $userAction == "close" ) {
    // Close the file
} elseif ( $userAction == "logout" ) {
    // Log the user out
} else {
    print "Please choose an option";
}

where you test the same expression several times, may be written as

switch ($userAction) {
case "open":
    // Open the file
    break;
case "save":
    // Save the file
    break;
case "close":
    // Close the file
    break;
case "logout":
    // Log the user out
    break;
default:
    print "Please choose an option";
}
<?php
    $title = 'Selections, What is it?';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
        <style>
            header, footer {
                background-color: black;
                color: white;
            }
        </style>
    </head>
    <body>
        <header>
            <h1><?php print($title);?></h1>
        </header>
        <main>
        <?php
$xlo = isset($_GET['lo']) ? $_GET['lo'] : 5;
$lo = isset($_GET['lo']) ? $_GET['lo'] : 10;
$hi = isset($_GET['hi']) ? $_GET['hi'] : 30;
$gadgets = isset($_GET['gadgets']) ? $_GET['gadgets'] : 21;
print("<ol>\n");

if ($gadgets >= $lo) {
    print("<li>a) We have plenty of gadgets in stock.</li>\n");
} else {
    printf("<li>b) Less than %d gadgets left. Time to order some more!</li>\n", $lo);
}

if ($gadgets == 21) {
    printf("<li>c) We have exactly %d gadgets in stock!</li>\n", $gadgets);
}

if ($gadgets >= $lo && $gadgets <= $hi) {
    printf("<li>d) We have between %d and %d gadgets in stock.</li>\n", $lo, $hi);
}

if ($gadgets >= $lo) {
    if ($gadgets <= $hi) {
        printf("<li>e) We have between %d and %d gadgets in stock.</li>\n", $lo, $hi);
    }
}

if ($gadgets >= $lo) {
    print("<li>f) We have plenty of gadgets in stock.</li>\n");
} else if ($gadgets >= $xlo) {
    printf("<li>g) Less than %d gadgets left. Time to order some more!</li>\n", $lo);
} else {
    printf("<li>h) Panic stations: Less than %d gadgets left! Order more now!</li>\n", $xlo);
}
print("</ol>\n");

        ?>
        </main>
        <footer>
            <p>&copy; nml</p>
        </footer>
    </body>
</html>

View in browser.

PHP: Iterations

PHP has several ways of repetitively executing the same statements a number of times. The subject matter lingo has it as iterations, you may also call it loops.

while
<?php
$i = 0;
while($i < 10) {
    print($i + 1);
    $i++;
}
?>
do - while
<?php
$i = 0;
do {
    print($i + 1);
} while($i < 10);
?>
for
<?php
for ($i = 0; $i < 10; $i++) {
    print($i + 1);
}
?>
Example D.6. while example
<?php
    $title = 'The Third Page';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
        <style>
            table, td {
                border: 1px solid blue;
                padding: 5px;
            }
            table {
                margin: 0 auto;
            }
            td {
                text-align: right;
            }
            header, footer {
                background-color: black;
                color: white;
            }
        </style>
    </head>
    <body>
        <header>
            <h1><?php print($title);?> - Fahrenheit to Celsius</h1>
        </header>
        <main>
        <?php
            $lower = 0;
            $upper = 300;
            $step = 20;

            print("<table>\n");
            $fahr = $lower;
            while ($fahr <= $upper) {
                $celsius = 5 * ($fahr - 32) / 9;
                printf("<tr><td>%d</td><td>%5.2f</td></tr>\n", $fahr, $celsius);
                $fahr = $fahr + $step;
            }
            print("</table>\n");
        ?>
        </main>
        <footer>
            <p>&copy; nml</p>
        </footer>
    </body>
</html>

View in browser.


Example D.7. for example
<?php
    $title = 'The Third Page';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
        <style>
            table, td {
                border: 1px solid blue;
                padding: 5px;
            }
            table {
                margin: 0 auto;
            }
            td {
                text-align: right;
            }
            header, footer {
                background-color: black;
                color: white;
            }
        </style>
    </head>
    <body>
        <header>
            <h1><?php print($title);?> - Fahrenheit to Celsius</h1>
        </header>
        <main>
        <?php
            $lower = 0;
            $upper = 300;
            $step = 20;
            
            print("<table>\n");
            for ($fahr = $lower; $fahr <= $upper; $fahr += $step) {
                $celsius = 5 * ($fahr - 32) / 9;
                printf("<tr><td>%d</td><td>%5.2f</td></tr>\n", $fahr, $celsius);
            }
            print("</table>\n");
        ?>
        </main>
        <footer>
            <p>&copy; nml</p>
        </footer>
    </body>
</html>

View in browser.


Example D.8. do while example
<?php
    $title = 'The Third Page - From the C book ;)';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($title);?></title>
        <style>
            header, footer {
                background-color: black;
                color: white;
            }
        </style>
    </head>
    <body>
        <header>
            <h1><?php print($title);?> - Fahrenheit to Celsius</h1>
        </header>
        <main>
        <?php
            $limit = 1000;
            $width = 1;
            $length = $width;
            
            do {
                $width++;
                $length++;
                $area = $width * $length;
            } while ($area < $limit);
            
            printf("The smallest square over %d m<sup>2</sup> in area<br/>
                    is %d m x %d m = %d m<sup>2</sup></p>\n", 
                    $limit, $width, $length, $area);
        ?>
        </main>
        <footer>
            <p>&copy; nml</p>
        </footer>
    </body>
</html>

View in browser.


PHP: Three Ways of Printing, Well Five, but …

PHP's claim to fame, as in PHP Home Pages, is it's ability with ease, to create dynamic HTML5 documents requested by the user. How is this done? Easy, PHP prints the HTML5. Easy, yes, but it can still be done in a number of ways.

The first way is a bit astonishing perhaps. The PHP script steps out of PHP mode and outputs plain HTML5 as if you were in an HTML5 document. Not really printing, it is not included in the three ways.

<?php
  // php statements
  $foo = 42;
?>
  <!-- outside php, write html here -->
  <header>
    <h1>PHP Rules</h1>
  </header>
  <main>
    <!-- etc -->
<?php
  // step back into php mode and continue
  $bar = factor($foo);

?>

Let me assume that you want to print two table data elements with some variable content coming from two PHP variables. The resulting static HTML5 would look like:


  <td>17°</td>
  <td>Clouded</td>
echo
<table>
<?php
  $temp = 17;
  $cloud = "Overcast";
  echo "<tr>";
  echo "<td>$temp&deg;</td>\n<td>$cloud</td>";

  // or

  echo "<td>" . $temp . "&deg;</td>\n<td>" . $cloud. "</td>";

  // or

  echo '<td>' . $temp . "&deg;</td>\n<td>" . $cloud. '</td>';
  echo "</tr>";
print
<table>
<?php
  $temp = 17;
  $cloud = "Overcast";
  print("<tr>")
  print("<td>$temp&deg;</td>\n<td>$cloud</td>");

  // or

  print("<td>" . $temp . "&deg;</td>\n<td>" . $cloud. "</td>");

  // or

  print('<td>' . $temp . "&deg;</td>\n<td>" . $cloud. '</td>');

  print("</tr>");
printf
<table>
<?php
  $temp = 17;
  $cloud = "Overcast";

  printf("<tr><td>%s&deg;</td>\n<td>%s</td></tr>", $temp, $cloud);
sprintf
Also not counted in the three ways. It formats a string, it does not really print it.
<table>
<?php
  $temp = 17;
  $cloud = "Overcast";

  $s = sprintf("<tr><td>%s&deg;</td>\n<td>%s</td></tr>", $temp, $cloud);

sprintf() does not print, it returns a string for the user. The string is formatted in the same way as it would be by printf().

print_r
The function print_r() is for debugging only. You will never use it for content or messages to the user of your application.
var_dump
The function var_dump() is also for debugging only. You will not use it for content or messages to the user of your application.

PHP: Reading Files

Files may be read in either of two ways. Either you read line by line until you find what you want, or to the end of the file. How much you save for deferred processing is up to you. The other way is reading a whole file into a string buffer. Then you may traverse the read text from the buffer. The latter has high ram demands if files are big.

Example D.9. Reading a File in a Loop, Line by Line, readfile.php
<?php
    $key = 'Monday';
    $title = 'Is It ' . $key . '?';
    $weekday = date('l', time());
    if ($weekday === $key) {
        $title .= ' 42!';
    } else {
        $title = 'It Is Not ' . $key . '!';
    }

    $file = isset($_GET['file']) ? $_GET['file'] : 'ourfirstfile.txt';

    include '../head1n.inc.php';
    include '../neck1n.inc.php';

    $fh = fopen($file, 'r');                // open file, must

    print("<table>\n");
    while (!feof($fh)) {
        $line = fgets($fh);                 // read while not at e-o-f
        $arr = explode(":", $line);         // do whatever
        print("<tr>\n");
        for ($i = 0; $i < count($arr); $i++) {
            printf("<td>%s</td>", $arr[$i]);
        }
        print("</tr>\n");
    }
    print("</table>\n");

    include '../feet1n.inc.php';

Example D.10. Reading a File in a Loop, Line by Line, readwithsearch.php
<?php
    $key = 'Monday';
    $title = 'Is It ' . $key . '?';
    $weekday = date('l', time());
    if ($weekday === $key) {
        $title .= ' 42!';
    } else {
        $title = 'It Is Not ' . $key . '!';
    }

    $file = isset($_GET['file']) ? $_GET['file'] : 'ourfirstfile.txt';

    include '../head1n.inc.php';
    include '../neck1n.inc.php';

    $fh = fopen($file, 'r');
    print("<table>\n");
    while (!feof($fh)) {
        $line = fgets($fh);
        $arr = explode(":", $line);
        $t = stripos($line, 'systemd');     // is systemd in text
        if ($t !== false) {                 // if yes skip
            continue;
        }
        printf("<tr %s>\n", $t);
        for ($i = 0; $i < count($arr); $i++) {
            printf("<td>%s</td>", $arr[$i]);
        }
        print("</tr>\n");
    }
    print("</table>\n");
    include '../feet1n.inc.php';

View passwords in browser.


Example D.11. Reading a Whole File in One Go
<?php
    $key = 'Monday';
    $title = 'Is It ' . $key . '?';
    $weekday = date('l', time());
    if ($weekday === $key) {
        $title .= ' 42!';
    } else {
        $title = 'It Is Not ' . $key . ';)';
    }

    $file = isset($_GET['file']) ? $_GET['file'] : 'ourfirstfile.txt';

    include '../head1n.inc.php';
    include '../neck1n.inc.php';

    $totalfiletext = file_get_contents($file);  // read whole file
    $lines = explode("\n", $totalfiletext);     // create array of lines

    print("<table>\n");
    foreach ($lines as $line) {                 // loop through lines
        printf("<tr><td>%s</td></tr>\n", $line);
    }
    print("</table>\n");

    include '../feet1n.inc.php';

View in browser.


PHP: Writing Text Files

As with reading, files may be written in either of two ways. Either you write line by line until you're done, or you build a whole file into a string buffer, and then write the buffer into the file in one go.

Example D.12. Write Line by Line
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Form</title>
    </head>
    <body>
        <h1>Headline for text input</h1>
        <form action='myrealrecipient.php' method='post'>
            <p>
            Headline:<br/>
            <input type='text' name='headline'/>
            </p>
            <p>
            Content:<br/>
            <textarea rows='10' cols='50' name='bread'></textarea>
            </p>
            <input type='submit' value='OK'/>
        </form>
    </body>
</html>
<?php
if (isset($_POST['headline']) && $_POST['headline'] != ''
    &&
    isset($_POST['bread']) && $_POST['bread'] != '') {

                                                // line by line
    $file = 'ourfirstfile.txt';
    $fh = fopen($file, 'w');                    // file open, must, new file
    if($fh == false)                            // success?
        die("unable to create file");               // no
    $text = $_POST['headline'];                 // yes
    $text .= PHP_EOL;                           // pertinent eod of line
    fwrite($fh, $text);                         // write a line
    $text = $_POST['bread'];
    $text .= PHP_EOL;                           // programmer responsibility
    fwrite($fh, $text);                         // write a line
    fclose($fh);                                // file closed, or it doesn't exist

    header('Location: ./myrealinput1.html?ok');
} else {
    header('Location: ./myrealinput1.html?errorcode=42');
}

Write through form.

Read result.


Example D.13. Write All in One
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Form</title>
    </head>
    <body>
        <h1>Headline for text input</h1>
        <form action='myrealrecipient1.php' method='post'>
            <p>
            Headline:<br/>
            <input type='text' name='headline'/>
            </p>
            <p>
            Content:<br/>
            <textarea rows='10' cols='50' name='bread'></textarea>
            </p>
            <input type='submit' value='OK'/>
        </form>
    </body>
</html>
<?php
if (isset($_POST['headline']) && $_POST['headline'] != ''
    &&
    isset($_POST['bread']) && $_POST['bread'] != '') {

    $file = 'ourfirstfile.txt';

    $text = $_POST['headline'];                     // yes
    $text .= PHP_EOL;                               // pertinent end of line
    $text .= $_POST['bread'];
    $text .= PHP_EOL;                               // programmer responsibility
    file_put_contents($file, $text, FILE_APPEND);   // in one go

    header('Location: ./myrealinput1.html?ok');
} else {
    header('Location: ./myrealinput1.html?errorcode=42');
}

Write through form.

Read result.


PHP: Class

Figure D.6. Class Room

Example D.14. Class Room, Room.php
<?php
/**
 * Description of Room
 * Teaching resources, ie classrooms
 * 
 * @author nml
 */
class Room {
    const M3PP = 6;
    private $id;
    private $lengthInM;
    private $widthInM;
    private $heightInM;
    private $floor;
    
    public function __construct($id, $lengthInM,
            $widthInM, $heightInM, $floor) {
        $this->id = $id;
        $this->lengthInM = $lengthInM;
        $this->widthInM = $widthInM;
        $this->heightInM = $heightInM;
        $this->floor = $floor;
    }

    public function getId() { return $this->id; }
    public function getLength() { return $this->lengthInM; }
    public function getWidth() { return $this->widthInM; }
    public function getHeight() { return $this->heightInM; }
    public function getFloor() { return $this->floor; }
    public function getPersonCapacity() { 
        return (int)($this->getLength() * $this->getWidth() *
                $this->getHeight() / self::M3PP); 
    }
    
    public function __toString() {
        $s = sprintf("%16sRum: %s, L:%s, W:%s, H:%s, Max %s persons<br/>\n", 
                ' ', $this->getId(), $this->getLength(),
                $this->getWidth(), $this->getHeight(),
                $this->getPersonCapacity());
        return $s;
    }
}

PHP: The Project Outline

This demo project consists of a front page with a menu for selecting a page for entering new rooms into the database ie a form page, and a database update page called from the form.

In addition to that there is a room display page called directly from the front page. It reads and displays rooms from the database.

One might say this satisfies the CR-part of the CRUD, Create, Retrieve, Update, and Delete of database rows.

Example D.15. Frontpage of the project, index.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create Rooms</title>
        <link href="./css/styles.css" rel="stylesheet"/>
    </head>
    <body>
<?php
        require_once './includes/menu.inc.php';
?>
        <main>
            <h1>School Admin</h1>
            <h2>Classrooms</h2>
        </main>
<?php
        require_once './includes/footer.inc.php';
?>
    </body>
</html>

Example D.16. Display Page, displayRooms.php
<?php
require_once './includes/Room.php';
require_once './includes/DbP.inc.php';
require_once './includes/DbH.inc.php';
$dbh = DbH::getDbH();

$sql = "select * from room order by length * width * height";
try {
    $rs = $dbh->query($sql);
} catch(PDOException $e) {
    printf("<p>%s</p>\n", $e->getMessage());
    die("go belly up");
}

$rooms = array();
while ($out = $rs->fetchObject()) {
    $r = new Room($out->id, $out->length, 
            $out->width, $out->height, $out->floor);
    $rooms[] = $r;
}
if (count($rooms) != 0) {
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create Rooms</title>
        <link href="./css/styles.css" rel="stylesheet"/>
    </head>
    <body>
<?php
        require_once './includes/menu.inc.php';
?>
        <main>
            <h1>School Admin</h1>
            <h2>Classrooms</h2>
            <p>
<?php
            foreach($rooms as $room) {
                print($room);
            }
            printf("%12s</p>\n", " ");
            printf("%8s</main>\n", " ");
}
        require_once './includes/footer.inc.php';
?>
    </body>
</html>

PHP: Database Conncetion

Example D.17. Concrete Class DbH.inc.php

The database handler is project agnostic, aka project invariant. Never changes as long as the PDO object doesn't change. This means that it may be copied into every new project.

<?php
/**
 * Project Agnostic DbH.inc.php with PDO
 * @author nml
 * @copyright (c) 2018, nml
 * @license http://www.fsf.org/licensing/ GPLv3
 */
require_once 'DbP.inc.php';

class DbH extends DbP {
    private static $instance = FALSE;
    private static $dbh;

    private function __construct() {
        try {
            self::$dbh = new PDO(DbP::DSN, DbP::DBUSER, DbP::USERPWD);
            self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            printf("<p>Connect failed for following reason: <br/>%s</p>\n",
              $e->getMessage());
        }
    }

    public static function getDbH() {
        if (! self::$instance) {
            self::$instance = new DbH();
        }
        return self::$dbh;
    }
}

Example D.18. Abstract Class DbP.inc.php

The abstract class, DbP holds the database connection parameters. They change per project.

<?php
abstract class DbP {
    const DBHOST = 'localhost';
    const DBUSER = 'nobody';
    const USERPWD = 'test';
    const DB = 'db5';
    const DSN = "mysql:host=".self::DBHOST.";dbname=".self::DB;
}

PHP: The Form, The Update, and their Connection

The form might be a pure HTML5 was it nor for some small UX related issues.

Example D.19. The Form enterRooms.php
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create Rooms</title>
        <link href="./css/styles.css" rel="stylesheet"/>
        <style>
            #error { color: red; }
        </style>
    </head>
    <body>
<?php
        require_once './includes/menu.inc.php';
?>
        <main>
            <form action="room2db.php" method="post">
                <table>
                    <caption>Enter Classroom</caption>
                    <tr><td>Length:</td>
                        <td>
                            <input type="text" name="length" 
                                   placeholder="enter length in meters"/>
                        </td></tr>
                    <tr><td>Width:</td>
                        <td>
                            <input type="text" name="width" 
                                   placeholder="enter width in meters"/>
                        </td></tr>
                    <tr><td>Height:</td>
                        <td>
                            <input type="text" name="height" 
                                   placeholder="enter height in meters"/>
                        </td></tr>
                    <tr><td>Floor:</td>
                        <td>
                            <input type="text" name="floor" 
                                   placeholder="enter floor no"/>
                        </td></tr>
                    <tr><td></td><td><input type="submit" value="Go"/></td></tr>
                </table>
            </form>
            <?php
                if (!empty($_GET['error']) && $_GET['error'] == 1) {
                    print("<p id='err'>All input fields must filled</p>");
                }
                if (isset($_GET['inserted'])) {
                    print("<p>Room inserted</p>");
                }
            ?>
        </main>
<?php
        require_once './includes/footer.inc.php';
?>
    </body>
</html>

Example D.20. The Database Update room2db.php
<?php
// receives data in $_POST array
require_once './includes/Room.php';
require_once './includes/DbP.inc.php';
require_once './includes/DbH.inc.php';
$dbh = DbH::getDbH();

foreach ($_POST as $key => $value) {    // create named vars
    $$key = trim($value);               // from form input fiekds
}

if (    empty($length)   // check that no field is empty
     || empty($width)
     || empty($height)
     || empty($floor)
   ) {
    header("Location: ./enterRooms.php?error=1");
}

$room = new Room(null, $length, $width, $height, $floor);

$sql = "insert into room (length, width, height, floor)";
$sql .= " values(:l, :w, :h, :f);";
try {
    $q = $dbh->prepare($sql);
    $q->bindValue(':l', $room->getLength());
    $q->bindValue(':w', $room->getWidth());
    $q->bindValue(':h', $room->getHeight());
    $q->bindValue(':f', $room->getFloor());
    $q->execute();
} catch(PDOException $e) {
    printf("<p>%s</p>\n", $e->getMessage());
    die("go belly up");
}
header("Location: ./enterRooms.php?inserted");

HTML5/CSS Basics

<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>This goes into the title line</title>
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            header, footer {
                background-color: black;
                color: white;
            }
            h1 {
                margin: 0;
            }
            a {
                color: yellow;
                text-decoration: none;
            }
            a:hover {
                /* font-weight: bold; */
                color: magenta;
            }
            header ul {
                list-style: none;
                text-align: right;
            }
            header li {
                display: inline;
                font-family: Helvetica, sans-serif;
                font-size: 1.2em;
                margin-left: 1.5em;
            }
        </style>
    </head>
    <body>
        <header>
            <h1>This goes into the title line</h1>
            <ul>
                <li><a href="./myinput.html">Home</a></li>
                <li><a href="http://dr.dk">First Office</a></li>
                <li><a href="http://bbc.co.uk">Second Office</a></li>
                <li><a href="http://fu.dk">The Minister</a></li>
            </ul>
        </header>
        <main>
            <p>
                This is actual content, made up on the spot by your's
                truly for the sake of demoing various qualities of html.
            </p>
            <p>
                This is actual content, made up on the spot by your's
                truly for the sake of demoing various qualities of html.
            </p>
            <ol>
                <li>this is th first</li>
                <li>and this the second</li>
                <li>third</li>
            </ol>
        </main>
        <footer>
            &copy;, nml, 2015, &reg;
        </footer>
    </body>
</html>

View in browser.

body {
    margin: 0;
    padding: 0;
}
header, footer {
    background-color: black;
    color: white;
}
h1 {
    margin: 0;
}
a {
    color: yellow;
    text-decoration: none;
}
a:hover {
    /* font-weight: bold; */
    color: magenta;
}
header ul {
    list-style: none;
    text-align: right;
}
header li {
    display: inline;
    font-family: Helvetica, sans-serif;
    font-size: 1.2em;
    margin-left: 1.5em;
}
<?php
    $headline = 'What you see is what you get';
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title><?php print($headline)?></title>
        <link rel='stylesheet' href='newstyles.css'/>
    </head>
    <body>
<?php
        include 'header.inc.php';
?>
        <main>
            <p>
                This is actual content, made up on the spot by your's
                truly for the sake of demoing various qualities of html.
            </p>
            <p>
                This is actual content, made up on the spot by your's
                truly for the sake of demoing various qualities of html.
            </p>
            <ol>
                <li>this is th first</li>
                <li>and this the second</li>
                <li>third</li>
            </ol>
        </main>
<?php
        include 'footernml.inc.php';
?>
    </body>
</html>

View in browser.