PHP Primer

This month we thought we'd take a quick look at PHP, the latest entry in the world of Web programming for the System i platform. We're excited about this new arrival as it helps to lower the "cost" of entering the world of the Web and moves the System i platform firmly into the mainstream. The introduction of PHP is a joint effort by IBM and Zend ("The php Company"). Full details of the announcement are online (www.ibm.com/systems/i/software/php.)

Normally when we use an acronym such as PHP in an article, the first time you see it, it's spelled out. For example: Java Server Pages (JSPs). This is a little difficult with PHP since it's a recursive, or self-referential, acronym (i.e., the first "P" in PHP stands for ... PHP!). The formal definition of PHP is PHP: Hypertext Preprocessor. Originally PHP supposedly stood for Personal Home Page; it's come a long way from its roots. To describe it in this way would be as meaningless and convey as little about its capabilities as saying that RPG stands for Report Program Generator!

So why is the availability of PHP so important to the System i platform? Because PHP is probably the single most widely used Web programming language today. Usage figures are hard to come by, but a NetCraft survey of French Web sites (as quoted by IBM in a recent presentation) indicated that PHP was being used on 58 percent of all French Web sites compared with a combined total of 41 percent for ASPs, JSPs and .Net.

In real estate, it's all about the three Ls - location, location, location. In today's programming world, it's all about the three Cs-community, community, community. When selecting a new programming language, the size of the programming community should be a major consideration. The larger the community, the more high-quality code samples, documentation and help you'll have available to you. Similarly, a large community makes it easier to recruit skilled help, and you'll discover a larger pool of affordable consulting services.

A quick search of the Web will convince you of the staggering amount of quality PHP resources available. Many are free, some are conventional commercial offerings, and others are available for the payment of a maintenance fee.

Suppose, for example, you wanted to implement an in-house bulletin board system. A quick search of the Web led us to HotScripts.com (www.HotScripts.com) where we quickly located no less than 217 such systems. Many of these, including the highly rated phpBB, are available free of charge. Incidentally, not only is phpBB free, but it also comes complete with installation and customization tools that would not look out of place in a commercial product. In fact, they're a great deal better than many commercial System i offerings we've reviewed in the past.

Still not convinced? Perhaps your CEO has been reading airline magazines and is now hot-to-trot on implementing a wiki*. HotScripts located 21 such applications for us. We also checked their current "Top Rated" list and came across Help Desk and Call Center applications that might be useful for those of you considering implementing such capabilities. So what is PHP? It's a general-purpose scripting language that's particularly well suited for Web development and can be embedded into HTML. In this regard, it's very similar to Java Server Pages (JSPs) (i.e., The scripting language is embedded within the HTML/XML to make up the Web page). The PHP interpreter then dynamically constructs the Web page by processing the embedded script and building the HTML.


However, it isn't restricted to Web use, and we can see great potential for it as a general- purpose scripting language - something the System i platform has never really had since Rexx really never got off the ground.

What does a PHP program look like? Example 1 (below) is a simple piece of HTML that includes a PHP script within the special <?php ...?> tag. Within the script, the first thing we do is assign the value "dynamic content" to the variable $MyVar. In PHP, all variable names begin with the dollar ($) sign. That's right, just when we were finally persuading RPG programmers not to use special characters in their variable names, along comes PHP and confuses everything.

Next, we use PHP's echo function to supply the dynamic portion of the Web page content. Notice that within the literal string "<p>And this ..." we've included the name of the variable $MyVar. In RPG, this would simply result in the characters "$MyVar" appearing in the string. However, PHP recognizes the name and replaces it with the content of the variable; much simpler than having to concatenate the literals with the variable's content as we'd have to with RPG. If it occurs to you that this might present a problem if we actually wanted to include a "$"in the text, you're quite correct. In fact, this is the reason for the appearance of the backslash (\) later in the string. It's the escape character and causes PHP to treat the following $ as a character and not as the beginning of a variable name. The following is the result of running this code.

Example 1: A Simple "Hello World" Web Page
<html><body>
<h3>Simple "Hello" Test</h3>
<p>This part is static text</p>
<?php
$MyVar = "dynamic content";
echo "<p>And this (<b>$MyVar</b>) is the content of the variable \$MyVar</p>";
?>
</p></body></html>

Example 2: Simple Database retrieval
Our second example includes the use of SQL embedded within the PHP script. For the purposes of the example, we've chosen to use the SQLite database, which is built into PHP V5. The reason being to encourage those of you who will not be moving to V5R4 for a while to install and use PHP on your PC while you're waiting. A DB2 version of the program would be very similar.

Rather than go through the code in detail, we'll focus on those parts that are "unusual" from an RPG or COBOL perspective. The first step is to use the sqlite_query function to execute the SQL query. It returns the variable $query that will contain a "handle" to the results (similar to a cursor if you're familiar with using embedded SQL). We then pass this handle to the sqlite_fetch_all function, which returns an array ($result) containing all of the rows matching the query. Arrays are a very powerful feature of PHP and can have not only conventional numeric indices, but also keys (known as an associative index). As you'll see later, this makes it far easier to reference the individual columns in the result set. The SQLITE_ASSOC parameter is the means by which the return of the results in this form was requested.

It may have come as a surprise to you to hear that $result was an array - after all it looks like a simple variable. This is because of an interesting (and at first confusing) aspect of PHP - namely that variables are dynamically typed. One minute a field can be numeric, the next a character variable, and the next an array.

The PHP foreach function provides a simple way of stepping through the rows in the result set and returns each row in the array variable $entry. We then use the column name to index into the required element. For example, $entry['location'] references the data in the array element associated with the location column. Notice that these references are enclosed in curly brackets ({ }). This is necessary to ensure that PHP interprets the array reference correctly. The results of running the program are shown below.

<?php
$db = sqlite_open("db.sqlite");

$query = sqlite_query($db, 'SELECT * FROM names
WHERE salary > 45000
ORDER BY lastname, firstname');

// Output table headers
echo "<table border=1 width=40%> <th>Id<th>Name<th>Location<th>Salary";

// Get results as an array with the column name as the index
$result = sqlite_fetch_all($query, SQLITE_ASSOC);

// Iterate through the retrieved rows and output row data
foreach ($result as $entry)
{
echo "<tr><td>{$entry['id']}</td>
<td>{$entry['lastname']}, {$entry['firstname']}</td>
<td>{$entry['location']}</td>
<td align=right>{$entry['salary']}</td></tr>";
}

// Wrap up the table
echo "</table>";

sqlite_close($db);

?>


Get in the Game

That's all we have time for in this all-too-brief introduction. We plan to return to the topic later, to study the language and its capabilities in more detail. In the meantime, if you want to start playing today, you can download a pre-release version of PHP from the link on the announcement Web page mentioned earlier.

If loading PHP on your System i isn't an option at this time, you can explore the language by downloading the Windows version (www.php.net). Here, you'll also find documentation, tutorials and much more. If you really want to do it the easy way, then do as we did and download one of the pre-packaged distributions such as XAMPP (www.apachefriends.org/en/xampp.html). This will install PHP, Apache, MySQL and additional tools, and configure them to work together. Good luck in your PHP explorations. We're sure that you'll soon become as enthusiastic about the prospects as we have. To help you with your explorations, here are two more Web sites you might find interesting:

www.phpjunkyard.com
www.phpfreaks.com

*If like us you're not altogether certain just what a "wiki" is, the following definition from Wikipedia may help: "A type of Web site that allows users to easily add, remove, or otherwise edit all content, very quickly and easily, sometimes without the need for registration. This ease of interaction and operation makes a wiki an effective tool for collaborative writing."