Examples


On the CD This section starts with simple examples of ASP and PHP. It is important for you to try them because it will determine that you have workable arrangements with your server. Keep in mind that ASP and PHP scripts must run on a server computer. You will upload the examples to the server using a program such as ws-ftp, or you will run them on your own computer after establishing your computer as a server using Personal Web Server or Windows IIS or another facility. The remaining examples are the ASP and PHP implementations of a quiz program on the states and the capitals. The example demonstrates use of form input, multiple scripts, and several programming features. You will find the code for the simple examples and the two state capital applications on the CD-ROM in the folder named chapter4code.

Beginning ASP and PHP Scripts

Write the following and save it as test.asp.

    <%@ language="JavaScript"%>     <html><head><title>First ASP </title>     </head>     <body>      <%     Response.Write ("This was done on the server");     %>     </body>     </html>

Upload this to your server and open it. You should see the display produced by the following HTML file:

    <html>     <head><title>First ASP </title>      </head>     <body>     This was done on the server     </body>     </html>

Similarly, write the following and save it as test.php.

    <html>     <head><title>First PHP </title>     </head>     <body>     <?php     print("This was done on the server");     </html>     ?>

If you have taken any computing course and feel obliged to do a Hello, world program, feel free to do one or both as an exercise. For PHP, there actually is a standard first program and it is the following:

    <html>      <head><title>First PHP </title>     </head>     <body>     <?php     phpinfo();     </html>     ?>

The function phpinfo() is an example of a built-in function; it is part of the PHP language. The opening and closing parentheses with nothing in between indicate that it is a function without arguments. No information is passed to the function. This particular function will display on the client computer a very lengthy list of information about the server. Try it; type it up; save it as phptest.php; upload it to your server; and then open it using a browser. You will see an extensive display of information on the settings of your server.

States and Capitals Quiz

The next set of examples (one in PHP and one in ASP) will implement a quiz/drill on U.S. states and their capitals. This requires information to be kept on the server; namely, the 50 pairs of state name and capital name. For these examples, the information will not be in a database but in a file on the server. The application is implemented using three files: one file presents one form to the player (the person at the client computer) giving a choice of how to ask the question and then presents the question, also using a form. The second file checks the answer. A third file holds the state/capital information.

Both the PHP and the ASP implementations of the quiz use a trick common to middleware projects. Files (scripts) both present forms and handle form input. You write program logic to detect which of the situations it is by checking on form input. The plan is to have one script present the question choice and then the question and another check the result. If the player gets it wrong, the program presents two options: get a new turn, or try again with the same question.

Now, at this point, there is a semantic issue on how to phrase the question giving the player a choice in the asking of the question. The first form is for the player to choose between being told a state (e.g., New York) and being asked for its capital (Albany), or being told a capital (Albany) and being asked to come up with its state (New York). Rather than presenting this very long message, this example produces the screen shown in Figure 4.1.

click to expand
Figure 4.1: Initial screen for state capital quiz.

If the player clicks the radio button to the left of State and then clicks the Submit choice button, the next screen will resemble Figure 4.2.

click to expand
Figure 4.2: Asking for the capital.

The reasoning here is that the state is what gets named and the player must supply the capital. Good people might claim that being “asked the state” should mean the opposite: being told the capital and being asked to come up with the state.

Let’s show the rest of the screens before turning to the code. Memphis is a city in Tennessee, although not the capital. Programming games (and other applications) require you to try all types of input, including incorrect answers. Figure 4.3 shows the player entering an incorrect answer.

click to expand
Figure 4.3: Player enters an incorrect answer.

After clicking the Submit Answer button, the person who entered Memphis would see the screen in Figure 4.4.

click to expand
Figure 4.4: System responds to incorrect answer.

The player has a choice of giving up on this state and getting the very first screen again with the choice of type of question, or trying again. Let us say the player chooses to try again and with the correct answer. The resulting screen is shown in Figure 4.5.

click to expand
Figure 4.5: System responds to correct answer.

This sequence does not test all the possibilities. For one thing, the choice of being asked a capital first was not shown. When you prepare this and any other project, you need to try all possibilities and all combinations (sequences) of possibilities. However, it is time to look at the scripts.

Here is the outline for the miniquizask script.

HTML including head section, start of body, and a header

Get into PHP or ASP

Make the choice of state/capital using a facility that produces random results

Determine if the player has been shown the choice form

If this is the case, then determine if the choice was state or capital

If state, present that question (display that form)

If capital, present that question (display that form)

If the player has not been shown the choice form yet, display it

