Dynamic Web Pages with PHP Week 2

How a PHP Cache Works

When you write new PHP statements and upload a file to a server, you will notice a wide range of performance in how fast your page reloads in your browser. The delay is not likely at your end unless you happen to be on a very slow Internet connection or there is a major outage or runaway process on the Web somewhere. Instead, the delay is within the PHP process itself. Requests for PHP processing can pile up when multiple people are using the same single server. But, the PHP engine has a trick available to administrators like myself. Popular PHP queries can be run and saved in the cache such that they can be served immediately without having to be recomputed.

Think about that within the context of our class goals. We want to be able to have highly dynamic pages which means our content can change via changes to our PHP statements or changes to the data we access in our database(s). A good PHP process cache must constantly check whether our PHP code has changed or if our data has changed. If either of these do change, the PHP engine must refresh the result being held in the cache. One huge benefit of using an Internet Service Provider who can afford a huge amount of live computer memory is that more PHP results can be held in the cache and maintained to be as fast as possible in serving those requests that request it on a regular basis. I am extremely impressed how Go Daddy's PHP and mysql caches work. I feel confortable writing very complicated database queries and convoluted PHP statements that work with that data - because I know the cache will update the page that gets returned and keep it in the cache upon the first running of the new statements and data changes. But, here's the trick: I always run the code myself first myself in a browser so it is in the cache before anyone else has to wait! This sounds obvious since you'll want to verify your results anyway, but some people (like myself) cut corners when it comes to code (when the world isn't going to end based on a mistake - and I don't work on that code in the first place). The cache has motivated me not to cut corners as some of my queries take upwards of five minutes to run on even Go Daddy's quick databases.

In our class, you can likely forget about the cache. For one reason, the cache is very small on our very humble server from 1997 technology (hey - if your code performs on there you can have confidence it will work almost everywhere - there is benefit to using old technology during develoment). And, for another reason, our PHP statements and databases are not likely to get so complex (which is why I need to make you aware of this cache issue early and often for any professional work you do). OK, enough said. Let's start learning some PHP (and let's make the commitment to never stopping to do so - as long as we want to be effective layout and information designers).

Basic PHP Syntax

I learn PHP best by following discussions among programmers who write PHP code often. I like dialog in my novels to break up all that description that some writers go overboard on (I am more a plot guy outside of one extensive description of the character I am supposed to be identifying with for the ride in the story). Many PHP support groups follow an on-line recipe of presenting an interesting description of something interesting that can be done wth PHP and then opening up a discussion on the implications, efficiency, and usefulness of that topic. Take a look at http://www.php.net/basic-syntax and read through the page while noticing how the format opens up a discussion with anyone on the Internet (or at least those invited guests who have been selected for their brilliant track record).

Thousands of Informative Pages

