A Brief Introduction
to PHP:
|
|
Note the two <?...?> tags in the above text. This syntax indicates PHP commands that are interpreted by the server instead of being passed to the client. You may jump in and out of PHP mode in an HTML file like this all you want. This program is extremely simple and you really didn't need to use PHP to create a page like this. All it does is display "Hello World" using the ECHO command. With ECHO you can print out strings enclosed in quotes, variables, or a combination of both. At the end of the ECHO command you will see a semicolon (;). Almost every PHP command must end in a semicolon (;).
By clicking on the blue magnifying
glass
in the bottom
right corner of the code window above you can view the code results in a separate
browser window. If you view the source, you will see the following:
|
As you see, the scripting commands are not visible on the client side. This is good because it keeps the source code for the PHP protected. This means the original PHP code cannot be downloaded and copied without permission. So let's try something useful by generating a table of font colors generated on the fly. If you were to do this by hand it would take a very long time, with PHP it only takes a very few well placed lines of code.
The
above simple program prints out "Netsafe
colors" which are colors that display relatively similar in all browsers
across all platforms. The
program sets up an HTML page with three "for" loops, one for each
of the RGB elements. The FOR loop is the most complex loop in PHP, it consists
of three parts, or expressions:
FOR(expr1; expr2; expr3) statement |
The first expression (expr1) is evaluated only once at the beginning of the loop. In the beginning of each loop, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statements are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated. In our program we set expr1 in each of the loops to a variable ($iR, $iG, $iB) which holds a decimal number representing a piece of our Netsafe colors (0, 51, 102, 153, 204, or 255). In expr2 we compare our variable to see if it is greater than 255, if it is we exit the loop, if not we run the statements following the FOR loop and then evaluate expr3 which adds 51 to our variable using the "+=" operator. For example, in our first FOR loop we have "$iR += 51" this literally means take the current value of $iR, add 51 to it and then assign it back to $Ir. In addition to being more concise, it results in faster execution time.
The three loops together cycle through the 216 colors that will not dither in a web browser. Each time the second loop is run it prints a table row. Each time the third loop is run it prints a table element which includes a font tag with a PHP formatted print statement:
printf("%02X%02X%02X", $iR, $iG, $iB);
|
Printf allows us to output a formatted string consisting of our RGB variables. The first part of the printf statement is the format specification to use. The remaining comma delimited portions are variables, strings or numbers to print out using the format specification. Notice that the specification string repeats itself three times ("%02X"), once for each variable that we are outputting. The "%" marks the beginning of a format string. The next character is an optional padding specifier that says what character will be used for padding the results to the right string size. In our case we want all our hexadecimals padded with 0, hence the "0" in our format string.. The next number is a width specifier that says how many characters (minimum) this conversion should result in, in our case "2". Finally we have a type specifier that says what type the argument data should be treated as. In this case we want to convert our decimal numbers to hexadecimal. We use the "X" in the format string to do this.
So now you are thinking that all this is great, but what you really want to do is print out a bunch of names from a database. This is much easier than it may sound at first. For our next example we will connect to a readily available Microsoft Access database. The database file is PHPTest.mdb and contains one table called "Contacts". The Contacts table contains three columns labeled UserID, FirstName, and LastName and looks something like this…
| UserID | FirstName | LastName |
| 1092 | Lisa | Vincent |
| 2938 | Pat | Charles |
| 9284 | Christine | Honeycutt |
| 2837 | Mike | Vincent |
The database requires a System DSN to be set up under the webserver’s ODBC connections. Your system administrator should be able to do this for you, but if you are developing on your local machine or you have permission to do it yourself on a development box, it is rather straightforward and just requires a few simple steps.
The following program will execute a SQL command against our Access database and print out the UserID and FirstName of all the contacts that have a LastName field that matches "Vincent"...
|
Whatever you do don’t panic, its not nearly as bad as it may look. The majority of the lines are simple ECHO statements which we have seen before. Two of the lines are FOR loops and one line is a PRINTF which we have been over as well. This leaves an IF_THEN_ELSE statement which you are probably familiar with. The IF construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. Whatever is in the parenthesis after the IF is evaluated to its truth value. If it evaluates to TRUE, the next statement will be executed, and if it evaluates to FALSE - it'll ignore it. The ELSE found several lines below the IF extends our IF statement to execute a statement in case the expression in the IF statement evaluates to FALSE.
Now we get to the important bits. Notice the commands which start with ODBC? These are all ODBC specific commands which we use to interact with our database. The first command we execute is ODBC_CONNECT which we pass our System DSN name. ODBC_CONNECT returns an ODBC connection ID. The two empty quotes represent a USERNAME/PASSWORD combination which are not required for our database. Next we send the connection ID along with a SQL query to the database using ODBC_EXEC which returns a result identifier if the SQL command was executed successfully, otherwise a 0 (FALSE) will be returned. The result identifier is very important and we will need to send it to several of the other ODBC commands which we invoke. It basically represents the information that was returned from our query.IF the SQL statement was executed successfully we then perform the statements under the IF statement, otherwise we print out "There are no Vincent’s in our database!" The first line inside the IF statement is ODBC_NUM_FIELDS which returns the number of fields contained in our SQL query. We use this information to loop through all the elements in the SQL query and print them out to a HTML table. But before we can loop through all the elements we must first retrieve the field names using ODBC_FIELD_NAME and print those as the table headers. We do this by looping through each of the fields and sending the SQL result identifier and field number as parameters to ODBC_FIELD_NAME, it returns to us the actual name of the field (i.e. "FirstName" and "UserID") Notice that we make the actual function call within the ECHO statement. We do this by appending the results of the call to the surrounding parameters of the echo statement with the DOT "." operator. You can use the DOT operator anywhere you need to append string information together.
The last two ODBC commands we have to examine are ODBC_FETCH_ROW and ODBC_RESULT. Each time ODBC_FETCH_ROW is called it proceeds on to the next row of our SQL results. The ODBC_FETCH_ROW command returns a TRUE if a row was retrieved, otherwise it returns a FALSE. The WHILE loop which the ODBC_FETCH_ROW is contained in looks at this TRUE/FALSE result and performs a loop if the results are TRUE, otherwise the WHILE loop quiets. Inside the WHILE loop we print out a table row and loop through all of the fields that need to be output. To retrieve a field to print we use ODBC_RESULT, passing it the result identifier and the number or name of the field we wish to retrieve.
So now that you have a taste for PHP, you will probably be looking for more information on it. The upcoming new edition of O'Reilly WebMaster's Guide will have a large section devoted to PHP and a full O’Reilly book will follow this. The authors are 5 of the PHP core development team (Andi Gutmans, Rasmus Lerdorf, Stig Bakken, Shane Caraveo and Zeev Suraski) . Support may be found online from sample code archives, function libraries and a PHP mailing list that receives close to 2500 messages per month!
Many more resources can be found online…