In the beginning, man created the Internet. And the Internet was basically text and had to be updated manually. And the programmers said "There shall be Dynamic Web Pages" and there were Dynamic Web Pages.
The page you are currently viewing is a classic example of a dynamic web page. If you look at the top of the page you see the words 'Last Updated:' followed by a date. If you looked at the source of the page you might think that I actually edit that date every time I make an update to the page but in reality, the web page checks to see when it was last updated and writes in the date DYNAMICALLY.
There are several methods for implementing dynamic web pages each of which usually falls into one of the following categories:
Dynamic web pages began with the creation of the Common Gateway Interface. This let people point their web browsers at a program on a webserver and see the output inside their browser window.
For example the following Perl program is here
#!/usr/bin/perl
print "Content-Type: text/html\n\n";
print "Hello World\n";
The advantages of CGI programs are that they are run on the server itself (aka Server Side). This means that:
The disadvantages of CGI programs are that they are regular computer programs, in every way. This means that:
Client Side Scripting languages like JavaScript and vbscript came next. Without changing anything about how web pages were handled by web servers, browser companies started competing by adding script processing capabilities into their browsers. They hoped that the more wizardry their browsers could manage,the more websites would force people to use their web browsers. They were right.
The long and short of it is that you can write a script inside your web page, known as inline, and the web browser will process it before it shows the website in the web browser. Since the processing happens inside the web browser, this is called a Client Side Script.
The upside of this is that it costs no processing time on the Server Side.
The downside of this Client Side processing is that on the client side the access to Server Side resources is necessarily limited and the web browser must be able to see the code of my script.
Both the CGI programs and the Client Side Scripts still have their places but they each have advantages and disadvantages.
Server Side Scripts combine the best of both worlds. They are processed on the server so the code is hidden from the web browser and they have access to everything the server does (just like CGI programs). They are written inline, so they only need to handle the dynamic parts of the web page, taking up less resources (like Client Side Scripts).
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.
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.
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 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: http://www.php.net
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.
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:
Click here to see how this example would appear in your browser.
Just like it's "Parent" languages, statements in PHP are separated by semi-colons. Here is an example of multiple statements:
Click here to see how this example would appear in your browser.
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.
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:
Click here to see how this example would appear in your browser.
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:
Click here to see how this example would appear in your browser.
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).
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.
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.
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.
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:
\n | linefeed (LF or 0x0A (10) in ASCII) | |
\r | carriage return (CR or 0x0D (13) in ASCII) | |
\t | horizontal tab (HT or 0x09 (9) in ASCII) | |
\\ | backslash | |
\$ | dollar sign | |
\" | double-quote | |
\[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.
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( array(1,2,3,4), array(1,2,3,4), array(1,2,3,4), array(1,2,3,4) ); //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.
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.
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.
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!
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=5; $a+=6; // $a = 5 + 6 print $a; //outputs 11
The same is true for the '-=', '*=', '/=', and '.=' Operators.
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=5; $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:
$a=5; 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;
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:
$a=1; $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.
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):
a | b | !a | a&&b | a||b |
0 | 0 | 1 | 0 | 0 |
0 | 1 | 1 | 0 | 1 |
1 | 0 | 0 | 0 | 1 |
1 | 1 | 0 | 1 | 1 |
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 ';' } else { //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:
Click here to see how this example would appear in your browser.
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: break; ... case RHVn: break; 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:
Click here to see how this example would appear in your browser.
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:
Initialize the variables on which the loop is dependant(usually a variable used in the continue condition).
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.
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:
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:
Click here to see how this example would appear in your browser.
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:
Click here to see how this example would appear in your browser.
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:
Click here to see how this example would appear in your browser.
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:
for($i=0;$i<=LAST_INDEX_OF_ARRAY;$i++) { $current_element_value=$array_name[$i]; //statements seperated by ';' }
Let's see an example:
Date | Correct/Incorrect Answers | % Correct | |||||||||
$value | "; } print "".($correct/$total)." | \n"; print "
Click here to see how this example would appear in your browser.
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:
Date | Correct/Incorrect Answers | % Correct | |||||||||
$date | "; foreach($date_record as $value) { print "$value | "; } print "".($correct/$total)." | \n"; print "
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.
The break statement simply exits the current loop or switch statement. For example:
$a=1; while($a<=10) { if($a>5) { break; } 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:
$a=1; while($a<=10) { if($a>5) { continue; } print $a++; }
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.
The get method sends the form contents in the address like: http://www.somewhere.com/myphp.php?name=value&name=value. This has several limitations:
The post method sends the form contents in the body of the request. This means that you can send anything you want this way. The only downside is that most browsers are unable to bookmark post requests.
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.
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:
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.
Here is an example of the source code of a form:
Please enter a name
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.
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:
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:
To put a Text Field into our page we place the following input tag inside our form tags:
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:
To put a Textarea Field into our page we place the following textarea tag inside our form tags:
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.
To put a Select Box on our web page we place the following series of tags inside our form tags:
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").
To put a set of Radio Buttons on our web page we place the following set of input tags inside our form tags:
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.
To put a Checkbox on our web page, we put the following input tag inside our forms tags:
We can also use the checked attribute here to make default selections.
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:
Let's see a real life example:
This page is littered with forms and form elements. The only form element missing is the Radio Button.
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.
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:
Name | Address | Phone Number |
Yonah Russ | 123 Sesame Street | 01-234-5678 |
Another table would describe an order: product, customer, date, sales price, etc. It might look as follows:
Product | Customer | Date | Price |
Computer | Yonah Russ | 10/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.
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.
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.
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.
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.
Entities | Attributes | Relationships |
Here is an example ER Diagram:
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.
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:
example_table | ||||||
id | status | username | description | datecreated | lastupdated | |
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.
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 |
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:
learning_programs | ||||
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:
learning_programs | ||||
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 |
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:
learning_programs | ||||
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.
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.
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:
learning_programs | ||||
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 |
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 table1.id and table2.id.
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 table1.id AS userid, table2.email AS useremail, table2.lastupdated AS last_login FROM table1,table2 WHERE ((table1.id > 10 AND table2.email LIKE '%@%') AND (table1.id = table2.id)) ORDER BY email DESC LIMIT 0,20;
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.
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.