function getDBConnection() { global $dbHostName, $dbUserName, $dbPassword, $dbName;

February 1st, 2007

function getDBConnection() { global $dbHostName, $dbUserName, $dbPassword, $dbName; // Get a persistent database connection if (!($link = mysql_pconnect($dbHostName, $dbUserName, $dbPassword))) { return new Function_Result( “Internal Error: Could not open database connection”, null); } // select mysql database if (!mysql_select_db($dbName, $link)) { return new Function_Result( “Internal Error: Could not selectdatabase “, null); } return new Function_Result(null, $link); } The functions open(), close(), read(), write(), destroy(), and gc() are the session handler functions which store the session data in the back-end database. One of the important requirements for the application was to store the session data in a MySQL table, so that it can be used by the instances of PHP running on different servers. The function open() is called for initializing the session storage. The function doesn’t do anything because the database table session is already created: function open($save_path, $session_name) { return true; } The function close() is the close handler of session storage. The function too doesn’t do anything: function close() { return true; } The function read() returns the session data of session with $id as its session identifier: function read($id) { global $dbHostName, $dbUserName, $dbPassword, $dbName; Open a persistent database connection: Page 557

Hint: This post is supported by Gama web hosting php services

function convertDateToMysqlFormat($dateStr) { list ($month, $day, $year) =

February 1st, 2007

function convertDateToMysqlFormat($dateStr) { list ($month, $day, $year) = split(”/”, $dateStr); return $year . “-” . $month . “-” . $day; } The function checkSessionAuthenticated() checks if the user session is authenticated. If the user session is not authenticated then the function sends a WML error page: function checkSessionAuthenticated() { global $isAuthenticated; Start the session: session_start(); Return true if the $isAuthenticated variable is stored in the session and its value is true. Else return an error page: if (session_is_registered(”isAuthenticated”) && $isAuthenticated) { return true; } else { sendErrorPage(”Unauthenticated Session”); exit; } } The class Function_Result encapsulates the return value of most of the functions. The member variable $errorMessage stores the error message, and the member variable $returnValue stores the return value. On failure the value of member variable $returnValue is null: class Function_Result { var $errorMessage; var $returnValue; The constructor of Function_Result sets the value of member variables $errorMessageand $returnValue: function Function_Result($errMessage, $retValue) { $this->errorMessage = $errMessage; $this->returnValue = $retValue; } } The function getDBConnection() returns the MySQL database connection: Page 556

Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Sandzak jsp web hosting provider

printf(”n”); } Most of the mobile devices do

February 1st, 2007

printf(”n”); } Most of the mobile devices do not support cookies, so we will have to use the session information in the URL itself. The function getSessionIdString() returns the session id string that will have to be appended to all the anchor elements generated by the PHP script: // Get the sessionId string function getSessionIdString() { return session_name().”=”.session_id(); } The function generateOptionElement() generates WML option element: // Generate option element function generateOptionElement($href, $displayText) { printf(”n”); } The function getDateString() returns the current date in the format YYYY-MM-DD, where YYYY corresponds to the year, MM to the month, and DD to the day component of the date. This function is used when inserting date columns into MySQL tables: // Returns Date function getDateString() { return date(Y-m-d); } The function convertDateFromMysqlFormat() coverts the date from YYYY-MM-DD format to MM/DD/YYYYformat. The argument $dateStr contains date in YYYY-MM-DD format: function convertDateFromMysqlFormat($dateStr) { list ($year, $month, $day) = split(”-”, $dateStr); return $month . “/” . $day . “/” . $year; } The function convertDateToMysqlFormat() converts the date from MM/DD/YYYY format to YYYY MM-DDformat: Page 555
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

The above screenshot displays the user’s account details.

January 31st, 2007

The above screenshot displays the user’s account details. The user should select the appropriate link to view the details of an order: The above screenshot displays the details of an item ordered by the user. From here, the user can either go back to the previous (view account) screen by selecting the BACK soft link, or can go to the home page of the application by selecting the HOME soft link: The Application Code Let’s walk through the code. The script Common.php contains variable definitions and functions that are used across the whole application. The following variables contain the information for accessing the back-end database. Before running the application, make sure you change these variables to reflect your installation environment: “); printf(”n”); Generate a WML card that displays the error message: printf(”n”); printf(”

n”); printf(”%s”, $mesg); printf(”

n”); printf(”n”); Page 554
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

Implementation We are now familiar with the requirements

January 31st, 2007

