Code Blocks and Browser Output

In Hour 3, "Installing and Configuring PHP,"you learned that you can slip in and out of HTML mode at will, using the PHP start and end tags. In this hour, you have discovered that you can present distinct output to the user according to a decision-making process that we can control with if and switch statements. In this section, we will combine these two techniques.

Imagine a script that outputs a table of values only when a variable is set to the Boolean value true. Listing 5.13 shows a simplified HTML table constructed with the code block of an if statement.

Listing 5.13 A Code Block Containing Multiple print() Statements
   1: <html>   2: <head>   3: <title>Listing 5.13</title>   4: </head>   5: <body>   6: <?php   7: $display_prices = true;   8: if ( $display_prices ) {   9:     print "<table border=\"1\">";  10:     print "<tr><td colspan=\"3\">";  11:     print "today's prices in dollars";  12:     print "</td></tr>";  13:     print "<tr><td>14</td><td>32</td><td>71</td></tr>";  14:     print "</table>";  15: }  16: ?>  17: </body>  18: </html> 

If $display_prices is set to true in line 7, the table is printed. For the sake of readability, we split the output into multiple print() statements, and once again escape any quotation marks.

Put these lines into a text file called testmultiprint.php, and place this file in your Web server document root. When you access this script through your Web browser, it should look like Figure 5.2.

Figure 5.2. Output of Listing 5.13.

graphics/05fig02.gif

There's nothing wrong with the way this is coded, but we can save ourselves some typing by simply slipping back into HTML mode within the code block. In Listing 5.14 we do just that.

Listing 5.14 Returning to HTML Mode Within a Code Block
   1: <html>   2: <head>   3: <title>Listing 5.14</title>   4: </head>   5: <body>   6: <?php   7: $display_prices = true;   8: if ( $display_prices ) {   9: ?>  10:     <table border="1">  11:     <tr><td colspan="3">today's prices in dollars</td></tr>  12:     <tr><td>14</td><td>32</td><td>71</td>  13:     </table>  14: <?php  15: }  16: ?>  17: </body>  18: </html> 

The important thing to note here is that the shift to HTML mode on line 9 only occurs if the condition of the if statement is fulfilled. This can save us the bother of escaping quotation marks and wrapping our output in print() statements. It might, however, affect the readability of our code in the long run, especially as our script grows larger.



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

Similar book on Amazon

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