Creating Checkboxes


Another fundamental control is the checkbox control, which is created with the HTML <INPUT TYPE="CHECKBOX"> element. You can see an example in checkboxes.html, Example 5-5, where we're asking the user if he or she wants some cash back.

Example 5-5. Checkboxes, phpcheckboxes.html
 <HTML>     <HEAD>         <TITLE>Using Checkboxes</TITLE>     </HEAD>     <BODY>         <CENTER>         <H1>Using Checkboxes</H1>         <FORM METHOD="POST" ACTION="checkboxes.php">             Do you want cash back?             <INPUT NAME="Check1" TYPE="CHECKBOX" VALUE="Yes">             Yes             <INPUT NAME="Check2" TYPE="CHECKBOX" VALUE="No">             No             <BR>             <BR>             <INPUT TYPE="SUBMIT" VALUE="Submit">         </FORM>         </CENTER>     </BODY> </HTML> 

You can see the two checkboxes in a browser in Figure 5-5.

Figure 5-5. Creating checkboxes.


You can determine which checkbox the user checked in your code using $_REQUEST["Check1"] and $_REQUEST["Check2"]. But what if the user only checked Check1 but not Check2? Asking for $_REQUEST["Check2"] will cause an error because it doesn't exist. To check if it exists first, you can use the PHP isset function, which returns trUE if a variable has been set and FALSE otherwise. You can see what that looks like in the PHP script that reads the checkbox settings, checkboxes.php, Example 5-6.

Example 5-6. Reading data from checkboxes, phpcheckboxes.php
 <HTML>     <HEAD>         <TITLE>             Using Checkboxes         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Retrieving Data From Checkboxes</H1>             You checked             <?php                 if (isset($_REQUEST["Check1"]))                     echo $_REQUEST["Check1"], "<BR>";                 if (isset($_REQUEST["Check2"]))                     echo $_REQUEST["Check2"], "<BR>";             ?>         </CENTER>     </BODY> </HTML> 

As you can see in Figure 5-6, we have indeed been able to determine which checkbox the user checked. Nothing to it.

Figure 5-6. Reading data from checkboxes.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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