Activity: Playing with PHP

If you have not already done so, read up on PHP.
See PHPpartI

To make sure you can do it, create a Web page that refers to Tookey’s PHP file.
On my web page there is a copy of oldMcdonald:
Next, store a copy of Old McDonald on YOUR Lemuria.

Now write your OWN PHP code.
You may do this with a partner if you wish.

Your code should be more creative than Hello World.

It is acceptable to generate the verses to “we shall overcome” similar to Old McDonald.
https://www.azlyrics.com/lyrics/joanbaez/weshallovercome.html
https://www.lyrics.com/track/1070894/Mahalia+Jackson/We+Shall+Overcome
Or you may use a different, favorite, repetitive folk song.

If you have time left in lab, explore additional features of PHP.
Remember, we will be using PHP to generate SQL commands.

// Old MacDonald
$sounds = array("cow"=>"moo", "dog"=>"woof",
                "pig"=>"oink", "duck"=>"quack");
 
foreach ($sounds as $animal => $sound)
{
    print "<p>Old MacDonald had a farm EIEIO";
    print "<br>And on that farm he had a {$animal} EIEIO";
    print "<br>With a {$sound}-{$sound} here";
    print "<br>And a {$sound}-{$sound} there";
    print "<br>Here a {$sound}, there a {$sound}";
    print "<br>Everywhere a {$sound}-{$sound}";
    print "<p>Old MacDonald had a farm EIEIO";
}

Web Database Applications with PHP and MySQL, 2nd Edition [electronic resource]
Chapter 2 PHP part 1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Hello, world</title>
</head>
<body bgcolor="#ffffff">
  <h1>
  <?php
    print "Hello, world";
  ?>
  </h1>
</body>
</html>
 
<?php
  print "Hello, world";
?>
Alternates:
<script language="PHP"> </script>
<? 
 ?>
Terminate statement with ;
Whitespace is only for readablility
Can interleave with HTML
<?php $outputString = "Hello, world"; ?>
 
Can savein file  as *.PHP
 PHP may need to be on server to execute properly.
Github does not play well with PHP

 

Many syntax features are usable from C or Java:
++ += 
Comments WITHIN PHP:
// This is a one-line comment
#  This is another one-line comment style
/* This is how you
   can create a multi-line
   comment */
. for concatenation of strings
.- for append string
 
IF ELSE
if ($var > 5)
    print "Variable greater than 5";
else
    print "Variable less than or equal to 5";
Use {} for more than one statement
Elseif allowed
Switch allowed (but remember break)
Default allowed
 
== used for Boolean comparison;
!=
= used for assignments
&&        ||          !

 

 

LOOPS
$counter = 1;
while ($counter < 11)
{
    print $counter . " ";
    $counter++;
}
$counter = 1;
do
{
    print $counter . " ";
    $counter++;
} while ($counter < 11);
 
$counter = 1;
do
{
    print $counter . " ";
    $counter++;
} while ($counter < 11);
 
for($counter=1; $counter<11; $counter++)
{
    print $counter;
    print " ";
}
 
Can use break; to exit early
Can use continue; to go back to top of loopPRINTING
print "Hello, world";
// echo works just the same
echo "Hello, world";
//echo can print more than one thing
echo "The answer is ", 42;

 

Variables
Variable need not be declared, but must always have $
Case sensitive
$var = 15;
No strong typing.  Watch for confusion of type issues.
PHP has four scalar types—boolean, float, integer, and string—
and two compound types, array and object.
PHP also supports null— a special type that is used when a variable doesn’t have a value.
 
CONSTANTS:
define("PI", 3.14159);
M_PI;//built in
 
Predefined functions:
strtoupper($var);
string date(string format [, integer timestamp]);
string strval(mixed variable)
integer intval(mixed variable [, integer base])
float floatval(mixed variable)
boolean settype(mixed variable, string type)
settype( ) explicitly sets the type of variable to type, where type is one of array, boolean, float, integer, object, or string.
various values of $var are converted using the (int), (bool), (string), and (float) casting operators.
PHP provides the isset( ) function and the empty( ) language construct to test the state of variables
Can do user defined functions:
function bold($string)
{print "<b>" . $string . "</b>";}
[To return a value use :
return($result);]
 
Variables can be global:
function doublevalue( )
{
    global $temp;
    $temp = $temp * 2;
}
A static variable keeps value between calls:
static $count = 0;
Do NOT use recursion with static variables.
 
