Use Ajax with PHP and DB2 9 - Xajax - IBM - United States · Use Ajax with PHP and DB2 9 - Xajax...

23
Use Ajax with PHP and DB2 9 - Xajax Using Xajax with DB2 for Linux, UNIX, and Windows Skill Level: Introductory Deepak Vohra ([email protected]) Web Developer Independent 25 Jan 2007 PHP is a scripting language commonly used in developing Web applications. Asynchronous JavaScript and XML (Ajax) is a Web technique that combines JavaScript, Document Object Model (DOM), and XMLHttpRequest technologies to provide dynamic interactions between a client and a server. Various PHP class libraries are available for using Ajax with PHP, among them Xajax, an open source, object-oriented, PHP class library. In this article, learn how to implement PHP, Ajax, and Xajax to develop a dynamic Web application solution accessing IBM® DB2® 9 for Linux®, UNIX®, and Windows®. Introduction More than 40% of Web applications today use PHP as their scripting language. Asynchronous JavaScript and XML (Ajax) is a Web technique that combines JavaScript, Document Object Model (DOM), and XMLHttpRequest technologies to provide dynamic interaction between a client and a server. Various PHP class libraries are available for using Ajax with PHP. Xajax is an open source, object-oriented, PHP class library with which Ajax may be used with PHP. As an example, suppose a user fills out a form to register with a Web site. The validity of data in the form is not checked until the form is submitted. With Ajax, the data added to the form is dynamically validated using business logic in a server application. Thus, a complete form does not have to be posted to the server to check to see whether or not the data in the form is valid. Asynchronous implies that the send() method of an XMLHttpRequest object returns immediately without the Use Ajax with PHP and DB2 9 - Xajax © Copyright IBM Corporation 1994, 2006. All rights reserved. Page 1 of 23

Transcript of Use Ajax with PHP and DB2 9 - Xajax - IBM - United States · Use Ajax with PHP and DB2 9 - Xajax...

Use Ajax with PHP and DB2 9 - XajaxUsing Xajax with DB2 for Linux, UNIX, and Windows

Skill Level: Introductory

Deepak Vohra ([email protected])Web DeveloperIndependent

25 Jan 2007

PHP is a scripting language commonly used in developing Web applications.Asynchronous JavaScript and XML (Ajax) is a Web technique that combinesJavaScript, Document Object Model (DOM), and XMLHttpRequest technologies toprovide dynamic interactions between a client and a server. Various PHP classlibraries are available for using Ajax with PHP, among them Xajax, an open source,object-oriented, PHP class library. In this article, learn how to implement PHP, Ajax,and Xajax to develop a dynamic Web application solution accessing IBM® DB2® 9 forLinux®, UNIX®, and Windows®.

Introduction

More than 40% of Web applications today use PHP as their scripting language.Asynchronous JavaScript and XML (Ajax) is a Web technique that combinesJavaScript, Document Object Model (DOM), and XMLHttpRequest technologies toprovide dynamic interaction between a client and a server. Various PHP classlibraries are available for using Ajax with PHP. Xajax is an open source,object-oriented, PHP class library with which Ajax may be used with PHP.

As an example, suppose a user fills out a form to register with a Web site. Thevalidity of data in the form is not checked until the form is submitted. With Ajax, thedata added to the form is dynamically validated using business logic in a serverapplication. Thus, a complete form does not have to be posted to the server to checkto see whether or not the data in the form is valid. Asynchronous implies that thesend() method of an XMLHttpRequest object returns immediately without the

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 1 of 23

HTTP request being complete and the processing of the HTML/JavaScript page thatinitiated the request continues. As a result, a developer may find that aHTML/JavaScript page that initiates an XMLHttpRequest request may continue tobe processed as the XMLHttpRequest object processes the HTTP responseasynchronously.

Overview of Xajax

Xajax is used to communicate asynchronously between a client application and aserver side application composed of PHP scripts. Xajax generates JavaScriptwrapper functions for PHP functions on the server side that may be accessed from aclient application. When a client application invokes the wrapper functions, anXMLHttpRequest object is initiated and an XMLHttpRequest HTTP request issent to the server.

