Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - PHP

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Dynamic Content - PHP

PHP can dynamically change the XHTML it outputs based on a user’s input.

Dynamic Content

 

PHP can dynamically change the XHTML it outputs based on a user’s input. We now build on Section 23.4’s example by combining the XHTML form of Fig. 23.12 and the PHP script of Fig. 23.13 into one dynamic document. The form in Fig. 23.21 is created using a series of loops, arrays and conditionals. We add error checking to each of the text input fields and inform the user of invalid entries on the form itself, rather than on an error page. If an error exists, the script maintains the previously submitted values in each form element. Finally, after the form has been successfully completed, we store the input from the user in a MySQL database. Before running the following example, make sure MySQL is installed, then execute the MailingList script (refer to Section 22.8) from the Script Examples folder of the Chapter 23 examples directory at www.deitel.com/books/iw3HTP4. Lines 36–47 create three arrays, $booklist, $systemlist and $inputlist, that are used to dynamically create the form’s input fields. We specify that the form created in this document is self-submitting (i.e., it posts to itself) by setting the action to 'dynamicForm.php' in line 148. [Note: We enclose XHTML attribute values in the string argument of a print statement in single quotes so that they do not interfere with the double quotes that delimit the string. We could alternatively have used the escape sequence \" to print double quotes instead of single quotes.] Line 50 uses function isset to determine whether the Register button has been pressed. If it has, each of the text input fields’ values is validated. If an error is detected (e.g., a text field is blank or the phone number is improperly formatted), an entry is added to array $formerrors containing a key corresponding to the field name with the error and a value of true. Also, variable $iserror is set to true. If the Register button has not been pressed, we skip ahead to line 138.

 

1     <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

 

2     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5     <!-- Fig. 23.21: dynamicForm.php -->

 

6     <!-- Dynamic form. -->

 

7     <html xmlns = "http://www.w3.org/1999/xhtml">

 

8           <head>

 

9                  <title>Sample form to take user input in XHTML</title>

 

<style type = "text/css">

11        td         { padding-top: 2px;

12                    padding-bottom: 2px;

13                    padding-left: 10px;

14                    padding-right: 10px }

15        div       { text-align: center }

16        div div { font-size: larger }

17        .name { background-color: #ffffaa }

18        .email { background-color: #ffffbb }

19        .phone           { background-color: #ffffcc }

20        .os       { background-color: #ffffdd }

21        .smalltext       { font-size: smaller }

22        .prompt           { color: blue;

23                    font-family: sans-serif;

24                    font-size: smaller }

25        .largeerror      { color: red }

26        .error   { color: red;

27                    font-size: smaller }

28        </style>

 

29        </head>

 

30        <body>

 

31        <?php

 

32        extract( $_POST );

 

33        $iserror = false;

34       

35        // array of book titles

 

36        $booklist = array( "Internet and WWW How to Program 4e",

 

           

37        "C++ How to Program 6e", "Java How to Program 7e",

38        "Visual Basic 2005 How to Program 3e" );

39                   

40        // array of possible operating systems

 

41        $systemlist = array( "Windows XP", "Windows Vista",

 

 

42        "Mac OS X", "Linux", "Other");

43       

44        // array of name values for the text input fields

 

45        $inputlist = array( "fname" => "First Name",

 

                       

46        "lname"          =>        "Last Name", "email" => "Email",

47        "phone"         =>        "Phone" );

48                               

49        // ensure that all fields have been filled in correctly

 

50        if ( isset ( $submit ) )

51        {

 

            if ( $fname == "" )                

52                               

53        {                      

54        $formerrors[ "fnameerror" ] = true;            

55        $iserror = true;                     

56        } // end if        

57                               

58        if ( $lname == "" )    

59        {                      

60        $formerrors[ "lnameerror" ] = true;

61        $iserror = true;         

62        } // end if        

63                               

64        if ( $email == "" )      

65        {                                  

66        $formerrors[ "emailerror" ] = true; 

67        $iserror = true;         

68        } // end if        

69                                           

70        if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) )

71        {                                  

72        $formerrors[ "phoneerror" ] = true;           

73        $iserror = true;         

74        } // end if        

75                                           

76        if ( !$iserror ) 

77        {                                  

78        // build INSERT query        

79        $query = "INSERT INTO contacts " .       

80        "( LastName, FirstName, Email, Phone, Book, OS ) " .

81        "VALUES ( '$lname', '$fname', '$email', " .         

82        "'" .      quotemeta( $phone )           . "', '$book', '$os' )";  

83                                           

84        // Connect to MySQL          

85        if ( !( $database = mysql_connect( "localhost",  

86        "iw3htp4", "iw3htp4" ) ) )    

87        die( "Could not connect to database" );  

88                                           

89        // open MailingList database         

90        if ( !mysql_select_db( "MailingList", $database ) )         

91        die( "Could not open MailingList database" );   

92                                           

93        // execute query in MailingList database

94        if ( !( $result = mysql_query( $query, $database ) ) )

95        {                                  

96        print( "Could not execute query! <br />" );          

97        die( mysql_error() ); 

98        } // end if        

99                                           

100     mysql_close( $database ); 

101                                        

102     print( "<p>Hi<span class = 'prompt'>       

103     <strong>$fname</strong></span>.         

104     Thank you for completing the survey.<br />       

105                                        

106     You have been added to the        

107     <span class = 'prompt'>     

108     <strong>$book</strong></span> 

109     mailing list.</p>       

110     <strong>The following information has been saved    

111     in our database:</strong><br />   

112                                        

113     <table><tr>   

114     <td class = 'name'>Name </td>     

115     <td class = 'email'>Email</td>       

116     <td class = 'phone'>Phone</td>   

117     <td class = 'os'>OS</td>

118     </tr><tr>

119    

120     <!-- print each form field’s value -->

121     <td>$fname $lname</td>

122     <td>$email</td>

123     <td>$phone</td>

124     <td>$os</td>

125     </tr></table>

126    

127     <br /><br /><br />

128     <div><div>

129     <a href = 'formDatabase.php'>

130     Click here to view entire database.</a>

131     </div>This is only a sample form.

132     You have not been added to a mailing list.

133     </div></body></html>" );

134     die();

135     } // end if

136     } // end if

137    

138     print( "<h1>Sample Registration Form.</h1>

 

139     Please fill in all fields and click Register." );

140    

141     if ( $iserror )

142     {

 

143     print( "<br /><span class = 'largeerror'>

                        Fields with * need to be filled in properly.</span>" );               

144                                        

145     } // end if        

146                                        

147     print( "<!-- post form data to form.php -->

 

148     <form method = 'post' action = 'dynamicForm.php'>

 

149     <img src = 'images/user.gif' alt = 'User' /><br />

 

150     <span class = 'prompt'>

 

151     Please fill out the fields below.<br /> </span>

152    

153     <!-- create four text boxes for user input -->" );

 

154     foreach ( $inputlist as $inputname => $inputalt )

155     {

 

156     $inputtext = $inputvalues[ $inputname ];

157

 

print( "<img src = 'images/$inputname.gif'                     

158                            

159     alt = '$inputalt' /><input type = 'text'                     

160     name = '$inputname' value = '" . $$inputname . "' />" );                       

161                                        

162     if ( $formerrors[ ( $inputname )."error" ] == true )                       

163     print( "<span class = 'error'>*</span>" );             

164                                        

165     print( "<br />" );

 

166     } // end foreach

167

168     if ( $formerrors[ "phoneerror" ] )

 

169     print( "<span class = 'error'>" );

170     else

 

171     print("<span class = 'smalltext'>");

172    

173     print( "Must be in the form (555)555-5555

 

174     </span><br /><br />

175

 

           

176     <img src         = 'images/downloads.gif'

177     alt =     'Publications' /><br />

178                

179     <span class = 'prompt'>

 

180     Which book would you like information about?

181     </span><br />

182

183     <!-- create drop-down list containing book names -->

 

184     <select name = 'book'>" );

185

186     foreach ( $booklist as $currbook )

187     {

 

188     print( "<option" );

189

 

if ( ( $currbook == $book ) )                       

190                            

191     print( " selected = 'true'" );              

192                            

193     print( ">$currbook</option>" );

 

194     } // end foreach

195

196     print( "</select><br /><br />

 

197     <img src = 'images/os.gif' alt = 'Operating System' />

 

198     <br /><span class = 'prompt'>

 

199     Which operating system are you currently using?

 

200     <br /></span>

201

 

 

202     <!-- create five radio buttons -->" );

203    

204     $counter = 0;

205    

206     foreach ( $systemlist as $currsystem )

207     {

 

208     print( "<input type = 'radio' name = 'os'

 

           

209     value = '$currsystem'" );

210                

211     if ( $currsystem == $os )     

212     print( "checked = 'checked'" );      

213     elseif ( !$os && $counter == 0 )    

214     print( "checked = 'checked'" );      

215                

216     print( " />$currsystem" );

217                

218     // put a line break in list of operating systems

 

219     if ( $counter == 1 ) print( "<br />" );

220     ++$counter;

 

221     } // end foreach

222

 

223     print( "<!-- create a submit button -->

 

224     <br /><input type = 'submit' name = 'submit'

 

225     value = 'Register' /></form></body></html>" );

226     ?><!-- end PHP script -->



 




 

Line 76 determines whether any errors were detected. If $iserror is false (i.e., there were no input errors), lines 79–133 display the page indicating that the form was sub-mitted successfully. We will say more about lines 79–133 later. If $iserror is true, the script from lines 79–133 is skipped, and the code from lines 138–224 executes. These lines include a series of print statements and conditionals to output the form, as seen in Fig. 23.21(a). Lines 154–166 iterate through each element in the $inputlist array. In line 156 the value of variable $inputtext is assigned to the text field’s value attribute. If the form has not yet been submitted, variable $inputtext’s value will be the empty string "". Lines 158–159 output the image that corresponds to each text field. The image src is set to 'images/$inputname.gif' because the images are stored in the images directory, and each image shares the name of its corresponding text field and ends with the .gif extension. Lines 159–160 initialize the input text field. The text field’s name attribute is set to variable $inputname.

 

In line 160 we encounter the $$variable notation for specifying a variable variable. A variable variable allows the code to reference variables dynamically. You can use this expression to obtain the value of the variable whose name is equal to the value of $variable. PHP first determines the value of $variable, then appends this value to the leading $ to form the identifier of the variable you wish to reference dynamically. (The expression $$variable can also be written as ${$variable} to convey this procedure.) For example, in lines 154–166, we write $$inputname to reference the value of each form-field variable. During the iteration of the loop, $inputname contains the value "email". Therefore, PHP replaces $inputname in the expression $$inputname with the string "email", forming the expression ${"email"}. The entire expression then evaluates to the value of the variable $email. Thus, the variable $email, which stores the value of the e-mail text field after the form has been submitted, is dynamically referenced. This dynamic variable reference is added to the string as the value of the input field (using the concatenation operator) to maintain data over multiple submissions of the form.

 

Lines 162–163 add a red asterisk next to the text input fields that were filled out incor-rectly. Lines 168–169 color the phone instructions red if the user entered an invalid phone number by assigning the class error to the span tag surrounding the text.

 

Lines 186–194 and 206–221 generate options for the book drop-down list and oper-ating-system radio buttons, respectively. Lines 190–191 and 211–214 ensure that the pre-viously selected or checked element (if one exists) remains selected or checked over multiple attempts to correctly fill out the form. If any book was previously selected, lines 190–191 add the string selected = 'true' to its option tag. Lines 211–214 select an oper-ating system radio button under two conditions. First, lines 211–212 select the button if it was previously selected, before an unsuccessful submit operation. Lines 213–214 select the first radio button only if the form has not yet been submitted ($os is not set) and it is the first radio button. This ensures that the form cannot be submitted without a radio button selected.

 

If the form has been filled out correctly, lines 79–98 place the form information in the MySQL database MailingList using an INSERT statement. Line 82 uses the quote-meta function to insert a backslash (\) before any special characters in the passed string. We must use this function so that MySQL does not interpret the parentheses in the phone number as having a special meaning aside from being part of a value to insert into the data-base. Lines 102–133 generate the web page indicating a successful form submission, which also provides a link to formDatabase.php (Fig. 23.22). This script displays the contents of the MailingList database.

 

38  <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

 

39  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

40        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

42  <!-- Fig. 23.22: formDatabase.php -->

 

<!-- Displaying the MailingList database. -->

7          <html xmlns = "http://www.w3.org/1999/xhtml">

 

8          <head>

 

9          <title>Search Results</title>

 

10        <style type = "text/css">

 

11        body  { font-family: arial, sans-serif;

12        background-color: #F0E68C }

 

13        h3 { color: blue }

 

14        table { background-color: #ADD8E6 }

 

           

15        td         { padding-top: 2px;

16                    padding-bottom: 2px;

17                    padding-left: 4px;

18                    padding-right: 4px;

19                    border-width: 1px;

20                    border-style: inset }

21        </style>

 

22        </head>

 

23        <body>

 

24        <?php

 

25        extract( $_POST );

26       

27        // build SELECT query

 

28        $query = "SELECT * FROM contacts";

29       

30        // Connect to MySQL

 

31        if ( !( $database = mysql_connect( "localhost",

 

 

32        "iw3htp4", "iw3htp4" ) ) )

33        die( "Could not connect to database </body></html>" );

34       

35        // open MailingList database

 

36        if ( !mysql_select_db( "MailingList", $database ) )

 

 

37        die( "Could not open MailingList database </body></html>" );

38       

39        // query MailingList database

 

40        if ( !( $result = mysql_query( $query, $database ) ) )

41        {

42        print( "Could not execute query! <br />" );

 

43        die( mysql_error() . "</body></html>" );

 

44        } // end if

 

45        ?><!-- end PHP script -->

46

47        <h3>Mailing List Contacts</h3>

 

48        <table>

49        <tr>

 

           

50        <td>ID</td>

51        <td>Last Name</td>

52        <td>First Name</td>

53        <td>E-mail Address</td>

54        <td>Phone Number</td>

55        <td>Book</td>

56        <td>Operating System</td>

 

57        </tr>

 

58        <?php

59        // fetch each record in result set

60        for ( $counter = 0; $row = mysql_fetch_row( $result );

61        $counter++ )

62        {

63        // build table to display results

64        print( "<tr>" );

65       

66        foreach ( $row as $key => $value )

67        print( "<td>$value</td>" );

68       

69        print( "</tr>" );

70        } // end for

71       

72        mysql_close( $database );

 

73        ?><!-- end PHP script -->

 

74        </table>

 

75        </body>

 

76        </html>

 


Fig. 23.22 | Displaying the MailingList database.


Operator Precedence Chart

 

This section contains the operator precedence chart for PHP. In Fig. 23.23, the operators are shown from top to bottom in decreasing order of precedence.







Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.