Functions are used to break large blocks of code into smaller, more manageable units. Code contained inside of a function performs a specific task and returns a value. PHP includes two types of functions – user defined or those created by the programmer and internal (built-in) functions which are a part of the PHP language definition. This first section focuses on creating and using user defined functions.
User defined functions are created using the function keyword. User-defined functions are useful particularly in larger PHP programs because they can contain blocks of code that can be called or used in the program without having to continuously re-write the code. The following is an example of a simple PHP user defined function:
Read more…
The ability to reuse exsiting code is important because it can save time, money, and promote consistency. Suppose a web site contains menu text that is repeated on each page. Instead of re-coding the menu, it would be much easier to code the menu once and dynamically include the menu contents on each of the individual web pages. This is possible using what are know as server-side include files.
Include files can contain any XHTML or PHP code and are usually saved with the .inc extension, although .php, .txt, or .htm can also be used. The contents of an include file are coded once and included in as many PHP pages as needed. If a change is made to an include file, the updates are automatically reflected on all of the PHP pages referening the include file.
Read more…
The foreach construct is a variation of the for loop and is used to iterate over arrays. There are two different versions of the foreach loop.
Read more…
The for statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the for loop is known as a definite loop.
Read more…
The do…while statement loops through a block of code as long as a specified condition is evaluated as true. In other words, the while statement will execute a block of code if and as long as a condition is true.
The do…while loop is similar in nature to the doloop discussed in the previous section. The key difference is that the do…while loop body is guaranteed to run at least once. This is possible because the condition statement is evaluated at the end of the loop statement after the loop body is performed. Read more…
In programming it is often necessary to repeat the same block of code a number of times. This can be accomplished using looping statements. PHP includes several types of looping statements. This section focuses on the while loop.
The while statement loops through a block of code as long as a specified condition is evaluated as true. In other words, the while statement will execute a block of code if and as long as a condition is true.
Read more…
In addition to the if Statements discussed in the previous section, PHP includes a fourth type of conditional statement called the switch statement. The switch Statement is very similar or an alternative to the if…else if…else commands. The switch statement will test a condition. The outcome of that test will decide which case to execute. Switch is normally used when you are finding an exact (equal) result instead of a greater or less than result. When testing a range of values, the if statement should be used.
Read more…
It is often desirable when writing code to perform different actions based on different decision. In PHP this is possible using conditional statements – The if Statement, the if…else statement, and elseif statement.
Read more…
The basic PHP date and time functions let you format timestamps for use in database queries or simply for displaying the date and time in the browser window. PHP includes the following date and time functions:
Read more…
A string is a series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings. String values can be used literally or be assigned to variables.
Read more…
Operators are used to perform operations or actions on variables. This can include assigning a value to a variable, performing addition with variables, comparing the value of variables, and to determine the status of a condition.
Read more…
A constant, like a variable, is a temporary placeholder in memory that holds a value. Unlike variables, the value of a constant never changes. When a constant is declared, the define() function is used and requires the name of the constant and the value you want to give the constant.
Read more…
While a PHP scalar variable stores a single value, an array variable can be used to store a set or sequence of values. PHP supports numerically indexed arrays and associative arrays. An array in PHP is actually an ordered map. A map is a type that maps values to keys. Array variables consist of two parts – an index and an element. The array index, sometimes referred to as the array key, is a value used to identify or access array elements. The array index is placed in square brackets. Most arrays use numeric indices that typically start with 0 or 1. In PHP associative arrays can use string indices. Both types of arrays are created using the array() construct.
Read more…
Variables are temporary place holders used to represent values used in a PHP script. PHP includes two main types of variables: scalar and array. Scalar variables contain only one value at a time , and array variables contain a list of values. Array variables are discussed in the next section. PHP scalar variables contain values of the following types:
Read more…
Comments are used in PHP to allow you to write notes to yourself during the development process. Such comments may define the purpose of a code segment or to comment blocks of code while testing scripts.
Read more…
Each line of code in PHP must end with an instruction terminator also know as the semicolon (;). The instruction terminator is used to distinguish one set of instructions from another.
Read more…
PHP includes two basic statements to output text to the web browser: echo and print. Both the echo and print statements are coded between the opening and closing PHP code block tags and can occur anywhere in the XHTML documents.
Read more…
PHP code is normally mixed with XHTML tags. PHP is an embedded language which means that you can jump between raw HTML code and PHP without sacrificing readability.
In order to embed PHP code with XHTML, the PHP must be set apart using PHP start and end tags. The PHP tags tell the web server were the PHP code starts and ends. The PHP parser recognizes three sets of start and end tags.
Read more…
PHP stands for PHP Hypertext Preprocessor. It is a server-side programming language specifically designed for creating dynamic web pages. The language was originally developed in 1994 by Rasmus Lerdorf and has since been expanded to become one of the WWW’s most popular scripting languages. According to 2005 Netcraft statistics, PHP is currently being used in over 23,000,000 domains. Like other types of server-side languages such as ASP, ASP.NET, and JSP, PHP code is processed on the web server and generates the XHTML code or other output that can be viewed in the browser. Unlike other server-side languages, PHP is an open source product, meaning everyone has access to the source code and can use, alter, and redistribute it all without charge.
Read more…
The final success of an e-commerce site is getting the money into the bank. For this purpose you must integrate your site with a credit card processing service. This service handles all the details of interacting with your customers over a secure connection, collecting credit card information, interfacing with the Federal banking system to debit and credit bank accounts, and notifying your site of the success of the transactions.
There are numerous commercial services available at various setup costs, transaction fees, and volume limits. For instance, a popular online payment service has entry-level costs including a $179 set-up fee and a $20 per month transaction fee for up to 500 transactions per month. Other fees are applicable for additional customer and merchant support services. In contrast, a payment service such as PayPal can be joined at no set-up cost and very modest transaction fees of around 3.5% of sales. Since this latter service is widely popular, the steps involved in integrating your e-commerce site with PayPal are summarized below. They are typical of integration with most commercial services.
Read more…
In returning the customer to the eCommerce site following credit processing, a short detour is made through the OrderCapture.aspx page to generate an email confirmation. From the OrderCapture.aspx page the customer arrives at the SalesOrder.aspx page where a summary of the order is displayed. Customers are encouraged to print the sales order for their records.
Read more…
The OrderCapture.aspx page is linked from the credit card processing site (locally, the OrderForm.aspx page). The purpose of this page is to capture returned order approval and customer information sent through a submitted form.
An eCommerce site requires information about customer purchase transactions in order to keep its own books in order. For instance, it needs to know if the purchase was approved; it needs to know the shipping address of the customer to send the merchandise; and it needs to know the dollar amount of the approved purchase to update its accounting system. Ancilliary processing that can take place includes updating the inventory system to reduce the quantities of items on hand by the quantities purchased. Information to initiate this processing is produced or gathered by the credit card processing service and packaged into a return form sent to the eCommerce site.
Read more…
The CreditCheck.aspx page is linked from the SubmitForm.aspx page, having been passed form information concerning the customer’s order. The page shown below is displayed to collect credit card information and to pass approval and processing results back to the eCommerce site. This page is assumed to be external to the eCommerce site. Often times the credit card processing service permits use of logos and styling schemes to format the page to resemble a page from the merchant site.
Read more…
A click on the “Checkout” button on the shopping cart page begins a series of steps to finalize purchase of items listed in the shopping cart. Normally, the eCommerce merchant has established an account with an external credit card processing service which handles all the financial and banking transactions surrounding the order. Involvement of the eCommerce site is minimal. Although this example site does not have formal arrangements with a commercial credit card processing service, it does illustrate the typical manner of interacting with such a service.
Read more…
The ShopCart.aspx page is visited by clicking on the menu link. It displays the current items in the ShopCart table for this customer. Options are provided to change the quantities ordered for any book or to delete the book from the shopping cart. A button is displayed to continue checkout processing.
Read more…
The Details.aspx page gives full information about a book chosen on the Search.aspx or Specials.aspx page. While viewing this information, visitors can add this book to their shopping carts.
Read more…
The eCommerce site offers two ways to search for Books. The visitor can click a category link to view all books within that category; or a word or partial word can be entered into the search box to locate all books containing that text string in its database fields. The following illustration shows the Search.aspx page after locating all books in the “Database” category. A similar display appears for all books with field values containing the search text.
Read more…
Below is shown the general layout for all of the pages of the eCommerce Web site. It is based on the use of a master page to present the common elements, which include the banner across the top of the page and the site menus down the left. Different content appears in the right-hand section of the page when menu links are clicked or when performing book searches.
Read more…
At this point a number of previous learnings can be pulled together to illustrate the integration of Web pages and workflows that tie them together. The following set of tutorials lead you through the steps for developing an online commercial Web site for selling products. This example uses the BooksDB.mdb database of books from previous tutorials. There is occasion in these examples to explore most of the considerations in developing an online store. The following illustration outlines the pages and links that comprise the site. General descriptions of these pages are given below.
Read more…
A theme is a collection of property settings used to define the visual appearance of pages and their controls for consistency across the pages of a Web site. A theme can be applied to an entire Web site, to a single page and its controls, or to an individual control. There is similarity to applying Cascading Style Sheets, with the addition of control properties for which there are no CSS equivalents. Read more…
The <asp:Wizard> control is a container for a group of <asp:WizardStep> controls, where each WizardStep is a visible portion of a page to display. Like the MultiView control, the Wizard control reveals individual screens coded on a single page. Whereas the MultiView is especially designed for use on mobile devices with restricted screen sizes, the Wizard is designed to manage a set of data entry screens. Various input controls such as textboxes, radio buttons, checkboxes, and drop-down lists can be packaged as separate screens in a sequence of data entry steps. At the completion of this process, entered data can be saved to an external data source as captured information.
Read more…
The <asp:MultiView> control is a container for a group of <asp:View> controls, where each View control is a visible portion of a page to display. Each View represents a series of steps in an application that otherwise would require coding of separate pages. The Views are revealed according to user preferences or in a scripted sequence. The MultiView is particularly applicable to mobile devices with small screens that cannot render a page in full but in incremental steps revealing a portion of the page at a time.
Read more…
One of the ways to provide a Web site menu is by using an <asp:Menu> control, either hard coded with page links or in connection with an <asp:SiteMapDataSource> control to import an external file of links. This type of menu displays static and PopOut menus for navigating the site. A second way to populate a site menu is with an <asp:TreeView> control that provides the same functionality as a Menu control but in the form of expanding and contracting menu items. An example of a site with a TreeView menu is shown in Figure 12-18. As in previous examples, this menu is coded on the master page for the site.
Read more…
One of the great advantages of using an external site map—coded in the default web.sitemap file or in a special site map provider—is that the external file also can be the source of a breadcrumbs navigation trail. You probably have encountered these navigation trails on many sites. They list the trail of pages that you have navigated to reach the current page, and you can backtrack through the list by clicking on the listed links.
A breadcrumbs navigation trail is shown in the top row of following example. Select the path “Page 3
Page 3-2
Page 3-2-1″ to view the full extent of the trail. Then click the breadcrumb links to backtrack through the pages of the menu hierarchy.
Read more…
Coding navigation menu items inside the <asp:Menu> control works fine for small Web sites. Once a site grows to a large hierarchy of pages, though, it becomes more difficult to maintain the menu since it means editing the Web page itself. A better solution is to move the menu items to an external file where the menu can be maintained apart from the Web pages which use it.
A common way to maintain a site menu is as an external XML file. Since XML data has a natural hierarchical structure, it is compatible for representing the structure of a hierarchical menu. An XML menu file can be linked to an <asp:Menu> control and used in the same fashion as if the menu had been coded internally as part of the control.
An external site menu is known as a site map. It is made available to an <asp:Menu> control through an <asp:SiteMapDataSource> control, much in the same way as an AccessDataSource feeds data to a GridView, DetailsView, FormView, or other type of bound information display control. Its general format is shown below.
Read more…
Navigation between pages of a Web site is conventionally set up with standard <a> anchor tags linked to the various pages. Often, this set of tags is enclosed inside a menu section on a page and duplicated across all pages that shares these navigational links. Of course, when using master pages, this set of links can be created one time only on the master page for display on all associated content pages.
It is not unusual that Web site navigation links change over time as new pages are added to a site, old pages are removed, and other pages are shifted around. There is routine need, then, to reconfigure these links. In this sense, navigation links are no different from other content information maintained for the Web site. They represent dynamic data that change over time. As such, there is convenience in being able to maintain this information apart from the pages on which it appears. Maintaining the navigational structure of a Web site in an external data store, rather than hard coded on the page, enhances the ability to keep it up to date.
ASP.NET 2.0 introduces the <asp:Menu> control to help manage the navigational structure of a Web site. It is used to create static links, much like hard coding <a> tags; it also permits maintenance of a site’s navigational links in an external file for convenience in changing the links and, effectively, changing the structure of the site.
Read more…
One of the main issues in putting together a Web site with multiple pages is coordinating the overall look and feel of the site. Normally, you wish for the site to be visually consistent from page to page and to operate navigationally in a consistent manner. This usually means that you must take great care to duplicate common elements on each page, using identical layout tags, titles, banners, menus, and the like. Although this effort produces the required consistency, it doesn’t go unpunished. Any time a change is made to common elements on one page it must be propogated to the remaining pages, a pesky and sometimes error-prone task.
Relief from the tedium of creating and updating the look and behavior of common page elements is at hand with ASP.NET master pages. A master page is a template page that defines the standard visual elements and behaviors that you want for all the pages at your site. Then, during site navigation, individual content pages are merged automatically with this master page to deliver changing content within the framework of the master page. A master page is created one time, and changes to common elements occur in one place.
Read more…
This first example of a Web Service is fairly simple. Suppost you have written a function that reports the number of shopping days until Christmas. This is generally useful knowledge which could be of interest to other sites which might wish to supply this same information to their applications. You decide, then, to package this function as a Web Service and make it available to other sites. They might pay big bucks to access your function rather than having to write their own original code.
Read more…
As described so far, the programming of ASP.NET pages is purely a “local” phenomenon. That is, scripts are contained on the same pages that access them, or they are packaged as code-behind files residing on the same local server. The point is, access to your scripts is restricted to the local pages that use them. It is not possible for users to run you scripts except within the confines of your own applications.
Normally, this restricted access to processing routines is not an issue. Your scripts are written for the special purposes of your applications, and there is little reason outsiders need access to them. By the same token, there may be little reason for your applications to access scripts housed on somebody else’s server. However, consider a couple of scenarios in which this might not be the case—where remote uses do need access to your scripts or where you need access to remote scripts.
Read more…
The <asp:ObjectDataSource> control can be employed along with DataSets to provide database maintenance functions. Recall that DataSets are in-memory tables that are filled with data from database tables. Manipulation of this information takes place in memory, with changes written back to the database through the DataSet’s Update() method. When using DataSets, it is not necessary, even, to supply SQL INSERT, UPDATE, or DELETE statements to rewrite changes to the database. These statements are composed and issued for you.
Read more…
The <asp:ObjectDataSource> control contains, besides the SelectMethod to retrieve information from a database, three additional methods to perform the full range of database operations. The UpdateMethod changes information in a database; the InsertMethod adds a new record to a database; and the DeleteMethod deletes a record from a Database. These methods are applied through bindings to server controls that permit these operations.
Read more…
The purpose of code-behind development is to encapsulate the business logic behind an application within separate, stand-alone software components. The goal is to divide an application into different layers, or tiers—a business logic layer and a user interface layer. Doing so promotes creation of processing components that can be shared among multiple pages, and it becomes easier to maintain the components separately than if coded multiple times on multiple pages.
A second way to encapsulate page components within different layers is to separate “data access” from the user interface. In previous applications this has been accomplished with code-behind files in which data access is part of the processing logic. ASP.NET 2.0 introduces more direct ways to create a data access layer.
Read more…
One of the purposes of creating code-behind files is to use them as business components, independing processing routines that are sharable among different pages. In this way, a generally useful processing routine does not have to be duplicated on all pages that need it; any page can inherit its class definition and take advantage of its processing. Therefore, the code-behind file needs to be independent of any page that uses it.
Read more…
It is often the case that Web developers do not have the aesthetic sense nor the understandings of cognitive psychology to create attractive, user-friendly Web sites. For this reason, many companies divide the work of Web site development between two individuals or teams, one responsible for design features, the other for technical details. In other words, a Web page is divided into presentation and application logic components, each of which is handled by separate individuals or groups. In short, the HTML portion of a page is separated from the script portion of a page such that each can be designed and coded independently of the other.
This idea of separating presentation from application logic is inherent in ASP.NET pages that include both. The use of server controls enforces this separation. There is physical separation between the controls residing in the <HTML> section of a page and the programming of those controls in the <SCRIPT> section of the page. Still, ASP.NET goes a step further. Techniques exist to divide presentation from application logic as independent files. This separation permits two teams of developers to work independently on these two different aspects of page design, and to have them brought together as a functional whole when the page is accessed over the Web.
This feature of ASP.NET is called code-behind development. Using the code-behind approach you can place your page’s application logic (its scripting) into a separate file from your page’s content presentation (its XHTML code and server controls). Even if you have responsibility for both aspects of page design, the use of code-behind encourages development of standardized processing components that can be reused on multiple Web pages.
Read more…
Recall from previous discussions that a Web page can be characterized as implementing three application levels, or tiers. These tiers are
- user interface – the Web page as it appears on-screen to the user and through which the user interacts with the page;
- application (business) logic – page processing as encapsulated within subprograms and functions organized within scripts; and
- data access – retrieval and updating of information residing in external data stores such as databases and files.
Up to this point, Web page development has been viewed as the detailed coding of all tasks—of all application tiers—necessary to carry out page processing. Server controls and XHTML code are placed on a Web page to represent the visual, on-screen appearance of the page and to supply mechanisms through which the user interacts with the page. Visual Basic subprograms and functions are coded within the script section of the page to carry out processing tasks in response to user requests. Various server controls and scripts issue SQL commands or activate stored procedures to handle data access chores surrounding the page. In other words, everything needed to carry out page processing is encapsulated on that very same page.
Read more…
A recurring need for many Web sites is to generate and send email messages. A commercial site, for instance, normally sends order confirmations to customers who purchase products or services. Sites with memberships routinely correspond with members to keep them up to date on site policies and features. In other cases, automated email feedback is provided when inquiries are made. There are numerous occasions in which Web pages need to handle routine email correspondence to relieve individuals from having to manually produce email themselves.
ASP.NET pages can be configured to send email through the server’s SMTP (Simple Mail Transfer Protocol) service. This is, as the name implies, a limited email service; however, it is sufficient for generating and sending automated emails from Web pages. The SMTP service is included as a component of Microsoft Windows Server and XP Professional. It may have to be installed and initiated if it were not part of a default installation.
Read more…
A very useful file access feature under ASP.NET is its file upload capability. You can present a form containing a text box and browse button for users to navigate their local PC directories to locate a file for uploading. By clicking a button users can copy the local file to a server directory. This feature is illustrated by creating a file upload form for copying book pictures to the c:\eCommerce\BookPictures directory. The upload function is disabled, but you should get a good sense of how it works. The following form restricts uploads to JPG files no larger that 100 KB.
Read more…
Among all the fancy data storage methods available under ASP.NET there is still comfort in working with plain vanilla text files. They are trusted friends. ASP.NET supplies file objects that make it very easy to read and write text files.
The System.IO namespace must be imported for working with files. This namespace gives access to the StreamReader and StreamWriter classes for reading and writing text files.
Read more…
The ASP.NET File class provides access to the files comprising an application. Through various methods supplied by this class scripts can create and delete files, move and copy files, read and write files, and view file attributes. Again, caution is advised when using File methods since files can be easily deleted without recourse to recovering them.
Read more…
Up to this point, most of your work has involved accessing and maintaining the central repositories of information that feed Web sites. Database activity is one of the central activities in site content management, involving the collection, organization, storage, retrieval, and maintenance of the primary content appearing on Web pages. Yet, there are other important surrounding tasks that go along with database management. Particularly, you need to set up and work with the directory and file structures within which all this activity takes place.
It may be that you have direct physical access to the Web server that hosts your site. If this is the case, then you can sit down at the server console and create and manage the folders and files you need. If you are hosted by a remote Internet Service Provider (ISP), you probably have FTP access to your main Web directory to which you can transfer files and otherwise work with your site structure. A third option is to create your own Web pages to handle directory and file access, much in the same way that your pages handle database access. In fact, ASP.NET supplies a collection of software classes that permit you to work with your site structure and its contents through your own Web pages in nearly identical fashion to having direct console or FTP access. It is not necessary to rely on physical access or third-party hosts to manage your site.
Read more…