Implementation We are now familiar with the requirements and important design issues of the shopping cart application. It is a good time to walk through the code. This section assumes that the readers are familiar with the WML syntax. Let’s first look at the application screenshots. This will help us in understanding the code better. Import To run the application from your PC, you will have to use a phone simulator. I ant used UP Simulator for testing the application, available from http://developer.phone.com/download/index.html. This is the main page of the application. From here, the existing users can go to the login screen, or new users can register themselves. To register, new users enter their name, user id, password, address, and credit card details. The user will be presented with a series of input forms (one per screen) for entering these details. The above screenshot is the first screen where the user enters their first name. In WML all the input forms cannot be displayed in one screen because of the display size limitations of the mobile devices. If the registration is successful then the following page is displayed, else an error message is displayed. The user can go to the login page, by selecting the Login page link: To login to the site the user enters their user id and password. If the authentication succeeds, then the main page of the application is returned: The adjacent screenshot is the main page of the application. When the user chooses Search they are shown a screen describing the search functionality of the application. The user should select the soft link OK to go to the next screen: The adjacent screenshot is the first input screen of the search menu. Here the user enters the search text, and presses the soft link OK to go to the next screen. Next, the user selects the search criteria and selects OK. Now the search request is sent to the server: The adjacent screenshot displays the search results. The user can select the link to view the details of the item: The above screenshot displays the details of the searched item. The user can either add the item to his cart by selecting the soft link ADD, or can go back to the earlier screen (Search Results) by selecting the soft link BACK. The user can then either view the details of the added item by selecting its link, or can view the contents of the cart by selecting the Display Cart link, or can go to the main page of the application by selecting the soft link HOME: The above screenshot displays the contents in the user’s cart. The user can view the details of an item by selecting the appropriate link. From here, the user can either change the quantity of this item by selecting the soft link CHG, or go back to the earlier (display cart) screen by selecting the BACK soft link: The above page is displayed when the user goes to the check out. From here, the user can either view the shipping address details by selecting the Address Details link, or can view their credit card details by selecting Credit Card Detailslink, or can go to the home page of the application: Page 553
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

. Open a database connection . Execute SQL

January 31st, 2007

. Open a database connection . Execute SQL commands . Manipulate/display data . Close the database connection To save the overhead of opening and closing of the database connection for each invocation of the PHP program, persistent database connections will be used. Persistent database connections remain open, even after the PHP script that opened the connection has exited. For more details on persistent database connections, refer to Chapter 17. Import ant Persistent connections will be useful only when PHP is configured as a module in the web server. See Chapter 2 for more details. Page 552
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

Design Consideration for the Middle Tier In this

January 31st, 2007

Design Consideration for the Middle Tier In this section we will make important design decisions and set guidelines that will be followed by all the application’s PHP scripts. Authentication The user, when entering the site, enters their user id and password. The PHP script verifies the user id and password, and, depending on the result, allows the user to use the application. After this, the user need not specify their user id and password again. The HTTP protocol is a stateless protocol, which means that for each browser request a new network connection is opened with the web server. The PHP script (running on the web server) should have a mechanism to identify the user from the request. The shopping cart application will use PHP sessions to implement the authentication mechanism. The application will create a PHP session after the user is authenticated. The user id and the isAuthenticated flag will be stored in the PHP session. All the PHP scripts will use the session variable isAuthenticated, to find out if the session is authenticated. The user of the session can be found from the value of session variable $userId. Session Storage One of the requirements of the application was to support multiple instances of the middle tier. This would require additional load balancing software that would distribute HTTP requests (depending on the load balancing policy) to different middle tier servers. Now the deployment scenario will look something like this: With the above deployment scenario, requests of a session might get forwarded to different middle tier servers. This would require the sessions to be shared across all the middle tier servers. The default session implementation of PHP does not allow session sharing between multiple PHP instances running on different machines. We will implement session handlers to store and retrieve session data from the back-end database. With these session handler functions, middle tier instances running on different machines will be able to share PHP sessions. This scheme of storing sessions in the database provides additional reliability, which means that the user will be able to access the application even if one of the middle tier instances goes down. WML Issues The application implementation will follow the following guidelines to take care of WML device constraints (small display size, navigational difficulty). A WML introduction has been provided along with the code which can be downloaded from the Wrox web site at http://www.wrox.com/: . Only relevant information, with links to get the details, will be displayed in the first card of the WML page. For example, in the first card of the search results page only the titles of the searched items will be displayed as links pointing to another card in the same page. The user can select the link to get the details of the item. . Only three items will be displayed per WML page. A link will be provided to view next items. For example, if there are ten transactions in a user’s account, then the view account details page will display only the first three transactions in the first page and will provide a link View Next Items (pointing back to the server), to view the remaining transactions. . A HOME link, pointing to the main page of the application, will be provided in all the WML cards. The user can select the HOME link anytime for going to the main page of the application. This way the user will have to traverse only two links to access any functionality. The WML page is of mime type text/vnd.wap.wml, so all the PHP scripts will send the Content-Type: text/vnd.wap.wml HTTP header. Performance Most PHP programs that access a back-end database will do the following tasks: Page 551
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