On the server, the xajax object receives the XMLHttpRequest and invokes thePHP functions corresponding to the JavaScript wrapper functions. The defaultrequest type of PHP functions registered through Xajax is POST. The PHP functionsreturn an XML response that is returned to the client application by the xajaxobject. Based on the instructions in the XML response, the Xajax's JavaScriptmessage pump updates the content of the client input page. Xajax has a feature thatensures that data is updated only if data has been modified.

To get you started with creating your own Web application, let's first walk through theprocess of installing the products and creating a database. Then you can delve intothe creation of the application itself.

Install DB2 for Linux, UNIX, and Windows

The PHP extension for DB2 database may be used with DB2 for Linux, UNIX, andWindows V8.2 or later. The following installation instructions use DB2 Enterprise 9for Windows:

1. Download DB2 9 data server (see Resources). (Although this exampleuses DB2 Enterprise 9, you may use other editions of DB2 as well.)

2. Extract db2_v9_ese_win_32.zip to a directory.

3. To install DB2, double-click on C:\DB2\ESE\image\setup.exe application.

4. In the IBM DB2 Setup Launchpad, click on Install a Product.

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 2 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

5. Click on Install New in the DB2 Enterprise Server header. The DB2Setup Wizard will start. Click on Next.

6. Accept license agreement, and click on Next.

7. Select an Installation Type (Typical ), and click on Next.

8. Select the installation and response file creation (default), and click onNext.

9. Select an installation folder (C:\Program Files\IBM\SQLLIB\ is the default),and click on Next.

10. Specify a user name (db2) and password (db2admin), and click on Next.

11. DB2 instance DB2 is listed as the default DB2 instance. You can configurethe service name and protocol for the default DB2 instance by clicking onthe Configure button. The default service name is db2c_DB2, and thedefault port is 5000. Click on Next.

12. Select the default setting in the Prepare the DB2 tools catalog frame, andclick on Next.

13. Set up notifications, if required, and click on Next.

14. Select the default settings in the Enable operating system security forDB2 objects, and click on Next.

15. Click on the Finish button to install the database server.

Now create a sample database. As a prerequisite, set the DB2INSTANCEenvironment variable to DB2: Select System Properties > Advanced >Environment Variables > System Variables. You can also set the DB2INSTANCEenvironment variable using the following command in a DB2 command window:

set DB2INSTANCE=DB2

To create a sample database, select Database Creation in the DB2 First Stepsframe. Click on the Create SAMPLE Database button. You can also create asample database using the following command:

db2sampl

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 3 of 23

Register the DB2 database SAMPLE as an ODBC data source with the followingDB2 command:

db2 catalog system odbc data source sample

Install PHP and Xajax

As Xajax is a PHP class library, first download and install PHP 5. PHP 5 may beinstalled on a number of different Web servers. This article discusses configuringPHP 5 with the Apache Web server on Windows.

Here are the steps for installing and configuring PHP:

1. Download PHP 5.2.0 (See Resources).

2. Extract the PHP zip file to an installation directory (C:/PHP, for example).

3. Download and install the Apache HTTP Server 2.0.

4. To the PATH environment system variable, add the directory in which PHP5 is installed (C:/PHP).

5. Modify the php.init-recommended file in C:/PHP directory to php.ini.

The example application in this article stores and fetches data from the DB2database. You will use the PHP PDO extension to connect to the DB2 database.

In the php.ini configuration file, you need to set the extension directory by specifyingextension_dir = "./ext". You need to activate the PDO extension byremoving the ';' before the following line in the php.ini file:

extension=php_pdo.dll

The PDO ODBC driver is also required to be activated. In the php.ini file, remove the';' before the following line:

extension=php_pdo_odbc.dll

Install PHP 5 in the Apache HTTP server. To the <Apache2>/conf/httpd.conf file,add:

