Receiving Form Data in Custom Arrays


Here's a useful tidbit: PHP lets you organize the data you get from a form in your own custom arrays. For example, say you wanted to ask for the user's name and favorite color and would like to have that data stored as $text['name'] and $text['color']. You tell PHP how to do that by giving each text field control a name with square brackets, such as texTData[name], as you see in Example 6-7, phptextarray.html.

Example 6-7. HTML for custom arrays example, phptextarray.html
 <HTML>     <HEAD>         <TITLE>             Using Text Fields         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Using Text Fields</H1>             <FORM METHOD="POST" ACTION="phptextarray.php">                 What's your name?                 <INPUT NAME="textdata[name]" TYPE="TEXT">                 <BR>                 <BR>                 What's your favorite color?                 <INPUT NAME="textdata[color]" TYPE="TEXT">                 <BR>                 <BR>                 <INPUT TYPE=SUBMIT VALUE=Submit>             </FORM>         </CENTER>     </BODY> </HTML> 

This page appears in Figure 6-7.

Figure 6-7. A custom array example.


To store this data in an array that we'll call $text, you simply use "textdata" as a key in the $_REQUEST array, as shown in Example 6-8, phptextarray.php.

Example 6-8. Using custom arrays, phptextarray.php
 <HTML>     <HEAD>         <TITLE>             Using Text Field Arrays         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Retrieving Data From Text Field Arrays</H1>             Your name is             <?php                 $text = $_REQUEST['textdata'];                 echo $text['name'], "<BR>";             ?>             Your favorite color is             <?php                 $text = $_REQUEST['textdata'];                 echo $text['color'], "<BR>";             ?>         </CENTER>     </BODY> </HTML> 

The results appear in Figure 6-8, where, as you can see, we've let PHP organize our data into a custom array to make things easier for us.

Figure 6-8. Getting data from custom arrays.




    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