If must pass by reference, use &$ not $
 
Assign a default value to a parameter:  function heading($text, $headingLevel = 2)
 
PHP provides the include and require statements that allow you to reuse PHP scripts containing statements, function definitions, and even static HTML.               WARNING
Any PHP code in an include file must be surrounded by the PHP start and end script tags.

Quotes and Formatting:
Single or double quotes can be used, but embedded terminator must use ‘\’
print 'This works';
print "just like this.";
print "This string has a \": a double quote!";
print 'This string has a \': a single quote!';
// And here are some strings that contain quotes
print "This string has a ': a single quote!";
print 'This string has a ": a double quote!';
To include a backslash character in a double-quoted string, use the escaped sequence \\.
Tab, newline (line break), and carriage-return characters can be included in a double-quoted string using the escape sequences \t, \n, and \r, respectively.
Inserting the white space characters \t, \n, and \r is often useful to make output more readable, however as HTML, white space is generally disregarded.
// This is Ok. $var contains a newline character
$var = 'The quick brown fox
        jumps over the lazy dog';
later, to create SQL:
$query = "SELECT max(order_id)
            FROM orders
           WHERE cust_id = $custID";
 
Can put variables inside quotes:
$number = 45;
$vehicle = "bus";
$message = "This $vehicle holds $number people";
Use {} when embedding variables in literals
$message = "This {$vehicle} holds {$number} people";

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>The Times-Tables</title>
</head>
<body bgcolor="#ffffff">
<h1>The Times Tables</h1>
<?php
 
// Go through each table
for($table=1; $table<13; $table++)
{ 
    print "<p><b>The " . $table . " Times Table</b>\n";
 
    // Produce 12 lines for each table
    for($counter=1; $counter<13; $counter++)
    {
        $answer = $table * $counter;
 
        // Is this an even-number counter?
        if ($counter % 2 == 0)
            // Yes, so print this line in bold
            print "<br><b>$counter x $table = " .
                 "$answer</b>";
 
        else
            // No, so print this in normal face
            print "<br>$counter x $table = $answer";
    }
}
 
?>
</body>
</html>

 
Arrays and array library functions
 
Strings and string library functions
 
Regular expressions
 
Date and time functions
 
Integer and float functions
 
$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");
 
// Print the third element from the array of integers: 3
print $numbers[2];
 
// Print the first element from the array of strings: "Web"
print $words[0];
 
Associative arrays
An associative array uses string keys to access values stored in the array. An associative array can be constructed with array( ) by associating each key to a value using the => operator as shown in the following example:
 
$array = array("first"=>1, "second"=>2, "third"=>3);
 
// Print out the second element: prints "2"
print $array["second"];
 
HP arrays can contain heterogeneous values—that is any mix of integer, string, Boolean, float, object, and even array variables.
 
We can create a multidimensional array like this:
 
$table = array(
    1 => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
    2 => array(1 => 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24),
    3 => array(1 => 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36),
...
);
The easiest way to traverse or iterate through an array is using the foreach statement.
 
The count( ) function returns the number of elements in the array var:
The array_count_values( ) function counts the instances of each value in an input array, returning a new associative array of the resultant counts.

 

// Old MacDonald
$sounds = array("cow"=>"moo", "dog"=>"woof",
                "pig"=>"oink", "duck"=>"quack");
 
foreach ($sounds as $animal => $sound)
{
    print "<p>Old MacDonald had a farm EIEIO";
    print "<br>And on that farm he had a {$animal} EIEIO";
    print "<br>With a {$sound}-{$sound} here";
    print "<br>And a {$sound}-{$sound} there";
    print "<br>Here a {$sound}, there a {$sound}";
    print "<br>Everywhere a {$sound}-{$sound}";
    print "<p>Old MacDonald had a farm EIEIO";
}
 
$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",
              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");
 
$petFrequency = array_count_values($pets);
 
// prints 2
print $petFrequency["Dog"];
 
// prints:
// Array ( [Dog] => 2 [Rabbit] => 1 [Cat] => 2 [Chicken] => 1 )
print_r($petFrequency);
 
PHP provides two functions that create new arrays with pre-filled values:
array array_fill(integer start, integer count, mixed value)
array range(mixed low, mixed high [, integer step])
 
PHP provides the explode( ) , implode( ), and join( ) functions, which convert strings to arrays and back to strings
You can find values in arrays with in_array( ) and array_search( )