# For PHP 5

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 4 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

LoadModule php5_module "C:/PHP/php5apache2.dll"AddType application/x-httpd-php .php

# configure the path to php.iniPHPIniDir "C:/PHP/"

By default, the <Apache2> directory is the directory C:/Program Files/ApacheGroup/Apache2. We have installed the Apache2 server in the C:/Apache2/Apache2directory. If PHP 5 is installed in a directory other than C:/PHP, replace C:/PHP withthe directory in which PHP 5 is installed. Restart Apache Web server after modifyingthe httpd.conf directory. Copy the PHP files to run in Apache Web server toC:/Apache2/Apache2/htdocs directory.

Download Xajax 0.2.4. Create an xajax directory in the C:/Apache2/Apache2/htdocsdirectory. Extract the xajax_0.2.4.zip file to the xajax directory.

Create a DB2 database table

The Xajax application retrieves data from a DB2 database table. The database tablemay be created with a PHP script. Create a PHP script, createTable.php. Definevariables for user and password:

$user = 'db2';$password = 'db2admin';

Obtain a connection with the DB2 SAMPLE database using the PDO constructor:

$connection = new PDO('odbc:SAMPLE', $user, $password);

By default, the PDO constructor creates a non-persistent connection. The PDOconstructor returns a DB2 database connection resource if the connection issuccessful. The output message reads, "Connection succeeded" if the connection issuccessful. If the database connection fails, the connection error message may beoutput. Define an SQL statement to create a table:

$createtable = "CREATE TABLE DB2.Catalog(CatalogId VARCHAR(25),Journal VARCHAR(25), Section Varchar(25), EditionVARCHAR(25), Title Varchar(45), Author Varchar(25))";

Run the SQL statement using the exec() function:

$connection->exec($createtable);

Define an SQL statement to add a table row:

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 5 of 23

$addrow = "INSERT INTO DB2.Catalog VALUES('catalog1', 'IBM developerWorks','XML', 'July 2006', 'The Java XPath API', 'Elliotte Harold')";

Run the SQL statement using the exec() function:

$result=$connection->exec($addrow);

A database table row gets added. Output the message to indicate number of rowsadded:

print("Added $result rows.\n");

Similarly, add another row to database table Catalog:

$addrow = "INSERT INTO DB2.Catalog VALUES('catalog2', 'IBM developerWorks','XML', 'October 2005', 'JAXP validation', 'Brett McLaughlin')";

$result=$connection->exec($addrow);

The PHP scriptcreateTable.php is shown in Listing 1. Copy createTable.php to theC:/Apache2/Apache2/htdocs directory. Start Apache Web server, if it is not alreadystarted. Run the PHP script in a browser with URL http://localhost/createTable.php.A database table, DB2.Catalog, gets generated, and data gets added to the table.

Listing 1. createTable.php

<?php

try {

$user = 'db2';$password = 'db2admin';

$connection = new PDO('odbc:SAMPLE', $user, $password);echo "Connection succeeded\n";

$createtable = "CREATE TABLE DB2.Catalog(CatalogId VARCHAR(25),Journal VARCHAR(25), Section Varchar(25), EditionVARCHAR(25), Title Varchar(45), Author Varchar(25))";

$connection->exec($createtable);

$addrow = "INSERT INTO DB2.Catalog VALUES('catalog1', 'IBM developerWorks','XML', 'July 2006', 'The Java XPath API','Elliotte Harold')";

$result=$connection->exec($addrow);

print("Added $result rows.\n");

$addrow = "INSERT INTO DB2.Catalog VALUES('catalog2', 'IBM developerWorks','XML', 'October 2005', 'JAXP validation',

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 6 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

'Brett McLaughlin')";

$result=$connection->exec($addrow);

} catch (PDOException $e) {

$e->getMessage();}

?>

Sending a request

