• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Exploring the DB2 for i5/OS Extensions to the PHP Language

    June 4, 2008 Erwin Earley

    This is the fifth (and final) article in the PHP on i5/OS series. Previous articles in this series have looked at the structure of Zend Core in i5/OS, basic syntax of the PHP language, and the i5 Toolkit collection of APIs for accessing native i5/OS resources. This article will look at the extensions to the PHP language for accessing DB2 for i5/OS resources.

    The DB2 extensions can be broken down into a number of categories as follows:

    • Server/Connection
    • Result
    • Commit/Rollback
    • Fetch
    • Field Information
    • Key Information
    • Statement
    • Errors
    • Column/Procedure
    • Table Information

    This article will focus mainly on functions from the Server/Connection and Fetch categories.

    There are several differences between the i5 Toolkit APIs and the DB2 for i5/OS language extensions, including:

    • The i5 Toolkit APIs can only access local resources (i.e., resources on the same i5/OS partition as Zend Core) while the DB2 for i5/OS extensions can access both local and remote DB2 for i5/OS resources through established network connections
    • All i5 Toolkit APIs begin with the characters “i5_” while the DB2 for i5/OS extensions begin with the characters “db2_”

    The difference in the location of the resources that can be accessed is summarized in the following diagram:

    Connecting To a Database Resource

    Before looking at a specific example, let’s take a look at the different types of server connections that can be made with the db2_connect() function and the implication behind them. The db2_connect() function call expects three arguments–the server to connect to as well as the user profile and password to use for authentication. If no values (or NULL values) are provided for these parameters, then a connection is made to the local server:

    db2_connect("","","");
    

    When connecting without specifying a user profile and password, the database connection job is created using the same user as the Apache server profile, which in the case of a default Zend Core environment will be profile NOBODY (*USER).

    An authenticated connection can be made to the local server by providing the name “*LOCAL” for server and then a specific user profile and password as shown in this example:

    db2_connect("*LOCAL","ERWIN","PASSWORD");
    

    In this case the database connection is created under the user profile ERWIN (assuming the password provided is valid).

    A connection can be made to a remote database server by providing the network name of the server in the db2_connect() function call:

    db2_connect("10.1.2.15","ERWIN","PASSWORD");
    

    In this case a connection will be made to the database resource on 10.1.2.15 using the user profile ERWIN on that server with the password of PASSWORD.

    Exploring the DB2 for i5/OS Language Extensions

    Unlike other articles in this series, this article is going to take a single example and build upon it throughout the article. The example will create an employee information search and retrieval form.

    Let’s start by taking a look at the PHP code that will generate the employee search form.

    <html>
    <?php
    define("PAGE_TITLE", "Employee Update");
    define("PHP_FILE_NAME", "employee_update.php")
    ?>
    
    <title><?= PAGE_TITLE . " - " . PHP_FILE_NAME; ?></title>
    <body>
    <?php 
    
    ?>
    </body>
    </html>
    

    Running the above block of code through a browser would generate a blank Web page with a title bar of “Employee Update – employee_update.php”.

    Now let’s add the code that will display the Employee Search form. The following block of code would be placed between the second <?php tab and the corresponding ?> tag.

    Note: The code in the above graphic is available for download here.

    This block of code simply outputs in the HTML stream instructions for what is to be entered into the form along with the HTML to generate the form information. When executed, the PHP will cause the following HTML form to be generated:

    The code we’ve developed so far should be saved as “employee_update.php”.

    Search Action

    Now that we have the form for the search request coded, we are ready to take a look at the code for the actual search action.

    The next section of code will establish the connection to the database server and it would be placed between the second <?php tag and the /*Display comment

    Note: The code in the above graphic is available for download here.

    1. The first block code simply includes a separate php file that contains a number of variable definitions for the program, including the database name, user profile, and password.
    2. The db2_connect() call is used to establish a connection to the database server. The parameters to this function are the database, user profile, and password for the user profile.
    3. Tests to ensure that a valid handle was returned from the db2_connect() function call. If not, the die() language construct is used to output an error message and then terminate processing.

    Query

    The next section of code to look at will perform a query on the EMPLOYEE table and place the results onto the Employee Search Results form. The following code snippit would be placed between the</form> line and the second ?> PHP end tag:

    Note: The code in the above graphic is available for download here.

    Let’s take a closer look at this code:

    1. The first block of code simply establishes a variable (called $sql) that contains the SQL select statement that will be executed. Notice in the assignment that the “lastname” entered on the form is being used in the where clause of the select statement and that the “%” character is being appended to the name entered on the form so that all records with a last name that starts with the characters entered on the form will selected.
    2. The db2_exec() statement causes the SQL statement to be executed against the database that was opened previously with the db2_connect() function call. Notice that the db2_exec() statement is using the handle to the database ($dbh) that was returned by the db2_connect() call. The db2_exec() call returns a statement resource ($stmt) that can be used by a subsequent db2_fetch_array() call to process the resource returned by execution of the SQL statement.
    3. The print statements will output into the HTML stream the first part of the search results form, which includes a header line indicating what records are being displayed as well as a table that will contain the returned records.
    4. The while loop will iterate through the records pointed to by the db2_exec() call (as represented by the $stmt variable) and print them into the HTML table. Each time through the loop the db2_fetch_array() call will return an array of values representing a row from the result set.
    5. Notice that the employee number ($customerNumber) is being printed as an actionable tag that will be a selectable link on the HTML page. This is accomplished through the href statement, which will cause “employee_update.php to be invoked with the value for the selected “customerNumber” (represented in a _GET variable).
    6. The final statements simply cause the HTML tag to close the table to be output in the HTML stream as well as a message indicating the page was built through a dynamic SQL statement.

    Note: Using the db2_exec() statement to insert PHP variable values into an SQL statement can be considered a security exposure. Rather then using the db2_exec() statement, you might want to consider calling the db2_prepare() statement to prepare an SQL statement with parameter markers for input values. Then the db2_execute() statement could be used rather then db2_exec() statement to pass in the input values.

    Now when you invoke the PHP file from a Web browser (after saving the changes), the search form will be displayed as shown earlier in this article. Entering data in the Last Name field and then selecting the Search button will cause the just coded search code to be executed and display a result page similar to the following:

    The next part of the example would be to add the code to edit an Employee record. This code would be invoked when an employee number is selected from the search results window. The following block of code should be placed between the $action = $_POST[“action’] and if (!$action) lines:

    Note: The code in the above graphic is available for download here.

    1. The employee number selected on the search results form is retrieved from the URL and assigned to the $customerNumber variable.
    2. The test of the $customerNumber field is performed to see if this block of code was reached after an employee number was selected from the search results window. Keep in mind that this PHP code generates the Employee Search as well as the Employee Search Results pages.

    Edit Record

    The next portion of code works with displays the values of a record and allows the user to edit those values. The following snippit of code would be placed into the PHP application between the bracket line and the second ?> PHP end tag.

    Note: The code in the above graphic is available for download here.

    1. The select statement establishes the query using the customer number from the HTML form.
    2. The db2_exec() call executes the query.
    3. The db2_fetch_array() call retrieves an array of field values from a record in the return set from the db2_exec() call.
    4. The if statement tests to ensure that a record was returned from the db2_fetch_array() call. If a record was returned, local variables are used to store the field values.
    5. A series of print statements are used to output text labels as well as the contents of the returned record.

    It should be noted that the print ‘<form>’ line along with the print ‘<input> line will cause the program to place the “Update” action onto the URL line when the Update button is selected. Each of the field values are also placed into the URL string. This causes the application to “call” itself once again. The URL string values are retrieved using the $_GET function and then used in the SQL update call that will be discussed in the next part of the article.

    Now when you invoke the PHP program (after saving it) from a Web browser searching for a record and then select one of the returned records from the Employee Search Results form, it will display the Employee Edit Record form with the values from the selected record:

    Record Update

    The next section of code is invoked when the user has selected the Update button from the Edit page. This code updates the DB2 for i5/OS table using the user modified fields. Once the record has been updated an HTML form is output that simply echoes out the SQL statement along with an indication of whether or not the update was successful. The form will include a Continue button that, as we will see from the code, resets the application and returns to the Search form.

    The first thing we need to do is determine the state of the application. The following lines of code should replace the $action = $_POST[“action”] line of code that can be found just prior to the $customerNumber= $_GET[“customerNumber”] statement:

    $action = $_GET["action"];
    /* if no value from $_GET, try $_POST */
    if (!$action) {
         $action = $_POST["action"];
    }
    

    Additionally, the section of code that resembles the following:

       } 
    } else { /* Edit the selected customer number record */ 
    

    Should be changed to resemble the following (i.e., remove the beginning close bracket on the else statement):

     } 
    else { /* Edit the selected customer number record */ 
    

    The following block of code should be placed into the employee_update.php file. This code is placed before the else { /* Edit the selected customer number record */ statement:

    Note: The code in the above graphic is available for download here.

    1. The if statement determines whether or not the user requested the Update action from the Edit Record form. If the update action was invoked then the remaining code in this snippit will be executed.
    2. The assignment statement generates the SQL update statement using values passed from the calling form.
    3. The db2_exec() statement executes the SQL update statement returning the results into the $result variable.
    4. The if statement tests the result returned from the db2_exec() call. If an error was encountered by the update statement, then an error message is output to the HTML form. Otherwise, a success message is output along with the actual SQL statement that was executed by the db2_exec() call.
    5. The <form> line along with the <input> line will cause the program to place the Continue action onto the URL string when the Continue button is selected. The program will then re-invoke itself.

    Note: In addition to inserting the above code snippit you will also need to add a line containing a closing bracket before the second ?> PHP end tag at the bottom of the application.

    Once all of these changes have been made you should save the file. Once the file has been saved, execute the program from your browser, search for a set of records, select a record, edit the values, and select the Update button. Upon a successful update a Web page similar to the following should be displayed:

    Continue

    The final section of code that we need to take a look at is the code to process selection of the Continue button and reset the application back to the Employee Search form.

    The if (!$action) line of the following snippit of code:

    /* Determine which form to display based upon the state of application */
    if ($customerNumber == "") {
    if (!$action) {
    

    needs to be changed to test for the Continue action as follows:

    if ((!$action) or ($action == "Continue")) {
    

    The check for the Continue action will cause the Search form to be displayed when the Continue button is selected from the Update database form.

    That’s it. Save the file and re-execute the PHP application. Now going through the process of searching for records, selecting a returned record, editing the fields, selecting update, and then selecting Continue should return you back to the Search form.

    Conclusion

    In this article we have put together a complete PHP application that allows a user to search a database for records matching a specified selection criteria and update records from the returned set. I hope this article has provided you with some insight into the possibilities that PHP provides for developing PHP based applications that leverage DB2 for i5/OS resources.

    Thanks for reading this series of articles on PHP on i5/OS and taking the journey with me on exploring some of the features that PHP on i5/OS provides for developing and deploying Web-based applications that leverage both i5/OS native resources as well as DB2 for i5/OS resources. I hope that this series has been of interest to you and you will continue to explore the ways that PHP can be used in your shop.

    Erwin Earley is an advisory software engineer in the IBM lab located in Rochester, Minnesota, and heads up the Open Source Technologies Center of Competency for System i within the System i Technology Center. At that center, he provides education and enablement services for open source related technologies on System i including Linux, MySQL, and Zend’s PHP. Earley currently holds certifications from Red Hat as well as the Linux Professional Institute and is a candidate for certification with Zend’s PHP.

    RELATED STORIES

    Bringing i5/OS Resources to the Web

    Use PHP to Bring i5/OS Resources to the Web

    PHP: An Easy Yet Powerful Language Syntax

    PHP on i5/OS: A Whole New Stack



                         Post this story to del.icio.us
                   Post this story to Digg
        Post this story to Slashdot

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    Midrange Dynamics North America

    Git up to speed with MDChange!

    Git can be lightning-fast when dealing with just a few hundred items in a repository. But when dealing with tens of thousands of items, transaction wait times can take minutes.

    MDChange offers an elegant solution that enables you to work efficiently any size Git repository while making your Git experience seamless and highly responsive.

    Learn more.

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    MoshiMoshi:  An Interactive Experience for the System i Community. Watch now!
    COMMON:  Join us at the Focus 2008 workshop conference, October 5 - 8, in San Francisco, California
    Vision Solutions:  System i Management Tips Blog - Free i5/OS Tips Each Week!

    IT Jungle Store Top Book Picks

    Easy Steps to Internet Programming for AS/400, iSeries, and System i: List Price, $49.95
    Getting Started with PHP for i5/OS: List Price, $59.95
    The System i RPG & RPG IV Tutorial and Lab Exercises: List Price, $59.95
    The System i Pocket RPG & RPG IV Guide: List Price, $69.95
    The iSeries Pocket Database Guide: List Price, $59.00
    The iSeries Pocket Developers' Guide: List Price, $59.00
    The iSeries Pocket SQL Guide: List Price, $59.00
    The iSeries Pocket Query Guide: List Price, $49.00
    The iSeries Pocket WebFacing Primer: List Price, $39.00
    Migrating to WebSphere Express for iSeries: List Price, $49.00
    iSeries Express Web Implementer's Guide: List Price, $59.00
    Getting Started with WebSphere Development Studio for iSeries: List Price, $79.95
    Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00
    Getting Started with WebSphere Express for iSeries: List Price, $49.00
    WebFacing Application Design and Development Guide: List Price, $55.00
    Can the AS/400 Survive IBM?: List Price, $49.00
    The All-Everything Machine: List Price, $29.95
    Chip Wars: List Price, $29.95

    Dun & Bradstreet Picks Raz-Lee to Secure i Servers Magic Targets Rich Internet Apps, SaaS with G5

    Leave a Reply Cancel reply

Volume 8, Number 21 -- June 4, 2008
THIS ISSUE SPONSORED BY:

WorksRight Software
Profound Logic Software
COMMON

Table of Contents

  • Exploring the DB2 for i5/OS Extensions to the PHP Language
  • Use Parameter Markers in SQL Persistent Stored Modules
  • Admin Alert: Quick Audits for i5/OS Backups

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • Public Preview For Watson Code Assistant for i Available Soon
  • COMMON Youth Movement Continues at POWERUp 2025
  • IBM Preserves Memory Investments Across Power10 And Power11
  • Eradani Uses AI For New EDI And API Service
  • Picking Apart IBM’s $150 Billion In US Manufacturing And R&D
  • FAX/400 And CICS For i Are Dead. What Will IBM Kill Next?
  • Fresche Overhauls X-Analysis With Web UI, AI Smarts
  • Is It Time To Add The Rust Programming Language To IBM i?
  • Is IBM Going To Raise Prices On Power10 Expert Care?
  • IBM i PTF Guide, Volume 27, Number 20

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle