Page 158 - Open Soource Technologies 304.indd
P. 158

Unit 9: Working with Forms



              11.  print “<ul>\n\n”;                                                              Notes
              12.  ?>

              13.  </body>
              14.  </html>

            9.4 Combining HTML and PHP Code on a Single Page


            In some circumstances, you might want to include form-parsing code on the same page as a
            hard- coded HTML form. Such a combination can be useful if you need to present the same
            form  to the user  more  than once. You would have  more  flexibility  if  you were  to write the
            entire page dynamically, of course, but you would miss out on one of the great strengths of
            PHP. The more standard HTML you can leave in your pages, the easier they are for designers
            and page builders to amend without reference to you. You should avoid scattering substantial
            chunks of PHP code throughout your documents, however. Doing so makes them hard to read
            and maintain. Where possible, you should create functions that can be called from within your
            HTML code and can be reused in other projects.

            For the following examples, imagine that we’re creating a site that teaches basic math to preschool
            children, and have been asked to create a script that takes a number from form input and tells
            the user whether it’s larger or smaller than a predefined integer.

            Listing 6 creates the HTML. For this example, we need only a single text field, but even so,
            we’ll include a little PHP.
            Listing 6 An HTML Form That Calls Itself

               1.  <html>
               2.  <head>

               3.  <title>Listing 6 An HTML form that calls itself</title>
               4.  </head>

               5.  <body>
               6.  <form action=”< ?php print $_SERVER[PHP_SELF] ? >” method=”POST”>

               7.  Type your guess here: <input type=”text” name=”guess”>
               8.  </form>

               9.  </body>
              10.  </html>

            The action of this script is $_SERVER[PHP_SELF]. This variable is the equivalent of the name
            of the current script. In other words, the action tells the script to reload itself.
            The script in Listing 6 doesn’t produce any output. In Listing 7, we begin to build up the PHP
            element of the page. First, we must define the number that the user guesses. In a fully working
            version, we’d probably randomly generate this number, but for now, we keep it simple. We
            assign 42 to the $num_to_guess variable on line 2. Next, we must determine whether the form




                                             LOVELY PROFESSIONAL UNIVERSITY                                   153
   153   154   155   156   157   158   159   160   161   162   163