Now let's develop an example application comprising of an input form. The inputform takes data to add a catalog entry to database table Catalog. As a user beginsto enter data in the input field Catalog Id, a XMLHttpRequest HTTP request is sentto the server to validate the Catalog Id value added. If the Catalog Id is not alreadydefined in the database, a message "Catalog Id is Valid" is displayed. If the CatalogId is already defined in the database, a message "Catalog Id is not Valid" isdisplayed, the Create Catalog button is disabled, and field values for the Catalog Idare added to the form.

The xajax PHP object performs the function of an intermediary between the clientapplication and the server. First, include the xajax class library:

require('./xajax/xajax_0.2.4/xajax.inc.php');

Create an xajax object:

$xajax = new xajax();

The server-side processing is performed by PHP functions. Create PHP functionsvalidateCatalogId($formValues) and updateCatalog($formValues).Both these functions take a $formValues parameter:

function validateCatalogId($formValues){}function updateCatalog($formValues){}

Register the PHP functions with the xajax object using the registerFunction()method. The xajax object creates wrapper functions for the PHP functions that maybe invoked from a PHP script or an input form event handler.

$xajax->registerFunction("validateCatalogId");

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 7 of 23

$xajax->registerFunction("updateCatalog");

Xajax generates asynchronous wrapper functions for the registered PHP functions.A wrapper function name is of the format xajax_phpfunction. Variablephpfunction is a server-side PHP function for which a wrapper function is to bedefined. Xajax provides asynchronous form processing with thegetFormValues(string formId) method. Using the getFormValues()method, an array of form field values may be submitted as an argument to an xajaxasynchronous wrapper function. Sections of a form may also be submitted, insteadof the complete form, with the getFormValues(string formID ,booleansubmitDisabledElements, string prefix]) function. The prefixparameter specifies that only form elements starting with that prefix should besubmitted. Boolean parameter submitDisabledElements specifies if disabledelements are to be submitted. PHP functions validateCatalogId andupdateCatalog define a parameter for an array of form field values. Before anXMLHttpRequest is initiated, specify the xajax object to handle requests with theprocessRequests() function:

$xajax->processRequests();

Also specify in the <head></head> tags of the input form that xajax shouldgenerate any required JavaScript after an XML response has been sent back fromthe server:

<?php $xajax->printJavascript('./xajax/xajax_0.2.4');?>

An XMLHttpRequest is initiated by a client application. In the example application,an XMLHttpRequest is initiated by the onkeyup event handler in input fieldcatalogId:

<tr><td>Catalog Id:</td><td><input type="text"size="20"

id="catalogId"name="catalogId"

autocomplete="off"onkeyup="xajax_validateCatalogId(xajax.getFormValues('validationForm'));"></td>

<td><div id="validationMessage"></div></td></tr>

The input field invokes the wrapper function xajax_validateCatalogId with anarray of form field values as a parameter. The wrapper function sends anXMLHttpRequest to the server. The xajax object receives the XMLHttpRequest

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 8 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

and invokes the corresponding PHP functionvalidateCatalogId($formValues).

Processing a request

Xajax provides the xajaxResponse class to send a response to the clientapplication. In the validateCatalogId function, create an xajaxResponseobject:

$objResponse = new xajaxResponse();

The validateCatalogId function validates a Catalog Id value added in the inputform. From the $formValues array, retrieve the value of the catalogId field:

$catalogId=trim($formValues['catalogId']);

Next, use the PHP PDO extension to connect with the DB2 database and determineif a Catalog table row is defined for the catalog id value input in the input form.

Define variables for user and password:

$user = 'db2';$password = 'db2admin';

Obtain a connection with the DB2 database using the PDO constructor:

$connection = new PDO('odbc:SAMPLE', $user, $password);

The PDO constructor returns a DB2 database connection resource if the connectionis successful. Prepare an SQL-prepared statement to select a row of data for thecatalog id value input in the form. Use the prepare ( string statement [,array driver_options] ) function to compile a prepared statement:

$stmt = $connection->prepare("SELECT * from DB2.CATALOG WHERE CATALOGID=?");