Get out of PHP or ASP and produce the rest of the HTML

States and Capitals Quiz in PHP

Having determined the general approach, now is the time to get into the nitty-gritty code, starting with the PHP version. Remember that the PHP script outputs HTML using the print function. To produce a line break in the HTML file, the print function outputs the special symbol \n. Keep in mind that this is only for the HTML file. To get the browser to display a line break on the screen, the PHP file needs to include a <br> or a <p> either in the HTML that occurs outside the delimiters for the PHP or inside the string arguments of a print function.

    <html>     <head><title>Mini-quiz: ask</title>     </head>     <body>     <h1>State Capital Quiz </h1><p>     <?php     if (@$saywhich){       include("statecapitals.php");       $choice=rand(0, 49);       if ($which=='state') {       $state = $states[$choice];       print("What is the capital of $state?<br>");       print("<form action='miniquizcheck.php' ");       print("method='get'>\n");       print("<input type='text' name='capital'><br>\n");       print("<input type='hidden' name='which' ");       print("value=$which>\n");       print("<input type='hidden' name='choice' ");       print("value=$choice>\n");       print("<input type='submit' value='Submit Answer'>");       print("</form>\n");     }     else   {       $capital = $capitals[$choice];       print("$capital is the capital of which state?<br>");       print("<form action='miniquizcheck.php'");       print(" method='get'>\n");       print("<input type='text' name='state'><br>\n");       print("<input type='hidden' name='which'");       print("value=$which>\n");       print("<input type='hidden' name='choice' ");       print("value=$choice>\n");       print("<input type='submit' value='Submit Answer'>");       print("</form>\n");      }     }     else {        print("Choose form of question: ");        print("do you want to be given the state ");        print("or the capital?<br>");        print("<form action='miniquizask.php' ");        print("method='get'>\n");        print("Ask <input type='radio' name='which' ");        print("value='state'>State");        print(" <input type='radio' name='which' ");        print("value='capital'>Capital\n");        print("<input type='hidden' name='saywhich' ");        print("value='true'>\n");        print("<input type='submit' ");        print("value='Submit choice'>");        print("</form>");     }     ?>     </body>     </html>

Look at the overall structure of the code (trying not to get caught up initially in the details). You will see that it does follow the outline. There is an outer if/else statement, and within the first clause of the if statement, there is another if/else statement. Notice also that the script goes in to and out of PHP. You have some flexibility in how often you choose to do this. For example, in the preceding code example, starting with the else, you could write:

    else {     ?>     Choose form of question: do you want to be given the      state or the capital?<br>     <form action='miniquizask.php' method='get'>     Ask <input type='radio' name='which'      value='state'>State     <input type='radio' name='which'      value='capital'>Capital     <input type='hidden' name='saywhich' value='true'>     <input type='submit' value='Submit choice'>     </form>     <?     }     ?>     </body>     </html>

In all the clauses, there are several print statements, outputting HTML to the client computer. The arguments of the print statements include <form …> and <input …> tags. There is a mixture of HTML and PHP variables. Single quotes are used within strings that are defined using double quotes. The form presenting the choice of question has this script as the handler by citing it as the value of the action attribute. The forms that actually ask a question specify miniquizcheck.php as the action attribute.

The condition tested by the outermost if statement is intended to ask: should the player be shown the form for indicating choice of question, or has this been shown and the program needs to interpret and act on the result? The construction in PHP is:

    if (@$saywhich)

The @ symbol tells the PHP interpreter to not complain if the $saywhich variable does not exist because, indeed, it might not exist. That is exactly what you want to test for in this situation. In other situations, a variable or form input value not existing would be an error and you want the system to let you know. If $saywhich does not exist, essentially if it has not been set, then the condition is false. The else clause is what is executed, and the initial form offering the choice about the question is displayed. Notice that ‘saywhich’ is a hidden input tag and its value is set to true. Hidden input tags are ways to carry information from one script to another or one script to itself. If the $saywhich variable exists and has been set to true, the first clause of the if statement gets executed.

At this point, you might be asking, where are the states and the capitals? That information is in a separate file called statecapitals.php. The start of that file is:

    <?php     $states =  Array();     $capitals= Array();     $states[]='Alabama';$capitals[]='Montgomery';     $states[]='Alaska'; $capitals[]='Juneau';     $states[]='Arizona';$capitals[]='Phoenix';           …

