Programming Languages for Internet Applications

Nachum Danzig and Yonah Russ

Last Updated: 9/3/2003

  • Web Programming with Databases
  • Dynamic Web Pages are often used to provide a Database interface. Some common examples are:

    These examples are called "Extranet Database Applications". They allow the World to access some of the data located in Amazon.Com's Databases. The nature of this access requires a Server Side implementation of Dynamic Web Pages in other words- if you want your web page to use a database think Server Side Scripting.

  • Project
    1. In General
    2. Dynamic Web Pages can also be used to build "Intranet Database Applications." These allow many people inside an organization to use the same centrally located database from anywhere in the world. It is basically the same as an Extranet Application except that its use is not open to people outside the organization.

      In this course, you will be writing a complete Intranet Database Application. You will use HTML to create an interface. You will learn the Server Side Scripting language PHP which you will use to connect your HTML Interface to a MySQL database.

    3. Project Specifics (5763)
    4. There are many methods for teaching autistic children. One method called ABA (Applied Behavioral Analysis) takes a very scientific approach to the child's learning.

      Everything the child is taught is organized into Learning Programs. Each program consists of several components such as the materials required, the response expected from the child, the correction that is to be made in the case of an incorrect response.

      Each time a program is taught, it is repeated some number of times. Each repetition is called a Learning Unit. During the lesson the teacher records on a data sheet the correct or incorrect responses.

      This data is graphed and used to chart the child's progress. If the child succeeds in achieving 90% accuracy two days in a row, The Learning Program is changed for the positive- it is made harder, etc. If the child does not improve or shows dropping accuracy, the Learning Program is changed for the negative- it is made easier, etc.

      In an ABA school, two or more teachers may be teaching one child. All teachers who teach a child, record data on the same data sheets.

      With an Intranet Database Application:

  • PHP 1
  • PHP stands for "PHP: Hypertext Processor" it is one of the two major Server Side scripting languages. The other is ASP. PHP is partially based on Perl, C, and Java. You can find more information on PHP at the PHP Website:

    1. Inline Scripting
    2. As we said, one of the major advantanges to Server Side scripting languages is that you can include your code inline with the HTML of your web pages.

      If you haven't already guessed, we do this by enclosing our code in some special tags. This is called Escaping from HTML. This is similar to what we do for regular HTML Tags where we escape from the text. The only difference is that the tags we use to include our PHP code are meant to be interpreted by our web server unlike HTML Tags which are interpreted by our web browsers.

      1. Escaping from HTML <?php ..... ?>
      2. We must begin any of our inline PHP code with <?php

        We must end any of our inline PHP code with ?>

        Let's see an example:

        <html> <head> <title>My First PHP Example</title> </head> <body> <!-- Here I escape from the HTML inside the body and print something into the web page. It should show up like regular Body text --> <?php print "Hello World"; ?> <h1> <!-- Here I escape from the HTML inside the h1 and print something into the web page. It should show up like h1 text --> <?php print "Hello World"; ?> </h1> </body> </html>

        Click here to see how this example would appear in your browser.

      3. Statement Separation <?php statement 1; statement 2; ?>
      4. Just like it's "Parent" languages, statements in PHP are separated by semi-colons. Here is an example of multiple statements:

        <html> <head> <title>My Second PHP Example</title> </head> <body> <?php // btw: comments in PHP are like comments in C print "Hello World"; //Statement #1 print "<br>Hello World"; //Statement #2 /* Notice the <br> tag- without it I would have printed Hello WorldHelloWorld */ ?> </body> </html>

        Click here to see how this example would appear in your browser.

    3. Variables
    4. In any programming language, there are two types of data: Variables and Constants.

      Constants stay constant. In the PHP example above, the text which we gave the print function ("Hello World") was a constant. From the time the PHP script began to run until it finished, that text stayed exactly the same.

      Variables are more interesting. They are the heart of any programming language. When the programmer creates a variable named 'x', he tells the computer to set aside a piece of memory and call it 'x'. From then on he can assign a value to the variable 'x' and the computer will place that value in the memory set aside for the variable.

      1. Syntax
      2. Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

        Exactly how much memory the computer sets aside for a variable and how that memory is used is dependant on a characteristic of the variable called the Variable Type. We'll discuss types in a little bit.

        Let's see an example:

        <html> <head> <title>My Third PHP Example</title> </head> <body> <?php $var="Hello World"; //Assign the value 'Hello World' to the variable $var print "Aren't you glad I didn't print $var?\n"; //use the variable ?> </body> </html>

        Click here to see how this example would appear in your browser.

      3. Scope
      4. Variables necessarily have a characteristic called Scope, that is where in a program the variable name is recognized and where it isn't. When a variable is in scope, it's like Norm going to "Cheers" - a place where everybody knows your name. If you would scream Norm in The Underground, chances are people wouldn't have a clue what your were talking about. The same thing is true of a variable. If you try to use a variable in scope- no problem. If you try to use a variable out of scope, your program won't work if you're lucky. If you're unlucky, your program will work incorrectly and you won't know why.

        The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single Global scope. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. You can get around this if you really have to by declaring to PHP that you want to use the Global version of a variable.

        Let's see an example:

        <html> <head> <title>My Fourth PHP Example</title> </head> <body> <?php $var="Global"; //Assign the value 'Global' to the variable $var print "Printing the $var scoped variable.\n<br>"; //use the variable //write a function to change $var function Test_1() { $var="Local"; } Test_1(); //did my function change $var? print "Printing the $var scoped variable.\n<br>"; //write a better function to change $var function Test_2() { global $var; $var="Local"; } Test_2(); //did my new function change $var? print "Printing the $var scoped variable.\n<br>"; ?> </body> </html>

        Click here to see how this example would appear in your browser.

    5. Types
    6. PHP is a softly typed language but don't worry- that doesn't mean you loose points for typing loudly. What it does mean is that the programmer does not usually worry about the format which PHP uses to store data in memory. Where a programmer in Java or C would be required to tell the compiler what kind of memory to allocate, in PHP that is usually not necessary.

      On the other hand, it is still important to realize that data is stored in one of several formats (traditionally called types). PHP will automagically handle certain operations differently depending on the data types involved (similar to overloaded functions in C).

      1. Booleans
      2. Booleans are the simplest type. They express a truth value, and can contain either TRUE or FALSE.

        $var=TRUE; $var=true; $var=FALSE; $var=false;

        When other types are evaluated as truth values, they automatically get converted (aka casted) as a boolean. See each type for it's True/False values.

      3. Integers
      4. An Integer is a number of the set Z= {...-2, -1, 0, 1, 2...}.

        $var = 613; $var = -100;

        The size of an Integer is platform dependant. On 32 bit systems like ours, the maximum value is about 2 billion. PHP does not support unsigned integers.

        If you specify a value for an integer that is out of bounds, it will be converted to a float. The same is true if you perform an operation between integers that results in a value out of bounds for an integer.

        The integer 0 is considered false. Any non-zero integer is considered true.

      5. Floating Points
      6. Floating Point numbers (aka floats) are any numbers in the set R (real numbers).

        $var = 1.234; $var = 1.2e3; $var = 7E-10;

        The size of a float is platform dependant. The maximum value is commonly about 1.8e308 with a precision of 14 decimal places.

        The float 0.0 is considered false. Any non-zero float is considered true.

      7. Strings
      8. A string is a series of characters, each character taking up exactly 1 byte.

        PHP imposes no size limit on strings so they can be any size you want (until your webserver runs out of memory). Strings are enclosed in either single quotes (') or double quotes ("). As in Perl, strings enclosed within single quotes will be not be interpreted- they will be accepted as is. Strings enclosed in double quotes, on the other hand, will be interpreted and may contain variables or other special characters.

        Single Quote examples:

        print 'this is a simple string';
        print 'You can also have embedded newlines in strings
        this way';
        print 'Arnold once said: "I\'ll be back"';
        // output: ... "I'll be back"
        print 'I am trying to include at this point: \n a newline';
        // output: ... this point: \n a newline

        You may recognize some of the following special characters which can be used within a double quoted string:

        \nlinefeed (LF or 0x0A (10) in ASCII)
        \rcarriage return (CR or 0x0D (13) in ASCII)
        \thorizontal tab (HT or 0x09 (9) in ASCII)
        \$dollar sign
        \[0-7]{1,3}the sequence of characters matching the regular expression is a character in octal notation
        \x[0-9A-Fa-f]{1,2}the sequence of characters matching the regular expression is a character in hexadecimal notation

        Double Quote Examples(mixed with some more variable syntax):

        $beer = 'Heineken';
        print "$beer's taste is great"; // works, "'" is an invalid character for varnames
        print "He drank some $beers";   // won't work, 's' is a valid character for varnames
        print "He drank some ${beer}s"; // works

        The empty string "" as well as the string "0" are considered false. Any other string is considered true.

      9. Arrays
      10. An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees.

        Unlike the other types we discussed, arrays must be created or declared. To create an array we use the array construct as follows:

        //Numeric Keys(simple arrays like in C/Java)
        $var = array('a', 'b', 'c');
        print $var[0];  //outputs a
        print $var[1];	//outputs b
        //Change the starting key(index number)
        $var = array(1 => 'a', 'b', 'c');
        print $var[1];  //outputs a
        print $var[2];  //outputs b
        //Associative Arrays
        $var = array('Moshe Rabeinu' => 'Navi', 'Rashi' => 'Rishon');
        print $var['Moshe Rabeinu'];  //outputs Navi
        //mix up the key types - no problem
        $var = array(1 => 'a', 'Willy' => 'Wonka');
        //Two Dimensional (Simple) Arrays
        $var = array(
        //This is the same as:
        $col1 = array(1,2,3,4);
        $col2 = array(1,2,3,4);
        $col3 = array(1,2,3,4);
        $col4 = array(1,2,3,4);
        $var = array($col1, $col2, $col3, $col4);
        //Two Dimensional (Associative) Arrays
        $var = array( 'Joe Bloggs' => array( 'ID' => '00001',
                                             'STREET' => '123 Sesame St.',
        				     'CITY' => 'Yourtown',
        				     'COUNTRY' => 'Nowhere Land')
        print $var['Joe Bloggs']['ID']; //outputs 00001

        An array with 0 elements is considered false. Any other array is considered true.

  • PHP 2
    1. Operators
    2. Operators make the programmer's life easier. If it weren't for operators, even the simplest action would require a full fledged function.

      We will digress to briefly discuss functions. A function is basically a set of actions which is executed whenever the function is called. Functions can accept parameters and return values. For instance, a function 'add()' might accept two parameters 'a' and 'b' ( now we have add(a,b) ) and the function might return a value 'c' ( c=add(a,b) meaning c=a+b).

      We see directly from this example how operators make the programmer's job easier. It is much easier to write a+b as opposed to add(a,b).

      On a deeper level, I challenge anyone in the class to write the function add(a,b) without using any of arithmetic operators we learn in class. Anyone with a working function by the end of the semester will recieve a bonus on their final grade.

      Luckily for us, most of the operators we would want are already part of php.

      1. Arithmetic (+, -, *, /, %)
      2. The arithmetic operators will do what you expect them to most of the time. '+' adds, '-' subtracts, '*' multiplies, '/' divides, '%' performs the modulus operation- that is (a % b) divides a by b and returns the remainder.

        The precedence of the operators is the same as you would expect: (*,/,%) are performed first followed by (+,-) so that 1+5*3 is the same as 1+(5*3)=16. Even if the precedence of the operators says that your equation should work, you should still put parenthesis in the correct places to make your code more readable.

      3. String
      4. There is one main String Operator which is the '.'. The '.' Operator performs string concatenation which means that it glues strings together. In Java this is done with the '+' operator. For example:

        $var = "Hello"." "."World";
        print $var; //outputs Hello World
        $var = $var."!";
        print $var; //ouputs Hello World!
      5. Assignment (=, +=, -=, *=, /=, .=)
      6. We've been using Assignment Operators since we learned about variables. '=' is the simplest of the Assignment Operators. It takes the value on the right hand side and assigns it to whatever is on the left hand side.

        This brings up the issue of Left Hand Values and Right Hand Values. A Left Hand Value is anything that can have a value assigned to it. A Right Hand Value is anything with a value. Every Left Hand Value is a Right Hand Value but NOT every Right Hand Value is a Left Hand Value.

        $var = 5;  //works - $var is a LHV, 5 is a RHV
        5 = $var;  //BAD! - 5 is a RHV only, I can't assign it a value
        $a = $b = $c = 5; /*    works, I assign RHV 5 to LHV $c which becomes a
        			RHV to be assigned to $b... */

        Now that you know that the '=' sign is an Operator, we understand how we can write something like $var = $var."!"; in the example above. The '.' Operator has higher precedence than the '=' operator. As a matter of fact, since we almost always want the entire RHV to be calculated before it's assigned we have to give the '=' Operator (and all the other Assignment Operators) very low precedence. If you have a precedence problem or you want to be sure that something is interpreted in a specific order, use parenthesis

        Other than the '=' Operator, we have some more complex Assignment Operators. All of them follow the same modus operandi. 'a += b' translates into a = a + b for example:

        $a+=6;  // $a = 5 + 6
        print $a; //outputs 11

        The same is true for the '-=', '*=', '/=', and '.=' Operators.

      7. Incrementation Operators(++,--)
      8. Incrementation Operators are just shortcuts for incrementing a value. The ++ operator is the equivalent of adding 1 to a value while the -- operator is the equivalent of subtracting 1 from a value. For example:

        $a++;     //$a=$a+1; OR $a+=1;
        print $a; //outputs 6
        $a--;     //$a=$a-1; OR $a-=1;
        print $a  //outputs 5

        An important thing to note about incrementation operators is that they are unary operators, meaning that they only have one operand. The operators + and - can also be unary operators, for example -5 meaning negative 5. In this case the - is the unary operator - and the 5 is its only operand. In the case of 5 - 4, on the other hand, we are using the binary operator - and its two operands 5 and 4.

        Another important thing to note about incrementation operators have both a prefix syntax and a postfix syntax. What does that mean? The other unary operator we just discussed, -, only has a meaning when you prefix it to a number; -5 means negative 5 while 5- is meaningless. With incrementation operators, this is not the case. --$a means something slightly different from $a--. The easiest way to see this is in an example:

        print $a++;  //outputs 5, THE SAME AS: print $a; $a=$a+1; 
        print $a;    //outputs 6
        print ++$a;  //outputs 7, THE SAME AS: $a=$a+1; print $a;
      9. Comparison (==,!=, <, >, <=, >=, ?:)
      10. Comparison Operators return Truth Values.

        The operator ?: is a special kind of operator called the Ternary Operator. It takes three operands and is used as follows:

        $b = ($a > 0) ? "Positive" : "Negative";
        print $b; //outputs Positive

        Read the above as "If ($a > 0) then assign 'Positive' to $b else assign 'Negative' to $b"

        Beware using the comparison operators on strings. You might get unexpected answers. For instance if you compare the number 0 to the string "0000000000" php will consider them the same because it converts the string to a number and the numbers are equal. If you compare the string "01" and "001", they will also match for the same reason- that numerically they are equal. The correct way to compare strings is by using the function strcmp() which we'll learn later.

      11. Logical (!, &&, ||)
      12. Logical Operators are used to manupulate Truth Values. The three basic logical operators are:

        The following truth table shows all the possible combinations of output(0 is false, 1 is true):
        0 0 1 0 0
        0 1 1 0 1
        1 0 0 0 1
        1 1 0 1 1

    3. Conditionals
      1. if(true){statements}elseif(true){statements}else{statements}
      2. Conditionals allow the programmer to perform different sets of statements based on the values of relavent parameters. The syntax is:

        if(Truth Value == TRUE)
          //statements to do seperated by ';'
        elseif(Truth Value == TRUE)
          //statements to do seperated by ';'
          //statements to do seperated by ';'

        Using an if statement does not require using an elseif statement nor does it require using an else statement.

        You may have as many elseif statements as you want following an if statement.

        You may only have ONE else statement following an if statement.

        Let's see an example:

        <?php $a=-1; if($a>0) { print "Positive"; } elseif($a == 0) { print "Zero"; } else { print "Negative"; } ?>

        Click here to see how this example would appear in your browser.

      3. switch($var){case x: statements; break; default: statements; break;}
      4. Switch Case statements are like if statements that have been optimised for the situation where the programmer wants to test the same expression for many possible values. The syntax is:

        switch(RHV1)  //if RHV1 ==
           case RHV2:  //this RHV then
           //do the folowing statements seperated by ';' 
             break;   //leave the switch
           case RHV3:  
           case RHVn:
           default:   //if nothing else matches do this
             //do the folowing statements seperated by ';' 

        Any expression can go inside the switch. The computer goes through the cases in order looking for a case that returns TRUE for the comparison ((expression from switch) == (value from case)).

        If the computer reaches a case which matches, it performs the set of statements beneath it until it finds a break statement. BEWARE if you forget to put a break statement at the end of your case the computer will continue with the statements under the next case statement. If this is used properly, it is a feature- not a bug. See the example above.

        The programmer can also use a default case. This case is put at the end of all the cases and it will always match in case no other cases matched.

        Let's see an example:

        <?php $lucky_number=7; switch($lucky_number) { case -1: case -2: case -3: //for all these cases do this print "Don't be so negative!"; break; //the break tells me to leave the switch case 0: print "You're a 0!"; break; case 1: print "You're Number 1!"; break; case 2: print "Two's Company!"; break; case 3: print "Three's a crowd!"; break; case 4: print "Why have you 4saken me?"; break; case 5: print "High 5!"; break; case 6: print "Pickup Stix!"; break; case 7: print "That's MY Lucky Number!"; break; case 8: print "Crazy Eights!"; break; case 9: print "Only cats have 9 lives!"; break; } ?>

        Click here to see how this example would appear in your browser.

    4. Loops
    5. Loops allow the programmer to perform the same set of statements a multiple number of times. The most common problem with loops is the infinite loop in which the computer is caught in a loop which never ends. In order to prevent infinite loops, we say that every loop must have three elements:

      1. Initialization
      2. Initialize the variables on which the loop is dependant(usually a variable used in the continue condition).

      3. Continue Condition
      4. In each iteration, this condition is checked to see whether or not the computer should perform another iteration. If the condition is found to be true, then the loop continues.

      5. Incrementation
      6. In each iteration, something must be incremented to bring the loop closer to completion(usually the variable used in the continue condition).

      There are several ways to implement loops:

      1. while(true){statements}
      2. The while loop is the simplest of all loops. It's syntax is as follows:

        while(continue_condition == TRUE)
           //do some statements seperated by ';'

        The Initialization usually takes place before the while loop actually begins. The Continue Condition is located within the parenthesis. As long as that condition evaluates to TRUE, the loop will continue to iterate. The Incrementation in a while loop usually takes place at the beginning or the end of the loop but it can take place anywhere inside.

        Let's see an example:

        <?php //Initialization $i=1; //Continue Condition while($i<=10) //Is $i <= 10???? { print "$i\n"; //print $i //Incrementation $i++; } ?>

        Click here to see how this example would appear in your browser.

      3. do{statements}while(true);
      4. A do..while loop is basically the same as a while loop except that the continue condition is only checked at the end of each iteration and therefore the set of commands within the loop will always be executed at least once. For example:

        <?php print "<br>Doing first loop<br>"; //Initialization $i = 1; do { /* There is no Incrementation in this loop */ print $i; } while ($i>1); //Continue Condition print "<br>Doing second Loop<br>"; //Initialization $i = 1; do { print "$i\n"; $i++; //Incrementation } while ($i<=10); //Continue Condition ?>

        Click here to see how this example would appear in your browser.

      5. for(init;continue;increment){statements}
      6. A for loop is more complex than the while style loops. It contains all three elements of a loop in it's opening clause. It's syntax is as follows:

        for(Initialization;Continue Condition;Incrementation)
          //statements seperated by ';'

        When the for loop begins it performs the initialization in the first section of the opening clause and checks the Continue Condition. If the Continue condition returns TRUE then the program performs the statements in the loop. When it reaches the end of the iteration, it performs the incrementation in the third section of the opening clause and checks the Continue Condition again.

        Let's see an example:

        <?php for($i=1;$i<=10;$i++) { print "$i\n"; } ?>

        Click here to see how this example would appear in your browser.

      7. foreach(array as $value){statements}
      8. The foreach loop is optimized for looping through arrays. Since arrays in PHP have a complex syntax, the foreach loop has two syntaxes.

        The simple syntax is most usefull for numerically indexed arrays where the index of the array is not of any significance to the program. In such a situation, a programmer would most likely have used a for loop with an incremented variable to reference each index of the array.With the foreach loop, there is no need for an extra variable to track the index of the array because it is done internally.

        With a regular for loop the programmer would also have to reference the element of the array using array syntax, ie. $array[$index]. With a foreach loop, the value of each element is automagically assigned to a variable for use within the loop.

        The simple syntax of a foreach loop is as follows:

        foreach($array_name as $current_element_value)
          //statements seperated by ';'

        The corresponding for loop would look like:

          //statements seperated by ';'

        Let's see an example:

        <html> <head> <title>My Fifth PHP Example</title> <body> <table border="1" cellpadding="3"> <tr> <td>Date</td> <td colspan="10">Correct/Incorrect Answers</td> <td>% Correct</td> </tr> <?php //escape into php $results=array( array('21/1',0,0,1,1,1,1,1,1,1,1), array('22/1',0,1,1,1,1,1,1,1,1,1), array('23/1',0,1,1,1,1,1,1,1,1,1), array('24/1',0,0,0,0,0,1,1,1,1,1), array('25/1',0,0,0,0,0,1,1,1,1,1), array('26/1',0,1,1,1,1,1,1,1,1,1), array('27/1',0,0,0,0,0,1,1,1,1,1) ); foreach($results as $date_record) { $total=-1; $correct=0; foreach($date_record as $value) { if($total<0) { $total++; continue; } elseif($value) { $correct++; } $total++; } if(( $correct / $total)>=.9) { $color="lightgreen"; } elseif(( $correct / $total)<=.6) { $color="red"; } else { $color="yellow"; } print "<tr bgcolor=\"$color\">\n"; foreach($date_record as $value) { print " <td>$value</td> "; } print "<td>".($correct/$total)."</td>\n"; print "</tr>\n"; } ?> </table> </body> </html>

        Click here to see how this example would appear in your browser.

      9. foreach(array as $key=>$value){statements}
      10. When the programmer is interested in the index or key of the array as well as the value of the element, the complex foreach syntax is a good choice. It will store the value of the current key and the current element in variables for use inside the loop.

        The complex syntax of a foreach loop is as follows:

        foreach($array_name as $key => $current_element_value)
          //statements seperated by ';'

        There is NO corresponding for loop.

        Let's see the same example as above:

        <html> <head> <title>PHP Example</title> <body> <table border="1" cellpadding="3"> <tr> <td>Date</td> <td colspan="10">Correct/Incorrect Answers</td> <td>% Correct</td> </tr> <?php //escape into php $results=array( '21/1' => array(0,0,1,1,1,1,1,1,1,1), '22/1' => array(0,1,1,1,1,1,1,1,1,1), '23/1' => array(0,1,1,1,1,1,1,1,1,1), '24/1' => array(0,0,0,0,0,1,1,1,1,1), '25/1' => array(0,0,0,0,0,1,1,1,1,1), '26/1' => array(0,1,1,1,1,1,1,1,1,1), '27/1' => array(0,0,0,0,0,1,1,1,1,1) ); foreach($results as $date => $date_record) { $total=0; $correct=0; foreach($date_record as $value) { if($value) { $correct++; } $total++; } if(( $correct / $total)>=.9) { $color="lightgreen"; } elseif(( $correct / $total)<=.6) { $color="red"; } else { $color="yellow"; } print "<tr bgcolor=\"$color\">\n"; print "<td>$date</td>"; foreach($date_record as $value) { print " <td>$value</td> "; } print "<td>".($correct/$total)."</td>\n"; print "</tr>\n"; } ?> </table> </body> </html>

        Click here to see how this example would appear in your browser.

        NOTE: This way we save ourselves making total equal -1 and the continue which we needed so we don't mess up and count the date as one of the answers.

      11. break, continue
      12. The break statement simply exits the current loop or switch statement. For example:

          print $a++;

        break also takes a numeric argument which is the number of levels to exit from. In the above example we could also have typed 'break 1;' to break out of one level of loops.

        The continue statement skips to the next iteration of a loop. Like the break statement, it also works inside switch statements but you should never use it there because it doesn't make sense.

        Let's see an example:

          print $a++;
    6. PHP has many functions for doing many things. See for a complete reference. Here I will give you two simple examples of reading and writing to text files. <?php $filename = 'test.txt'; $content = "Add this text to the file\n"; // Make sure the file exists and is writable first. if (is_writable($filename) == FALSE ) { echo "The file $filename is not writable"; exit; } // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename , 'a')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $somecontent ) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename)"; fclose($handle); } ?> fread() reads up to length bytes from the file pointer referenced by handle. Reading stops when up to length bytes have been read, EOF (end of file) is reached, (for network streams) when a packet becomes available, or (after opening userspace stream) when 8192 bytes have been read whichever comes first. Returns the read string or FALSE in case of error. <?php // get contents of a file into a string $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); ?>
  • Getting User Input
    1. HTML Forms
    2. An HTML Form allows a user to pass input through the web browser to the web server where it can be processed. HTML Forms make it possible to build an Intranet Database Application, specifically they compose the User Interface of the application.

      A form is defined with the <form> tag. A form must have both an opening tag and a closing tag. All form elements that belong to a form must be enclosed within the opening and closing tags. You may have more than one form on a page. You may NOT have a form within a form.

      In the opening form tag, you must define two attributes for the form to work properly, the method and the action.

      The action defines where to send the information for processing. In our case this will be a PHP page.

      The method defines how to send the information. This can be either get or post.

      In most cases we will use the post method although sometimes it is useful to send information to pages via the get method. Moreover, if you want to get to a specific php page via a link from a non-form html page, you will have to use get.

    3. PHP and HTML Forms
    4. Really there is very little to know about using PHP with forms. PHP was made for this so it doesn't get easier. Three easy steps:

      1. Make your form in HTML
      2. Remember that the names you give your form elements will be the variable names in PHP with which you can access the values of the input. That means you MUST use valid PHP variable names.

      3. Write a PHP page that uses the input variables
      4. Point your form at your PHP page

      Here is an example of the source code of a form:

      <html> <head> <title>Sample Form </title> </head> <body> <h1>Sample Form</h1> <P>Please enter a name </p> <form action="displayhello.php" method="POST" > Name <input type="text" name="username" size="10" maxlength="8" > <input type="submit" value="Click me!"> </form> </body> </html>

      We see that the form tag has attribute action defining the php page which is to receive the data entered (displayhello.php) and the method how it receives it (POST). You can also see two input tags. The first one is used to create an input window on the web page for the user to type in his name. The second is used to create a button for him to submit the data to the php page. You will only have one button per form. More about input type in the next section.

      Now let's see the php page that handles the data.

      <?php print "<html>"; $name = $_POST["username"]; print "<body>"; print " hello $name"; print "</body>"; print "<html>";

      Notice that the variable named in the form was "username". So, in the php page we get the data the user typed in from the variable named "username" also. For security reasons php stores this information in an array. The $_POST array is used for post requests and the $_GET array is used for get requests. Since we sent the information via a post, we have to look for it in the $_POST array. You will notice that the array is an associative array, so we locate our data by its name, not by index 0.

      Here is another php example which could be used with the sample form. It mails an email:

      <?php print "<html>"; $name = $_POST["username"]; $sub="testmessage"; $message=" Name: $name "; mail("",$sub,$message,"From: ESP Feedback <>\n"); print "<body>"; print " Hello $name again. We sent mail to Bill Gates."; print "</body>"; print "<html>";

      Test the sample form

    5. Form Elements
    6. Form Elements define the types of information for processing by the web server. There are several types of Form Elements which, together, can be used to build a fully functional interface:

      1. Text Fields - For entering one line of text
      2. To put a Text Field into our page we place the following input tag inside our form tags:

        <input type="text" name="firstname">

        This puts a default sized text field on the web page(type="text"). It gives the field the name 'firstname' which means that when we send the information to our PHP page, we will send it inside the variable $firstname.

        In addition we could use the value attribute to give our text field a default value. We could use the size attribute to define how many characters wide the text field should be. We could use the maxlength attribute to define how many characters the field is willing to accept. For example:

        <input type="text" name="country" size="3" maxlength="2" value="IL">
      3. Textarea Fields - For entering multiple lines of text
      4. To put a Textarea Field into our page we place the following textarea tag inside our form tags:

        <textarea rows="10" cols="30" name="comment">Default Text</textarea>

        This puts a 10 row by 30 column textarea on the web page. It gives the field the name 'comment' which means that when we send the information to our PHP page, we will send it inside the variable $comment. NOTE: A textarea must be opened an closed. Default text may be placed in between the opening and closing tags.

      5. Select Boxes - For selecting a choice from a list
      6. To put a Select Box on our web page we place the following series of tags inside our form tags:

        <select name="area_code"> <option value="Cellcom">058</option> <option value="Cellcom">052</option> <option value="Cellcom">053</option> <option value="Cellcom">064</option> <option value="Pelephone">051</option> <option value="Pelephone">056</option> <option value="Pelephone">050</option> </select>

        This creates a drop down menu with 7 options. The options that appear in the list are written in between the option tags. Which ever choice is selected, the VALUE of that option is put into the variable, in this case $area_code.

        We could also have used the multiple attribute of the select tag to allow multiple choices to be selected(multiple="true").

      7. Radio Buttons - For selecting one of a limited number of choices
      8. To put a set of Radio Buttons on our web page we place the following set of input tags inside our form tags:

        Male: <input type="radio" name="Sex" value="Male" checked> Female: <input type="radio" name="Sex" value="Female"> Male: Female:

        NOTE: Both input tags have the same name. This is what connects them so that only one of the choices can be selected at a time. Which ever one is checked when the form is sent to be processed will send it's value inside the variable. The checked attribute selects a default selection.

      9. Checkboxes - For selecting one or more of a limited number of choices
      10. To put a Checkbox on our web page, we put the following input tag inside our forms tags:

        Check Me <input type="checkbox" name="user_listens_to_anything_we_tell_him" value="yes"> Check Me

        We can also use the checked attribute here to make default selections.

      11. Buttons - For submiting or reseting the form
      12. To put a button in our web page we use the input button tags. There two button types: submit, and reset.

        A submit button will take the information in the form and send it to be processed by the action defined by the form using the method defined by the form. Without at least a submit button, your form won't do anything.

        A reset button will reset all the values of the fields in your form.

        Let's see an example:

        <input type="submit" value="Click Me!">

      Let's see a real life example:

      Hotmail's Compose Screen

      This page is littered with forms and form elements. The only form element missing is the Radio Button.

  • Databases
    1. Introduction
    2. What is a Database? According to the official definition, a database is any organized body of related information. Several examples might include a dictionary, a telephone book, a shopping list, etc.

      The most prevalent type of database is the relational database, a tabular database in which data is defined so that it can be reorganized and accessed in a number of different ways. The relational database was invented by E. F. Codd at IBM in 1970.

    3. Relational Database Tables
    4. In a relational database is a set of tables containing data fitted into predefined categories. Each table (which is sometimes called a relation) contains one or more data categories in columns. Each row contains a unique instance of data for the categories defined by the columns.

      For example, a typical business order entry database would include a table that described a customer with columns for name, address, phone number, etc. It might look as follows:

      NameAddressPhone Number
      Yonah Russ123 Sesame Street01-234-5678

      Another table would describe an order: product, customer, date, sales price, etc. It might look as follows:

      ComputerYonah Russ10/02/03$1000

      One user of the database could obtain a view of the database that fitted the user's needs. For example, a branch office manager might like a view or report on all customers that had bought products after a certain date. A financial services manager in the same company could, from the same tables, obtain a report on accounts that needed to be paid.

    5. Data Modeling
      1. Entities
      2. The first step in modeling a service or process, is to identify the entities involved in that process. An entity is a thing or object of significance to the business, whether real or imagined, about which the business must collect and maintain data, or about which information needs to be known or held. An entity may be a tangible or real object like a person or a building; it may be an activity like an appointment or an operation; it may be conceptual as in a an organizational unit.

        Whatever is chosen as an entity must be described in real terms. It must be uniquely identifiable. That is, each instance or occurrence of an entity must be separate and distinctly identifiable from all other instances of that type of entity.

        For example, if we were designing a computerized application for the care of plants in a greenhouse, one of its processes might be tracking plant waterings. Within that process, there are two entities: the Plant entity and the Watering entity. The Plant has significance. Each Plant is uniquely identified by its biological name, or some other unique reference to it. A Watering has significance as an application of water to a plant. Each Watering is uniquely identified by the date and time of its application.

      3. Attributes
      4. After you identify an entity, then you describe it in real terms, or through its attributes. An attribute is any detail that serves to identify, qualify, classify, quantify, or otherwise express the state of an entity occurrence or a relationship. Attributes are specific pieces of information which need to be known or held.

        An attribute is either required or optional. When it's required, we must have a value for it, a value must be known for each entity occurrence. When it's optional, we could have a value for it, a value may be known for each entity occurrence. For example, some attributes for Plant are: description, date of acquisition, flowering or non-flowering, and pot size. The description is required for every Plant. The pot size is optional since some plants do not come in pots. Again, some of Watering's attributes are: date and time of application, amount of water, and water temperature. The date and time are required for every Watering. The water temperature is optional since we do not always check it before watering some plants.

        The attributes reflect the need for the information they provide. In the analysis meeting, the participants should list as many attributes as possible. Later they can weed out those that are not applicable to the application, or those the client is not prepared to spend the resources on to collect and maintain. The participants come to an agreement on which attributes belong with an entity, as well as which attributes are required or optional.

        The attributes which uniquely define an occurrence of an entity are called primary keys. If such an attribute doesn't exist naturally, a new attribute is defined for that purpose, for example an ID number or code.

      5. Relationships
      6. After two or more entities are identified and defined with attributes, the participants determine if a relationship exists between the entities. A relationship is any association, linkage, or connection between the entities of interest to the business; it is a two-directional, significant association between two entities, or between an entity and itself. Each relationship has a name, an optionality (optional or mandatory), and a degree (how many). A relationship is described in real terms.

        Rarely will there be a relationship between every entity and every other entity in an application. If there are only two or three entities, then perhaps there will be relationships between them all. In a larger application, there are not always relationships between one entity and all of the others.

        Assigning a name, an optionality, and a degree to a relationship helps confirm the validity of that relationship. If you cannot give a relationship all these things, then perhaps there really is no relationship at all. For example, there is a relationship between Plant and Watering. Each Plant may be given one or more Waterings. Each Watering must be for one and only one specific Plant.

      7. Entity Relationship Diagrams
      8. A picture is worth 1000 words. We can define a schema for describing the Entity Relationship model in the form of a diagram.

        First let's define the symbols for each part of the model.


        Here is an example ER Diagram:

    6. Accessing a Database
    7. Databases are built using the client server structure. A program that wishes to use a database must implement a client. In our case, we will use the functions existing in PHP for this purpose. The client implementation must connect to the database server and perform queries. A query tells the database server what information to retrieve and how to report it. A query can also be used to insert, update, or delete data from the database.

      Queries are written using Structured Query Language also known as SQL. All versions of SQL are basically the same although each server has its own extensions and syntax which may give it certain advantages and/or disadvantages.

      We will be using the MySQL database server. It is free, fast, and very well known.

      1. Creating Tables
      2. Everything in the database is stored in tables. The tables are created using SQL queries. In the creation of a table we define the name and type of each field(column). We also place constraints on the fields in order to ensure the validity of the data, ie. a field for the age of a person could not have a negative number as a value. Here is the CREATE TABLE syntax:

        CREATE TABLE <new table name> (
        	fieldname fieldtype (options),
        	fieldname2 fieldtype2 (options2),

        Create table creates a new table in the currently connected database. new table name may only include alphanumeric characters and no white space ([A-Za-z0-9_]). For field specifics see field descriptors later in this file. Let's see an example:

        CREATE TABLE example_table (
          id int(10) DEFAULT '0' NOT NULL auto_increment,
          status tinyint(3),
          username varchar(20),
          email varchar(255),
          description text,
          datecreated datetime,
          lastupdated datetime,
          PRIMARY KEY (id)

        This creates a table called example_table which looks like:


        Aside from being able to visualize the table from it's CREATE command, we also need to understand the field types. Otherwise, we might try to put illegal data into one of the fields when we write our program.

      3. Field Types
      4. All fields allow for a "NOT NULL" option, and a DEFAULT value

        TINYINT unsigned,auto_increment Signed: -128 to 127
        Unsigned: 0 to 255
        SMALLINT unsigned,auto_increment Signed: -32,768 to 32,767
        Unsigned 0 to 65,535
        MEDIUMINT unsigned,auto_increment Signed: -8,388,608 to 8,388,607
        Unsigned 0 to 16,777,215
        INT unsigned,auto_increment Signed: -2,147,683,648 to 2,147,683,647
        Unsigned: 0 to 429,496,967,295
        VARCHAR(#)   4-255 Stores up to 255 characters (fields adjust to max. value size) (use BLOB for case sensitivity)
        TEXT   Stores (almost) unlimited amount of data but reduces efficiency of querying, etc. (use BLOB for case sensitivity)
        DATE (yyyy-mm-dd) 1000-01-01 to 9999-12-31
        TIME (hhh-mm-ss) -838:59:59 to 838:59:59
        DATETIME (yyyy-mm-dd hh-mm-ss) 1000-01-01 00:00:00 to 9999-12-31 23:59:59
        YEAR (yyyy) 1901 to 2155
        TIMESTAMP(#) # determines display 2,4,6,8,10,12,14 pass nothing for this field, it is automatically updated to the current system time
        1970-01-01 to 2037
      5. Adding Data
      6. Every table in a database represents some relationship. Each row in a table represents an instance of that relationship. For example, consider the following table:

        program_id name description learning_units last_run
        1 Ownership Show John an object. He must say "sheli" if it's his. 20 Sunday Feb. 16, 2003

        This table describes information relating to a learning program. In order to add a new learning program to the table I use an INSERT query. Here is the INSERT syntax:

        INSERT INTO <table> (<fieldlist>) VALUES (<values>);

        Enters a new row into <table>. In the case of a <fieldlist> the values for the given fields and in the given order are entered. When no field list is specified all fields must have a supplied value (even if that value is NULL) and values will be inserted in the order they appear in the table's field list given by mysqlshow.

        Note: If a field is defined as auto_increment then "NULL" should be passed. Dates and times can be in a number of formats but the recommended format is: yyyy-mm-dd hh:mm:ss. Let's see an example:

        INSERT INTO learning_programs (program_id,name,description,learning_units,last_run)
        VALUES (NULL,'Matching','Put the blocks in the matching holes',15,NOW());

        This query should result in the following table:

        program_id name description learning_units last_run
        1 Ownership Show John an object. He must say "sheli" if it's his. 20 Sunday Feb. 16, 2003
        2 Matching Put the blocks in the matching holes. 15 ה' מרץ 27 15:15:56 IST 2003
      7. Deleting Data
      8. Deleting data is also done via SQL queries. Here is the syntax:

        DELETE FROM <table> ( WHERE <field> <operator> <value>);
        Deletes rows from <table>. By itself, the DELETE query will delete all the rows in the table. In order to specify the rows which are to be deleted we add the WHERE clause. Where ever the WHERE clause matches a row, the row will be deleted. For example:

        DELETE FROM learning_programs WHERE program_id = 1;

        This query should result in the following table:

        program_id name description learning_units last_run
        2 Matching Put the blocks in the matching holes. 15 ה' מרץ 27 15:15:56 IST 2003

        Note the use of the '=' operator. SQL has several operators which we must learn. Many of them are the same as in PHP.

      9. Operators
      10. All expressions can be grouped with parentheses ie. ( (user='username') AND (pass='password') )
        Logical Operators
        AND or &&   evaluates to 1 if both sides are true
        OR or ||   evaluates to 1 if either side is true
        NOT or !   evaluates to 1 if following side is false
        Comparison Operators
        = a = b true if operands are equal
        !=, <> a != b, a <> b true if operands are not equal
        < , <= a < b, a <= b true if less than, or if less than or equal to
        > , >= a > b, a >= b true if greater than, or if greater than or equal to
        LIKE a LIKE b Pattern Match: true if a matches b
        NOT LIKE a NOT LIKE b Pattern Match: true if a does not match b
        IS NULL a IS NULL true if a is NULL
        IS NOT NULL a IS NOT NULL true if a is not NULL

        When using the Pattern Matching operators, LIKE, etc. you can use the wildcard '%' to match anything. We will see examples as we continue.

      11. Updating Data
      12. Don't think you have to delete a row and insert a new one when you want to change something in the database. Here is the UPDATE syntax:

        UPDATE <table> SET <field1>=<value1>,<field2>=<value2>, ... ( WHERE <field> <operator> <value>)

        Updates all rows in <table> setting each field equal to its corresponding value in the "SET list" where ever a row matches the WHERE clause. If no WHERE clause is provided then all rows are updated. For example:

        UPDATE learning_programs SET name='Matching Blocks'  WHERE program_id=2;

        This query should result in the following table:

        program_id name description learning_units last_run
        2 Matching Blocks Put the blocks in the matching holes. 15 ה' מרץ 27 15:15:56 IST 2003
      13. Retrieving Data
      14. Retrieves specified fields in the given number of rows (default is all matching) starting at the given row (default is 0) from <table> where records match,returned in the specified order (defaults to database structure, not necessarily input order).

        The field list may contain a number of specialized variants including, *, COUNT(*). The "AS" keyword allows a field name to be aliased to another, for example: SELECT verylongfieldname AS vlfn makes the values in "verylongfieldname" appear as values in a field named "vlfn" instead.

        Fields may be selected from multiple tables in the same query, but may require a field to be related in each table. When selecting from multiple tables non-unique fields will conflict if the table name is not included, for example if you are selecting from table1 and table2 and both have an "id" field then the field(s) you are selecting and the field(s) you are querying will need to be stated completely, such as and

        SELECT <field1>(,<field2> AS <newfieldname>) 
        FROM <table1>(,<table2>) 
        ( WHERE <field> <operator> <value> ) 
        ( ORDER BY <fieldlist> [DESC] ) 
        ( LIMIT <startrow>,<numrows> )

        Let's see some examples:

        SELECT * FROM learning_programs;
        SELECT program_id,name,description FROM learning_programs;
        SELECT program_id,name,description FROM learning_programs 
               WHERE learning_units>10;
        SELECT program_id,name,description FROM learning_programs 
               WHERE learning_units>10 ORDER BY learning_units;
        SELECT COUNT(*) FROM learning_programs;
        SELECT program_id FROM learning_programs WHERE name LIKE 'M%';
        SELECT program_id FROM learning_programs WHERE name LIKE 'M%' LIMIT 0,5;

        Many times you will have to retrieve information from several tables. Let's see an example:

        SELECT AS userid, AS useremail, 
               table2.lastupdated AS last_login FROM table1,table2 
               WHERE (( > 10 AND LIKE '%@%') AND 
                      ( = 
               ORDER BY email DESC LIMIT 0,20;
    8. Using the Database
    9. To use the database server we must first connect to the database server and select which database to use. Then we can send our queries to the database and retrieve the results. After processing the results we must disconnect from the database. To perform all these tasks, we use PHP functions.

      1. MySQL Functions
      2. Connect to the database using mysql_connect or mysql_pconnect. mysql_pconnect() acts very much like mysql_connect() with two major differences.

        First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

        Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()- instead they will timeout after remaining idle for a defined amount of time).

        The syntax of both is as follows:

        $link = mysql_pconnect ( server, username, password );

        The function returns a handle to the connection which can be used with other functions.

    Here is an example of a trivial message board
    Complete example in php mysql selecting data from a database <?php /* ob_start(); print "hello"; function master_redirect($newURL) { header('Location:' . $newURL); } master_redirect(""); */ $serverName = ""; $serverName = ""; $username = "User9"; $password = "sesame"; $dbName = "Kamione_IP9"; $ret = array(); //connect to the server /*1*/ $connection = mysql_connect($serverName, $username, $password) or die("HELP! BAD CONNECTION"); //choose the database within this server /*2 */ mysql_select_db($dbName); // define what the query will be /*3*/ $sql= "SELECT * from students"; // run the query /*4*/ $ret = mysql_query($sql, $connection) or die("HELP! BAD SQL = '" . $SQL . "'"); // get one partticular item from the information received /*5*/ $data= mysql_result($ret,1,0); /*6*/ print "&nbsp; $data"; /*5*/ $data= mysql_result($ret,1,1); /*6*/ print "&nbsp; $data"; /*5*/ $data= mysql_result($ret,1,2); /*6*/ print "&nbsp; $data"; mysql_close($connection); ?>