Set the cursor to be a scrollable cursor using the PDO::ATTR_CURSOR attribute:

$stmt ->setAttribute(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL);

Bind the CatalogId parameter using the bindParam() method:

$stmt->bindParam(1, $catalogId);

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 9 of 23

Run the SQL query in the prepared statement with the execute ( [arrayinput_parameters] ) function:

$stmt->execute();

Fetch the result set row using the fetch ( [int fetch_style [, intcursor_orientation [, int cursor_offset]]] ) function:

$row = $stmt->fetch();

The fetch() function returns TRUE if the requested row exists and FALSE if therequested row does not exist. If fetch() returns FALSE, the result set is empty,thus a Catalog table row for the catalog id value is not defined in the databasetable. Therefore, the Catalog Id field value added in the form is valid. Next, let'sgenerate a response to be sent to the client application. A response contains one ormore command messages. Some of the commonly used command messages arediscussed in Table 1:

Table 1. xajaxResponse Command MessagesCommand Message Description

Assign Sets the specified attribute of an element in inputpage with the method addAssign(stringelementId, string attribute, string data)

Append Appends data to the specified attribute of anelement in the input page with the methodaddAppend(string elementId, string attribute,string data)

Prepend Prepends data to the specified attribute of anelement in the input page with the methodaddPrepend(string elementId, string attribute,string data)

Replace Replaces data in the specified attribute of anelement in the input page with the methodaddReplace(string elementId, string attribute,string replace, string data)

Script Runs the specified JavaScript code with methodaddScript(string javascript)

Alert Displays an alert box with the specified messagewith the method addAlert(string message)

If the fetch() method returns FALSE, a message is displayed in thevalidationMessage div: "Catalog Id is Valid". The addAssign method sets theinnerHTML of the validationMessage div."

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 10 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is Valid");

If the fetch() function returns TRUE, the catalog id value is defined in the Catalogtable. Therefore, the Catalog Id value added in the input form is not valid. If thefetch() method returns a row, set the innerHTML of the validationMessagediv to "Catalog Id is not Valid":

$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is not Valid");

Next, fetch values from the result set row and set the values in the input form fields.The fetch() function sets the result set pointer to the next row.

Retrieve field values from the result set row with $row[mixed column] function.The column parameter may be specified as column index (0 based) or columnname. For example, the journal column value is obtained with PHP code infollowing listing:

$journal=$row['JOURNAL'];

Set the value attribute of the input form field elements with addAssign method.For example, the value attribute of the journal element is set as shown below:

$objResponse->addAssign("journal","value",$journal);

Also, disable the submit button:

$objResponse->addAssign("submitForm","disabled",true);

Return the $objResponse object from the validateCatalogId function as anXML string:

return $objResponse->getXML();

The XML response is sent to the xajax processor, which sends the XML response tothe xajax's JavaScript message pump. The message pump parses the XMLinstructions and sets the elements in the input page. Thus, the data specified in the$xmlResponse object with addAssign method is set in the input form.

The updateCatalog($formValues) function is used to update the databasetable Catalog from the input form. If the Catalog Id field value is valid, a new catalogentry may be created by adding values to the other fields of the form. Click on theCreate Catalog button to submit the form. The onsubmit event handler invokes the

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 11 of 23

wrapper function xajax_updateCatalog, which sends an XMLHttpRequest tothe server:

onsubmit="xajax_updateCatalog(xajax.getFormValues('validationForm'));"

The xajax object receives the XMLHttpRequest and invokes the correspondingPHP function updateCatalog($formValues). In the updateCatalog function,retrieve the form field values and create an SQL statement to add a row to databasetable Catalog. Obtain a connection with the database and run the SQL statement.The input.php script is listed in Listing 2:

Listing 2. input.php

<?php require('./xajax/xajax_0.2.4/xajax.inc.php');$xajax = new xajax();$xajax->cleanBufferOn();

$xajax->registerFunction("validateCatalogId");$xajax->registerFunction("updateCatalog");