The delimiter <?php is necessary to specify that this script is PHP code. This is not strictly logical, but omitting it makes the entire file be displayed in the HTML document. The next two lines set up two array variables, one called $states and the other $capitals. The following statements come in pairs, and each statement in a pair adds an element to the appropriate array. The fact that they are in pairs means that the Ith element of $states corresponds to the Ith element of $capitals. Arrays are indexed starting with zero and ending with one less than the number of elements. Therefore, the $choice variable, which is set to something between zero and 49, can be used to point to a state and a capital that match.

At this point, to understand the code, you need to go back and forth between the forms. The form presenting the choice of question to the player will set $which. When the script is executed subsequently, $saywhich will be true, and the inner if statement checks if $which is equal to “state.” If it is, then the “giving the state” form of question is presented. Otherwise, the “giving the capital” form of question is presented. In either case, the $choice variable is passed to the next script in the form of hidden data.

The code here uses the get method so you can see what your scripts are doing. After you get the scripts working, change to the put method. This is preferable for this type of application. For PHP, you simply change the method attribute in all the form tags. The code for reading the form input remains the same. For ASP, you need to do something more. The code to get (excuse the term) any form input acquired with the post method uses the Request.Form method.

Continuing with the example, here is an outline for the checking the result:

HTML start, head, title, body, heading

Start PHP or ASP

Using the form input indicated by choice, set up variables to hold the state and capital

If the question asked was ‘state’, check the answer (held in the capital form input)

If correct, say so and display a hyperlink back to the first script

If wrong, say so and display a hyperlink back to the first script and re-ask the question

If not (if the question asked was not ‘state’, that is, it was ‘capital’), check the answer (held in the state form input)

If correct, say so and display a hyperlink back to the first script

If wrong, say so and display a hyperlink back to the first script and re-ask the question

Close up PHP or ASP

Closing HTML material

Here is the code for miniquizcheck.php:

    <html>     <head><title>Mini-quiz: check answers</title>     </head>     <body>     <h1>State Capital Quiz </h1><p>     <?php     include('statecapitals.php');     $correctstate=$states[$choice];     $correctcapital=$capitals[$choice];     if ($which=='state')        {        if ($capital == $correctcapital)         {          print(           "Correct! $correctcapital is the capital of ");          print("$correctstate!");          print("<p><a href='miniquizask.php'>");          print("Play again </a>");         }        else {          print("WRONG!<p>\n");          print("<a href='miniquizask.php'>");          print("New turn </a><p>\n");          print("OR try again: What is the capital ");          print("of $correctstate?<br>");          print("<form action='miniquizcheck.php' ");          print("method='get'>\n");          print("<input type='text' name='capital'><br>\n");          print("<input type='hidden' name='which' ");          print("value=$which>\n");          print("<input type='hidden' name='choice'");          print("value=$choice>\n");          print("<input type='submit' ");          print("value='Submit Answer'>");          print("</form>\n");          }        }       else {         if ($state == $correctstate)           {           print("Correct! The capital of $correctstate ");           print("is $correctcapital!");           $saywhich='false';           print("<p><a href='miniquizask.php'>");           print("Play again </a>");          }        else {          print("WRONG!<p>\n");          print("<a href='miniquizask.php'>");          print("New turn </a><p>\n");          print("OR try again: ");          print("$correctcapital is the capital ");          print("of what state?<br>");          print("<form action='miniquizcheck.php' ");          print("method='get'>\n");          print("<input type='text' name='state'><br>\n");          print("<input type='hidden' name='which'");          print(" value=$which>\n");          print("<input type='hidden' name='choice' ");          print("value=$choice>\n");          print("<input type='submit' ");          print(" value='Submit Answer'>");          print("</form>\n");         }       }     ?>     </body>     </html>  

Again, look at the general form of the code and gradually notice more detail before examining it line-by-line. Notice how the nested if statements correspond to the outline. Notice the print statements with the arguments being strings surrounded by double quotes. The strings are often mixtures of HTML and variables, with the variable names beginning with dollar signs. Notice that the action attributes indicate that the handler is this script again. Notice that the hyperlinks back to the first script are implemented using regular HTML a tags, with the href attribute having the value miniquizask.php.

You can try and make this example work right now. If you do not want to type in all 50 states, type in 5 and in the line $choice = rand(0, 49), change the 49 to 4. Alternatively, a more robust approach is to have the program detect the size of the arrays. The PHP function that does this is sizeOf. Change the assignment statement that produces a random choice to:

    $choice=rand(0,sizeOf($states)-1);