itemType VARCHAR(20) NOT NULL, title VARCHAR(60) NOT NULL,

January 31st, 2007

itemType VARCHAR(20) NOT NULL, title VARCHAR(60) NOT NULL, artist VARCHAR(60) NOT NULL, price FLOAT NOT NULL, PRIMARY KEY(itemNo)); CREATE TABLE Transaction ( orderNo INT NOT NULL PRIMARY KEY AUTO_INCREMENT, userId VARCHAR(20) NOT NULL, itemNo VARCHAR(20) NOT NULL, quantity INT NOT NULL DEFAULT 0, date DATE NOT NULL, status VARCHAR(20) NOT NULL); CREATE TABLE Session ( lastAccessed TIMESTAMP, id VARCHAR(255) NOT NULL, data TEXT, PRIMARY KEY(id)); Indices Indices are created on the ItemNo, Title, and Author/Artist columns of the BookShopand MusicShoptables. Creation of indices on these columns will result in faster searches in the database. Import Indices are used to find rows with a specific value for a column quickly. The ant index stores the mapping between the value of the column, and the physical location of the row. Without indices the database will have to do a complete scan of the table (lots of disk I/O), to search for rows with specific values for a column. SQL commands for creating indices (shopindices.sql): USE shop; CREATE INDEX indexOnBookItemNo ON BookShop(itemNo); CREATE INDEX indexOnBookTitle ON BookShop(title); CREATE INDEX indexOnBookAuthor ON BookShop(author); CREATE INDEX indexOnMusicItemNo ON MusicShop(itemNo); CREATE INDEX indexOnMusicTitle ON MusicShop(title); CREATE INDEX indexOnMusicArtist ON MusicShop(artist); Page 550
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

In our case, the database and the middle

January 31st, 2007

In our case, the database and the middle tier will be hosted on different machines. So, grant all privileges on all objects in the shop database to user PHP, connecting from any machine: mysql> GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO ‘PHP@%’ IDENTIFIED BY “PHP”; Execute the following SQL script (shop.sql) at the command prompt to create the shopdatabase and tables: mysql < shop.sql CREATE DATABASE IF NOT EXISTS shop; USE shop; CREATE TABLE UserProfile ( fname VARCHAR(32) NOT NULL, lname VARCHAR(32) NOT NULL, userId VARCHAR(16) NOT NULL, password VARCHAR(16) NOT NULL, address VARCHAR(128) NOT NULL, city VARCHAR(64) NOT NULL, country VARCHAR(16) NOT NULL, zipCode VARCHAR(8) NOT NULL, gender VARCHAR(8) NOT NULL, age INTEGER NOT NULL, emailId VARCHAR(64) NOT NULL, phoneNumber VARCHAR(16) NOT NULL, cardNo VARCHAR(16) NOT NULL, expiryDate DATE NOT NULL, cardType VARCHAR(16) NOT NULL, accountBalance FLOAT NOT NULL, PRIMARY KEY(userId)); CREATE TABLE BookShop ( itemNo VARCHAR(20) NOT NULL, itemType VARCHAR(20) NOT NULL, title VARCHAR(60) NOT NULL, author VARCHAR(60) NOT NULL, price FLOAT NOT NULL, PRIMARY KEY(itemNo)); CREATE TABLE MusicShop ( itemNo VARCHAR(20) NOT NULL, Page 549
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

Column Name Description Author Author of the book

January 31st, 2007

Column Name Description Author Author of the book Price Price of the book The MusicShop table contains the description of available music titles: Column Name Description ItemNo Unique identifier for the music album ItemType CD/Cassette Title Title of the album Artist Artist Price Price of the album The Transaction table contains the records of user’s transactions: Column Name Description OrderNo Unique identifier for the user’s transaction. UserId User id of the user. ItemNo Unique identifier identifying the item. There must be a corresponding row for this item in either MusicShopor BookShop table. Quantity Number of ItemNo items ordered by the user. Date Date when the user did the transaction. Status Status of the item shipped/pending. The Session table, stores the data of PHP sessions: Column Name Description lastAccessed Time when the session was last accessed Id Unique session identifier Data Session data Database User One database user, PHP, is created for the shopping cart application. All the PHP scripts in the middle tier connect to the back-end database as user PHP. This user has all privileges on the tables of the shopping cart application. We need SQL commands for granting privileges on the tables in the shop database to the user PHP. To do so, execute the following SQL statement. The mysqlutility can be used for executing SQL commands. mysql> GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO ‘PHP@localhost’ IDENTIFIED BY “PHP”; Page 548
Hint: If you are looking for good and high quality web space to host and run your java application check Vision java web hosting services