function validateCatalogId($formValues){$objResponse = new xajaxResponse();

$catalogId=trim($formValues['catalogId']);

$user = 'db2';$password = 'db2admin';

$connection = new PDO('odbc:SAMPLE', $user, $password);

$stmt = $connection->prepare("SELECT * from DB2.CATALOG WHERE CATALOGID=?");$stmt ->setAttribute(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL);$stmt->bindParam(1, $catalogId);$stmt->execute();$row = $stmt->fetch();

if(!$row){$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is Valid");$objResponse->addAssign("submitForm","disabled",false);

$objResponse->addAssign("journal","value","");$objResponse->addAssign("section","value","");

$objResponse->addAssign("edition","value","");$objResponse->addAssign("title","value","");$objResponse->addAssign("author","value","");

}

if($row){$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is not Valid");

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 12 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

$catalogId=$row['CATALOGID'];$journal=$row['JOURNAL'];$section=$row['SECTION'];$edition=$row['EDITION'];$title=$row['TITLE'];$author=$row['AUTHOR'];

$objResponse->addAssign("journal","value",$journal);$objResponse->addAssign("section","value",$section);

$objResponse->addAssign("edition","value",$edition);$objResponse->addAssign("title","value",$title);$objResponse->addAssign("author","value",$author);$objResponse->addAssign("submitForm","disabled",true);

}

return $objResponse->getXML();

}

function updateCatalog($formValues){

$catalogId=trim($formValues['catalogId']);$journal=trim($formValues['journal']);$section=trim($formValues['section']);$edition=trim($formValues['edition']);$title=trim($formValues['title']);$author=trim($formValues['author']);

$user = 'db2';$password = 'db2admin';

$connection = new PDO('odbc:SAMPLE', $user, $password);

$sql = "INSERT INTO DB2.CatalogVALUES('".$catalogId."','".$journal."','".$section."','".$edition."','".$title."','".$author."')";

$r=$connection->exec($sql);

$connection->commit();

echo "Added $r rows.\n";

}$xajax->processRequests();

?><head><?php $xajax->printJavascript('./xajax/xajax_0.2.4');?></head><body><h1>Form to Create a Catalog Entry</h1><form id="validationForm" name="validationForm" onsubmit="xajax_updateCatalog(xajax.getFormValues('validationForm'));"><table><tr><td>Catalog Id:</td><td><input type="text"

size="20"id="catalogId"

name="catalogId"

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 13 of 23

autocomplete="off"onkeyup="xajax_validateCatalogId(xajax.getFormValues('validationForm'));"></td>

<td><div id="validationMessage"></div></td></tr>

<tr><td>Journal:</td><td><input type="text"size="20"

id="journal"name="journal"></td>

</tr>

<tr><td>Section:</td><td><input type="text"size="20"

id="section"name="section"></td>

</tr>

<tr><td>Edition:</td><td><input type="text"size="20"

id="edition"name="edition"></td>

</tr><tr><td>Title:</td><td><input type="text"

size="20"id="title"

name="title"></td></tr>

<tr><td>Author:</td><td><input type="text"size="20"

id="author"name="author"></td>

</tr>

<tr><td><input type="submit"value="Create Catalog"

id="submitForm"name="submitForm"></td>

</tr></table>

</form></body></html>

Next, run the input.php script in the Apache Web server. Copy input.php to theC:\Apache2\Apache2\htdocs directory. Run the PHP script with the URLhttp://localhost/input.php. The input form, as illustrated in Figure 1, gets displayed:

Figure 1. Input form

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 14 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Start adding a value for the Catalog Id field. A message gets displayed to verify if theCatalog Id field value is valid, as shown in Figure 2:

Figure 2. Validating input field

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 15 of 23

An XMLHttpRequest HTTP request is sent with each modification to the input field.

Figure 3. Adding Valid Input field Value

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 16 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

If a value is specified that is already defined in the Catalog table, a message"Catalog Id is not Valid" gets displayed, as shown in Figure 4. For example, add"catalog1" to Catalog Id field. As "catalog1" is already defined, the message"Catalog Id is not Valid" gets displayed.