When testing the project, notice the form input that shows up in the browser address window after submitting each form. For example, Figure 4.6 shows the address with the form data after selecting the capital choice of question and Figure 4.7 shows the address with the form data after answering the question.

click to expand
Figure 4.6: Address window showing call to miniquizask.php and form input.

click to expand
Figure 4.7: Address window showing call to miniquizcheck.php and form input.

The form data is displayed because the form tag specified the method as get. Being able to examine the form data in this way will help in the debugging of your code. Once you have the application debugged, you can choose to switch to the put method.

States and Capitals Quiz in ASP

This text will have some examples with PHP explained first and some with ASP explained first. Assume you have the PHP version working. What do you need to change to produce an ASP version? You need to do the following:

  • Change the delimiters, including adding <%@ Language="JavaScript"%> at the top.

  • In all strings, you need to use concatenation wherever there are embedded variables. You can do this and remove the dollar signs from the variable names.

  • Remove the dollar signs from any other variable names.

  • Explicitly declare (use the var statement) variables.

  • Explicitly set variables to hold the form input. This is done using Request.QueryString(form input tag name).

  • Use the ASP/JavaScript form of include to get the statecapitals file.

  • Change the file references to be the ASP files. This also applies to the statecapitals file.

  • Use the JavaScript Math.floor(Math.random()*50) expression in place of the PHP one using rand.

  • Change print to Response.Write.

This might seem like so much that you are better off writing the ASP/JavaScript code from scratch. This determination will be left to the reader. Here is the ASP/JavaScript code for miniquizask.asp:

    <%@ Language="JavaScript"%>     <!— #include file="statecapitals.asp" —>     <html>     <head><title>Mini-quiz: ask</title>     </head>     <body>     <h1>State Capital Quiz</h1><p>     <%     var saywhich=String(Request.QueryString("saywhich"));     if (saywhich !="undefined") {      choice=Math.floor(Math.random()*50);      var which = String(Request.QueryString("which"));      if (which=='state') {        state = states[choice];        Response.Write("What is the capital of ");        Response.Write(state+"?<br>");        Response.Write("<form action='miniquizcheck.asp' ");        Response.Write("method='get'>\n");        Response.Write("<input type='text' ");        Response.Write("name='capital'><br>\n");        Response.Write("<input type='hidden' ");        Response.Write("name='which' ");        Response.Write("value="+which+">\n");        Response.Write("<input type='hidden' ");        Response.Write("name='choice' value="+choice+">\n");        Response.Write("<input type='submit' ");        Response.Write("value='Submit Answer'>");        Response.Write("</form>\n");       }      else          {        capital = capitals[choice];        Response.Write("$capital is the capital of which ");        Response.Write("state?<br>");        Response.Write("<form action='miniquizcheck.asp' ");        Response.Write("method='get'>\n");        Response.Write("<input type='text' ");        Response.Write("name='state'><br>\n");        Response.Write("<input type='hidden' ");        Response.Write("name='which' value="+which+">\n");        Response.Write("<input type='hidden' ");        Response.Write("name='choice' value="+choice+">\n");        Response.Write("<input type='submit' ");        Response.Write("value='Submit Answer'>");        Response.Write("</form>\n");       }      }     else       {        Response.Write("Choose form of question: ");        Response.Write("do you want to be given the ");        Response.Write("state or the capital?<br>");        Response.Write("<form action='miniquizask.asp' ");        Response.Write("method='get'>\n");        Response.Write("Ask <input type='radio' ");        Response.Write("name='which' value='state'>State");        Response.Write(" <input type='radio' ");        Response.Write("name='which' ");        Response.Write("value='capital'>Capital\n");        Response.Write("<input type='hidden' ");        Response.Write("name='saywhich' value='true'>\n");        Response.Write("<input type='submit' ");        Response.Write(" value='Submit choice'>");        Response.Write("</form>");       }     %>     </body>     </html>

Do the same review of this code as was suggested for the PHP example. Observe the general format. The if statements correspond to what is indicated in the outline. The include statement is at the top.

The form data is extracted using the ASP object method Request.Query
String() and then applying the String function. The String function completes the process of getting a value from the form. It does not appear to be required in every case, but it is required here.

The change to making the code robust with respect to the number of states is the following:

   var num = states.length;    choice=Math.floor(Math.random()*num);