There are literally thousands of such code-suggestive pages on the Web for any popular computing language. It behooves you to get used to thinking in bite-sized chunks because this wonderfully collective reference is there for the taking. I love sitting under a tree somewhere and reading a book sequentially. In fact, my ideal vacation is on a beach with a good popular science book which I read cover to cover. But, it is not the ideal way to learn a computing language like PHP. I believe in the power of our redundant senses and in how redundant information from different senses builds our associative memory in ways that make us smarter (Jeff Hawkins' On Intelligence book resonates well with me on this topic because it rings so true in how my own smarts have been improved over time). Get your eyes and your fingers involved in the learning process. Read something and try it out! Read something more and try it out! Stop occasionally to reflect on everything you've been doing. And, then most importantly, get away from it and do something active that takes the burden off your consciousness so your sub-conscious can do some housekeeping with your new information. My suggestion is to save the most important things you need to learn for intense multi-sensory learning just before you go to sleep (for the evening or that power nap). Then sleep on it. If your brain gets used to that pattern, it will do amazing things while you sleep - including invading your dreams at times with powerful insights that just need to be interpreted to real world ways.

So many of us have found this trick to be so consistently successful and efficient that all our dicussions follow that pattern (hence the popular referencing formats like this example above). And with the Web and on-line repositories, we get this amazing ability to improve our collective intelligence by taking advantage of time zones brought on by a rotating planet. My favorite coding projects are those with teams dispersed eight hours apart. For example, I worked on a project with a team in Turin, Italy and Melbourne, Australia while I was in Seattle working with Californians. Our day started by reading updates as to where our Tuscan team had gotten during their workday. They put their questions in writing and we answered them in the flow of our workday (while they slept!). Then we gave an update to our Aussie team and asked questions of them. They worked and answered our questions while we slept. I would get up in the morning, pour a nice strong cup of bitter coffee (as all us Seattlites seemed to do), and delight in quietly reading the answers to all my questions! They were all answered and discussed in a manner like this page above. We all became so thankful for each other and we took our eight hours off from the moment we woke to eight hours later doing things we loved knowing that working would not be very useful - the next team was handling it all for us.

So, you aren't convinced. There is that recommended text book to play with in this class. And, there are plenty of run-on sequential pages on-line to read for learning (like this lecture page is becoming). Just Google with the word 'tutorial' on the topic you are interested in reading sequentially on. Do some empirical tests though - try learning both ways (with or without doing while you read) and see if your hardfast behaviors are in fact more enjoyable and more fruitful for your personal goals. Then ask yourself who multinational companies are frantically trying to set up coding teams eight hours apart from each other (the insurance company I worked for chose Ireland, China, and the US for good reason, in my humble opinion (abreviated as IMHO from now on as you might see often in these technical resources that are open to discussion)).

The rest of this lecture points out important concepts to get you started. I recommend reading each tidbit and then trying to implement it in one of our projects from class. Get into the swing of interactivity and iteration and see where it takes you.

PHP Data Types

No topic will be more important than understanding PHP data types - only because we will be connecting to databases holding data that we will want to manipulate and present properly to our Web audience. Ask yourself, "did I spend the requisite time to really understand all the HTML data types I have used in writing Web pages?". If the answer is, "perhaps not but how would I know?" (because you like to answer a question with another question), then take a look at http://www.php-editors.com/html4ref/types.html. It might be a little too technical for your likes, but it does a good job of outlining the types of data HTML incorporates. And guess what... since PHP is just a way to identify dynamic content for a static language (like HTML), the data types contained in PHP will need to align with the end-result content in order to be of maximum use.

The Basic Building Blocks

To focus on variable and PHP data types, I repeat the tutorial from http://www.smartwebby.com/php/variable.asp, but with my edits, here:

Variables are nothing but identifiers to the memory location to store data (think of an identifier as a label - you are identified by all the labels people put on you, first and foremost your name). In PHP code, we can create hundredds of variables in a single .php document. In PHP all variables in your code must begin with a dollar sign "$" and the value can be assigned using the "=" operator as shown below:


$Name, $Name1, $First_Name, $Last_Name

$Name = "David";

$Age = 16;

              Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't specify the variable type (type referring to how data is formatted in dynamic memory or the stored memory of a hard drive), as it takes the data type of the assigned value (you assign something and PHP figures out its type from how you wrote what was being assigned to that label). In the above example, the PHP engine understands that '$Name' is of data type String and '$Age' is of type Numeric.

Limitations in Variable Naming:

              PHP has no limit on the length of variable name as in the case of other programming languages. The variable name must start with a letter or underscore. The variable name must be a combination of letters, numbers and underscores. Other characters such as *, +, #, @ are not allowed and causes an error if used.

Data Types in PHP

In PHP the data type of a variable is not set by the programmer. PHP decides the data type of variables after interpreting the Web page. Data Types in PHP include:

  • Numeric data type
  • String data type
  • Array data type

Numeric data type

Numeric data type is used for a number. There are two different numeric data types:

  • Integer
  • Double

Integer Data Type

       Integer data types contain whole number values.


$intmark = 100;


      Double contains double-precision (usually 32 bits) floating point numbers.


$doubtotal = 99.5;

String Data Type

     String data type is used to contain textual information or sequences of letters combined with numeric digits. The value is assigned within quotes as shown below.


$strName = "David";

$strId = "David123";

String Concatenation

String Concatenation is a process of adding two strings. This is done by attaching one string to the end of another string. This is done by using '.' (period) operator as shown below:


$strFirst_Name = "David";

$strSpace = " ";

$strLast_Name = "John";

$strName = $strFirst_Name.$strSpace.$strLast_Name;

echo $strName;


David John

Array Data Type

Array data type is used to contain many values in a single variable. Each array element can be retrieved by using the array variable name and its key/index value. We can declare an array variable in different ways as shown below:


$arrMark[0] = 95;

$arrMark[1] = 88;

$arrMark[2] = 77;


$arrMark = array(95,88,77);

In the above example, the variable 'arrMark' contains three different values. In the first method the array elements are stored using the key values (0, 1, 2), but in the second example the keyword 'array' is used to assign values to the array variable. By default, array key element starts with 0.

The array elements can be accessed by using their key values. The different marks stored in the array elements can be added together to obtain the total marks as shown below:


$intTotalMark = $arrMark[0] + $arrMark[1] + $arrMark[2];

echo $intTotalMark;

Output: 260

In the above two examples we have used the key values as numbers, but it not necessary that the key value must be a number, it can also
be a string as shown below:


$arrMark['maths'] = 95;

$arrMark['english'] = 88;

$arrMark['science'] = 77;

$intTotalMark = $arrMark['maths'] + $arrMark['english']+$arrMark['science'];

echo $intTotalMark;


A word about diagramming variables

Basic variable types are often called built-in types if the type is understood natively by the programming language being processed by a computer. For diagramming purposes, you can consider basic variables as objects or you can consider them just ordinary parts of the basic statements that make up your code. I like to code the variable based on its use as opposed to whether it is a built-in type or not. But, I do believe any of these diagramming choices are valid.

What are you waiting for?

That's a lot of powerful information - presented in a format that isn't very obvious to our brains unless we've studied a lot of other programming languages to train our brain previous. Let's look at the Artist Gallery example from a previous class. The artists name 'Mary Ellis' can easily be assigned the value of a String variable you can reuse in echo statements:

<? <br/> $artist_name = 'Mary Ellis';
echo '<font COLOR="red" face=Verdana>'.$artist_name.'</font>';
$artist_name = 'Wilbur Wright';
echo '<font COLOR="red" face=Verdana>'.$artist_name.'</font>'

Notice how the variable works to allow you to reuse the same exact PHP statement with different results (imagine tying that into a database, adding a loop to crunch through many artist names, and presenting a list of all artists in the ArtStar community from which a Web visitor can choose). Get to work trying out all the variable data types in the tutorial in as many creative ways you can imagine given your limited skills so far. Commit yourself to investigating whether this is the most effective way for you to learn and maintain motivation while doing so. Ask yourself, "hey... do I feel empowered and above intimidation?". I wish you that.

But, most of all: make some mistakes! Get used to saving your previously working version and butchering a new version with a wild attempt at something that might work. See what the browser does with it upon getting your result back from the PHP engine. Get used to the CNTL-Z keyboard chord to undue what you have done most recently. Get a rhythm until it feels hardwired in your brain. That's all intelligence is to me: the ability to do something from past experience (heavily emphasized by an associative memory). Birds are much more intelligent fliers than we are and yet look how small their brains are! We call can do this as well as we can tie our shoelaces. We just need to get the rhythm down. Now is the time to do that as we are going to go over a lot in this course and you like swimming downstream, frolicking in the water as you do so (seriously, I am suggesting a good five hours strong this week while you have the comfort of your own computer, your own favorite place, and your own speed at doing and learning - use our three hour time slot for this at least).

Mathematical Statements

Definition: Mathematical operators preform simple math calculations on the operands in an expression. Four basic (and universal) mathematical
operators are multiplication (*), division (/), subtraction (-), and addition (+).


An example of addition:
$my_canvas_count + 4 = 10

An example of subtraction:

$my_canvas_count - $your_canvas_count = 3

An example of multiplication:

$your_canvas_count * 10 = 30

An example of division:

$my_canvas_count / 2 = 3
There are many mathematical operators that all work in the same fashion (are placed in the flow of a statement as a single character that suggests a mathematical operation to take place). You should be able to determine the values both $my_canvas_count and $your_canvas_count contain before these operations took place. The answers would differ if the values were not fixed as they must have been. One of my favorite mathematical operators is the mod operator. In PHP (and many other languages), mod is represented by the '%' symbol. If you don't know what mod is, Google it! In a programming course like this, you must develop that reflex of searching for a term to understand it better. Or else, continue along half understanding something and seeing how far it will get you. I would do you a disservice by explaining every term sequentially (and boring those who already understand a term) or by giving you a link to it. I believe a huge part of becoming good and comfortable at languages like PHP is in gaining your own independence and swagger by repetitively proving to yourself you are self-sufficent and willing to fight through mistakes through a relentless iterative attempt at making examples work with the ideas you have in your head. What other mathematical operators can you find on the Web that are relevant to PHP? What operations can you perform using variables you create yourself using the rules exposed above? Try out as many combinations it takes for you to get your confidence up for next week's class together. Send me e-mail if you are patting yourself on your back. I'll send back a reassuring message from the road along with a sign of relief that you are succeeding.

Dive into some good PHP tutorials on the Web if you have some time leftover: And, spend some time meditating on your resolve and motivation and getting to understand how your brain works better so you can learn more effectively for yourself. Remember when your first grade teacher told you that math was important at that age for developing your brain to think for itself? Well, this process is important for all of us at any age so that we can all become better at participating in the emergent global consciousness that is being formed rapidly by this Web of which we are so amorous (for better or worse, eh?).

Diagramming the example of processing a submitted form

Comments - grey (606060)

HTML - black (000000)

CSS - magenta (F030C0)

Function declaration/use  - light blue (0060F0)

Object  - dark green (006000)

Property - brown (960)

Member (field) - dark blue (0000C0)

Method - red (FF0000)

Operator - orange (F06000)

Control structure - purple (603090)

Statement  - black (000000)

<?php include("../header_test.php") ?>

<?php include("../menu_test.php") ?>

    <div id="content_main">

           <div id="sectionhead">

                   OCEAN PICTURE OF THE DAY (OPOD)


           <?php include("../menu.php") ?>

            <div id="right_col">

            <div id="content">

            <table border="0" cellpadding="16" cellspacing="0" width="780" bgcolor="white">


                    <td><center><h1>Ocean Picture of the Day (OPOD)<br />



                    <td><div align="center"><strong>OPOD Photo Submission</strong></div></td>








            $image_folder = "http://www.theoceanproject.org/opod/upload";

            // Upload the image...

            if ($_FILES['upload']['size'] < 1000000000) {

            if (isset($_REQUEST['firstName'])) {

            if ($_FILES['upload']['error'] > 0) {

            echo "Return Code: ". $_FILES['upload']['error']."<br />";

                        } else {

                                    if (file_exists("upload/".$_FILES['upload']['name'])) {

                                    echo "<br />";

                                    echo '<span class="Exists">'."upload/".$_FILES['upload']['name'].' image file already exists. Please try again with a different filename'.'</span>' ;

                                    echo "<br />";

                        } else {

                                    if ($_FILES['upload']['sname'] != null) {

                                    $target = "upload/";

                                    $target = $target.basename( $_FILES['upload']['name']) ;


                                    if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {

                                                                                                                                                                                                                                                                 echo "<center><img height=375  src=http://www.theoceanproject.org/opod/upload/".$_FILES['upload']['name']." id='name' /></center>";

                                          echo "<center><h2>Successful Upload: ".basename($_FILES['upload']['name'])."</h2></center>";

                                          echo "<center>Your picture has been submitted for review. You will be notified via e-mail when your picture is going to be used as the OPOD. Thank you so much for your participation.</center>";

                                          echo "<p> </p>";

                        } else {

                                    echo "Sorry, there was a problem uploading your file."; }

                        } else {

                                    echo "Sorry, problem uploading your file: file name is null";


//Connect To Database






//connect to database

$con = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database!');

//select - use this database


//add information to the following database tables

$firstName=$_REQUEST['firstName']; //This value has to be the same as in the HTML form file

                                                                                                                                                            $lastName=mysql_real_escape_string($_REQUEST['lastName']); //This value has to be the same as in the HTML form file

                                                                                                                                                            $Email=mysql_real_escape_string($_REQUEST['Email']); //This value has to be the same as in the HTML form file

$sql1="INSERT INTO user (first,last,email) VALUES ('$firstName','$lastName','$Email')"; //form_data is the name of the MySQL table where the form data will be saved.

$City=mysql_real_escape_string($_REQUEST['City']); //This value has to be the same as in the HTML form file

$State=mysql_real_escape_string($_REQUEST['State']); //This value has to be the same as in the HTML form file

$Type=mysql_real_escape_string($_REQUEST['Type']); //This value has to be the same as in the HTML form file

$currentdatetime=date("Y-m-d H:i:s");


$sql2="INSERT INTO pic SET size='".$_FILES['upload']['size']."', date='$currentdatetime',town='$City',state='$State', image_type='$Type' , name='".$_FILES['upload']['name']."', location='$location'";

$textarea=mysql_real_escape_string($_REQUEST['textarea']); //This value has to be the same as in the HTML form file

$sql3="INSERT INTO submits (caption) VALUES ('$textarea')"; //form_data is the name of the MySQL table where the form data will be saved.                                                                                                                                               

            if (!mysql_query($sql1,$con)) {

                        die('Error: ' . mysql_error());


            if (!mysql_query($sql2,$con)) {

                        die('Error: ' . mysql_error());


            if (!mysql_query($sql3,$con)) {

                        die('Error: ' . mysql_error());


            echo '<br />';

            $result = mysql_query("SELECT MAX(id) AS id from submits");

            if($row = mysql_fetch_array($result)) {

                        $id = $row['id'];

                        $sql4 = mysql_query("UPDATE submits SET picture_id=".$id." WHERE id=".$id);

                        $sql5 = mysql_query("UPDATE submits SET user_id=".$id." WHERE id=".$id);

            if (!mysql_query($sql4,$con)) {



            if (!mysql_query($sql5,$con)) {








} else  {

            echo '<span class="Error">'."Invalid File".'</span>'."<br />";






            <td style="font-size: 10px">

                        <center><p style="font-size:12px"><a href="index.php" onClick="return (false);">View Today's OPOD Record</a></p>

                        <p style="font-size:12px"><a href="upload_form.php" onClick="return (false);">Submit An­other OPOD Picture</a></p></center>






        <div id="footer" style="left:464px;top:712px">



                <td style="background:transparent">

<?php include( "../footer_div.php") ?>