Figure 4. Adding non-valid Input Field value

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 17 of 23

You can create a new catalog entry by specifying a Catalog Id field that is valid andadding values to the other form fields. Click on the Create Catalog button to createa catalog entry, as illustrated in Figure 5:

Figure 5. Creating a catalog Entry

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 18 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

If the Catalog Id field previously used to create a catalog entry, "catalog3" in theexample, a message, "Catalog Id is not Valid", gets displayed, as shown in Figure 6:

Figure 6. Adding a CatalogId for which a catalog entry has been created.

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 19 of 23

Posttodel.icio.us

Slashdotit!

In this article, you've seen how the asynchronous client-to-server XMLHttpRequestrequest provided by Ajax may be combined with PHP scripts to develop dynamicWeb applications. Use these examples to develop your own dynamic Webapplications to access your DB2 data.

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 21 of 23

Resources

Learn

• developerWorks resource page for DB2 for Linux, UNIX, and Windows: Readarticles and tutorials and connect to other resources to expand your DB2 skills.

• DB2 Express-C: Learn about the no-charge version of DB2 Express Edition forthe community.

• Ajax resource center: Learn more about Ajax.

• PHP project resources: Find project information for PHP developers.

• "Using Ajax with PHP and Sajax" (developerWorks, October 2005): Learn how touse Ajax with PHP, and get an introduction to the Simple Ajax Toolkit (Sajax), atool written in PHP that lets you integrate server-side PHP with JavaScript thatmakes this work.

• "Developing PHP the Ajax way, Part 1: Getting started" (developerWorks, May2006): Create a simple photo album as an online Web application, entirely in PHPand the Simple Ajax Toolkit (Sajax).

• "Developing PHP Applications for IBM Data Servers" (IBM Redbook, May 2006):Get an introduction on using PHP with IBM Data Servers. Find installation andconfiguration details for setting up the IBM data servers and Apache Webapplication server for PHP applications.

• "Connecting PHP applications to IBM DB2 Universal Database"(developerWorks, May 2006): Combine PHP with IBM DB2 Universal Databaseto create Web applications.

• "Connect PHP to DB2 and Cloudscape with PDO" (developerWorks, March2005): Learn how to obtain, install, and use PDO to connect to DB2 andCloudscape databases, insert and retrieve data, and explore more advancedfeatures, such as prepared statements, bound parameters, scrollable cursors,positioned updates and LOBs. Also, get a brief introduction on handling multibytedata.

• developerWorks Information Management zone: Learn more about DB2. Findtechnical documentation, how-to articles, education, downloads, productinformation, and more.

• Browse the technology bookstore for books on these and other technical topics.

Get products and technologies

• xajax_0.2.4.zip: Download the Xajax PHP class library.

developerWorks® ibm.com/developerWorks

Use Ajax with PHP and DB2 9 - XajaxPage 22 of 23 © Copyright IBM Corporation 1994, 2006. All rights reserved.

• php-5.2.0-Win32.zip: Download the PHP binaries.

• DB2 Enterprise 9: Download a free trial version.

• DB2 Express-C: Now you can use DB2 for free. Download a no-charge version ofDB2 Express Edition for the community that offers the same core data featuresas DB2 Express Edition and provides a solid base to build and deployapplications.

• Download IBM product evaluation versions and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus ®, Rational®,Tivoli®, and WebSphere®.

Discuss

• Participate in the discussion forum for this content.

• Check out developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Deepak VohraDeepak Vohra is a Web developer, a Sun Certified Java Programmer, and a SunCertified Web Component Developer. Deepak has published articles in XML Journal,WebLogic Developer's Journal, Java Developer's Journal, ONJava.com, and OracleMagazine.

ibm.com/developerWorks developerWorks®

Use Ajax with PHP and DB2 9 - Xajax© Copyright IBM Corporation 1994, 2006. All rights reserved. Page 23 of 23