You could combine the two (not use the variable num). Note that length is a property of the array states, whereas sizeOf is a function that takes as its argument the name of an array. The miniquizcheck.asp code is the following:

    <%@ Language="JavaScript"%>     <!— #include file="statecapitals.asp" —>     <html>     <head><title>Mini-quiz: check answers</title>     </head>     <body>     <h1>State Capital Quiz </h1><p>     <%     var choice=Request.QueryString("choice");     var correctstate=states[choice];     var correctcapital=capitals[choice];     var which=Request.QueryString("which");     if (which=='state')      {       var capital=Request.QueryString("capital");       if (capital == correctcapital)         {         Response.Write("Correct! "+correctcapital);         Response.Write(" is the capital of ");         Response.Write(correctstate+"!");         Response.Write("<p><a href='miniquizask.asp'>");         Response.Write("Play again </a>");        }       else        {         Response.Write("WRONG!<p>\n");         Response.Write("<a href='miniquizask.asp'>");         Response.Write("New turn </a><p>\n");         Response.Write("OR try again: ");         Response.Write("What is the capital of " );         Response.Write(correctstate+"?<br>");         Response.Write("<form action='miniquizcheck.asp'");         Response.Write(" method='get'>\n");         Response.Write("<input type='text' ");          Response.Write("name='capital'><br>\n");         Response.Write("<input type='hidden' ");         Response.Write(" name='which' value="+which+">\n");         Response.Write("<input type='hidden' ");         Response.Write("name='choice' ");         Response.Write(" value="+choice+">\n");         Response.Write("<input type='submit' ");         Response.Write("value='Submit Answer'>");         Response.Write("</form>\n");        }      }      else         {         var state=Request.QueryString("state");        if (state == correctstate)         {          Response.Write("Correct! ");          Response.Write("The capital of ");          Response.Write(correctstate);          Response.write(" is "+correctcapital+"!");          saywhich='false';          Response.Write("<p><a href='miniquizask.asp'>");          Response.Write("Play again </a>");         }        else          {          Response.Write("WRONG!<p>\n");          Response.Write("<a href='miniquizask.asp'>");          Response.Write("New turn </a><p>\n");          Response.Write("OR try again: ");          Response.Write(correctcapital);          Response.Write(" is the capital of what ");          Response.Write("state?<br>");          Response.Write(             "<form action='miniquizcheck.asp'");          Response.Write(" method='get'>\n");          Response.Write("<input type='text'");          Response.Write(" name='state'><br>\n");          Response.Write("<input type='hidden' ");          Response.Write("name='which' value="+which+">\n");          Response.Write("<input type='hidden' ");          Response.Write("name='choice' ");          Response.Write("value="+choice+">\n");          Response.Write("<input type='submit' ");          Response.Write(" value='Submit Answer'>");          Response.Write("</form>\n");         }      }     %>     </body>     </html> 

Again, look the code over and compare to the outline. In this case, it is again the nested ifs, the outermost if referring to the choice of question, and the inner ifs, in both cases, corresponding to right and wrong answers.

The last file to display, which, again, we will do only partially, is statecapitals. asp:

    <%     var states = new Array();     var capitals= new Array();     states[0]='Alabama'; capitals[0]='Montgomery';     states[1]='Alaska'; capitals[1]='Juneau';     states[2]='Arizona'; capitals[2]='Phoenix';

Notice that JavaScript forced the slightly more complex syntax: it was necessary to put in the array element numbers explicitly. The PHP syntax allowed saying $states[] = … to get the next element. In case you, the reader, are feeling sorry for the typist, please be aware that XML and XSLT scripts were used to generate these files. Consequently, the states and capitals were only typed once, and two different XSLT scripts were used to generate the PHP and the ASP files.

The ASP system distinguishes between form data submitted via the query string:

Request.Querystring("  ");

and form data submitted via the HTTP headers.

Request.Form("   "); 

The query string is what is used by the get method or by forming your own query string in an <a> tag. (This technique will be used in the origami store example.) The HTTP header is used by the put method. However, you can “get away with” just using:

… Request("  ");

which will work in either case. This is considered somewhat less secure, because a knowledgeable hacker could create a call with its own query string and trick your program. The PHP system also has long forms versus short forms for this same reason. Consider yourself warned.

The most obvious type of error you could have in a project such as the state capital quiz is to make a typo in the spelling of a state or a capital. The system does not help you here, and because of the random feature, it might be a long time before you or a player lets you know. In professional situations, it often is the practice to replace the random element with other code for some of the testing so that all options are taken to be checked.




Creating Database Web Applications with PHP and ASP
Creating Database Web Applications with PHP and ASP (Charles River Media Internet & Web Design)
ISBN: 1584502649
EAN: 2147483647
Year: 2005
Pages: 125
Authors: Jeanine Meyer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net