Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello,

I have a file called Catform.php which allows users to 1) select products from 4 different product categories and 2) provide comments if they cannot find their product.  This php file is  linked to another file called handle_Catform.php which  processes the user input and mail the input to my email address.   

 

Catform.php

1) On the Catform.php, to link to the handle_Catform.php, I used the following code:

<form action="handle_Catform.php" method="post" ;>

 

2) For the 4 product categories, I arranged them using checkbox arrays.  For example, for the SP category, I used the following code:

       <p style="font-weight:bold;" >S&P Equity Funds</p> <br>
       <input type="checkbox" name="SP[]" value="SP100" /> S&P 100 Fund
        <input type="checkbox" name="SP[]" value="SP200" /> S&P 200 Fund
        <input type="checkbox" name="SP[]" value="SP300" /> S&P 300 Fund

  Then for the other 3 categories (ND, DJ and RU), I just replaced the name from "SP[]" to "ND[]" and so forth.

 

3) For the user comment, I used textarea.  I used the following code:

        <p style = "font-weight:bold;"> Comments</p>
        <textarea name="comments" rows="6" cols="60"></textarea>

 

Handle_Catform.php

I had no problem capturing and printing the user input from Catform.php.

Below is an excerpt of my codes showing how I print input from the SP category and user input comments.

 

   <?php //this will receive the data from CatForm.php.
  //Create variables
   $username = $_POST['username'];
   $comments= $_POST['comments'];
      //Print Greetings
     print "Congratulations, $username!  You have successfully made the following selections: <br> <br>";
      //Print category SP

      if (isset($_POST['SP']) AND is_array($_POST['SP'])) {
        foreach ($_POST['SP'] as $SP) {
               print " $SP <br>\n ";
     }
            } else {
       print'No selection for SP<br>';
     }

       //Print comments
     if (($_POST['comments'])!=""){
               print " You provided the following comments: $comments <br>\n ";
     }
             else {
       print'You did not enter any comments. <br>';
     }

?>

 

Question:  How do I use the mail () function to send the same user input to my email address on Handle_Catform.php?  Please help!

 

I tried the following codes but it did not work quite right and I don't know how to incorporate $comments in $body. I just need something like the following:  For example, if the user selects only from SP category and provide comments " I want something else", then the email will look like:

"From [the  username of the user]

   We have received the following information:

   SP Selection = whatever user selected

   ND Selection =

   DJ Selection =

   RU Selection =

   Comments =  I want something else."

 

<?php //this will send the data from CatForm.php to my email address.
  //Create variables:
   $to = "
my email address";
   $username = $_POST['username'];
   $comments= $_POST['comments'];
   $from = $_POST['username']
   $fields = array();
   $fields{"SP"} = "SP Selection= ";
   $fields{"ND"} = "ND Selection= ";
   $fields{"DJ"} = "DJ  Selection= ";
   $fields{"RU"} = "RU Selection= ";
 
   $subject = "Category Selections";
   $headers = "From: $username";
 
   $body = "We have received the following information:\n\n"; foreach($fields as $a => $B){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

    mail($to, $subject, $message, $headers);

}
  
  ?>

 

  Thank you so much.

 

Jane

 

 

 

 

   

 

 

 

 

Link to comment
Share on other sites

Hello, Jane. Welcome to the forums.

Your $fields array syntax is wrong. You should be using $fields[] instead of $fields{} (i.e., square brackets instead of curly brackets).

 

Also, to get the values, you will need an array to take the posted value and turn it into a meaningful string for the user in the email.

For example, when I have checkbox data in a form, I usually put the data in a separate include file. In your case, I might make a file as follows:

 

checkbox_data.php

<?php
  
  $sp = array(1 => 'S&P 100 Fund', 'S&P 200 Fund', 'S&P 300 Fund');
  
  // Other arrays here.

I would then include the checkbox_data.php file in both the form script and the form-processing script.

In the form script, I'd construct the checkbox HTML as follows:

foreach ($sp as $k => $v) {
  
  echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;
  
}

That way, the array keys would become the values for the posted data.

Then, after posting the form, you should get values 1-3 for the checkboxes, which you can then refer back into the $sp array in the include file as follows:

foreach ($_POST['sp'] as $v) {
  
  $body .= 'SP value: ' . $sp[$v];
  
}

A couple notes:

1) If no checkboxes are selected, $_POST['sp'] will not exist. You definitely need to check for this.

2) If the user should only select one value per grouping, you should use radio buttons instead of checkboxes.

 

Hope that helps.

  • Upvote 1
Link to comment
Share on other sites

Hello HarleySan,

 

Thank you so much for your help and suggestion.

 I was able to revise my form script (with modification since I don't know how to include your checkbox_data.php).  But I need help to revise my form processing script.

 

1. My form script (Catform.php)

I revised my form script as follows:

Since I don't know how to include your checkbox_data.php, I put the codes directly inside my form script.  For example, in the SP category section, I put the codes (in red) immediately after the paragraph referring to the description of the category - S&P Equity Funds.

 

<p style="font-weight:bold;" >S&P Equity Funds</p> <br>
 
       <?php 
        $sp = array(1 => 'S&P 100 Fund', 'S&P 200 Fund', 'S&P 300 Fund', 'S&P 400 Fund', 'S&P 500 Fund');   
        
        foreach ($sp as $k => $v) {
  
        echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;
   
       }
 
       ?> 

Similarly for the next category (ND), I put the codes immediately after the paragraph with the description of the category - ND Equity Funds.

        <p style = "font-weight:bold;">ND Equity Funds</p><br>

      

 

2. My form processing script (Handle_Catform.php) - Please help!

After I enter the following section (in blue) at the beginning of my script,

 

<?php //this will send the data from CatForm.php to my email address.

  //Create variables:
   $to = "
my email address";
   $username = $_POST['username'];
   $comments= $_POST['comments']

   $headers = "From: $username";

 

how do I code the $body section if I don't include the checkbox_data.php?  

I don't think there should be 4 $body sections but only one that incorporates/concatenates all the user input for each category plus  $comments  Can I have something like:

$body = $bodysp +$bodynd + $bodydj + $bpduru + $comment (what should be used instead of the + sign?)  

Can I have:

     

     $body = $bodysp + $bodynd + $bodydj + $bodyru + $comments

      (what is the correct concatenating symbol to use in this case, I don't think it should be + sign).

 

        $sp = array(1 => 'S&P 100 Fund', 'S&P 200 Fund', 'S&P 300 Fund', 'S&P 400 Fund', 'S&P 500 Fund');   

        foreach ($_POST['sp'] as $v) {

        $bodysp .= 'SP value: ' . $sp[$v];
         }

       $nd = array(1 => 'ND100 Fund', 'ND 200 Fund', 'ND 300 Fund', 'ND 400 Fund', 'ND 500 Fund');   

        foreach ($_POST[''nd'] as $v) {

        $bodynd .= 'ND value: ' . $nd[$v];
         }

       $dj = array(1 => 'DJ100 Fund', 'DJ 200 Fund', 'DJ 300 Fund', 'DJ 400 Fund', 'DJ 500 Fund');   

        foreach ($_POST[''dj'] as $v) {

        $bodydj.= 'DJ value: ' . $dj[$v];
         }

         $ru = array(1 => 'RU100 Fund', 'RU 200 Fund', 'RU 300 Fund', 'RU 400 Fund', 'RU 500 Fund');   

        foreach ($_POST[''ru'] as $v) {

        $body ru.= 'RU value: ' . $ru[$v];
         }

       mail($to, $subject, $body, $headers);

 

Thanks.

Jane

 

 

 

Link to comment
Share on other sites

The whole point of including the arrays from a separate file is that you only have to code the arrays once, and then you can use them forever. To include a file, you have to use the include function (http://php.net/manual/en/function.include.php).

 

For example, to include a script called checkbox_data.php in the same folder as the file that is doing the including, you'd write:

include('checkbox_data.php');

The key with including files is getting either the absolute or relative path correct.

 

Also, to concatenate strings, you need to use the period (.), not the plus sign, in PHP.

Other than that, your script should more or less work.

Don't forget to properly validate the input you're accepting, as someone might try to hack your form.

  • Upvote 1
Link to comment
Share on other sites

Hello HartleySan,

Thank you for your reply.  Just one question - where should I place the include script in my script?

 

include('checkbox_data.php');

 

Should it go to the <head>tag section  or the <body> tag section?

 

In the <head> section, I have a <title> tag, a <link> tag to a CSS file, and a <script> tag which is a piece of  javascript to make sure user enters username.  I don't think the include script should go there. If it should go to the head section, can I put it after the <script> tag?

 

In the <body> section, I have the form tag, should I place the script before the form tag or inside the form tag?? Or it does not matter.

 

Option 1- Before the form tag

 

<?php

    include('checkbox_data.php');

   ?>

        

<form action="handle_CatForm.php" method="post" ;> <br>

  
     <p style="font-weight:bold;"> Check all products that you want:</p><br> //Instructions
 
        <p style="font-weight:bold;" >S&P Equity Funds</p> <br> //SP category
        
   <?php

   foreach ($sp as $k => $v) {

          echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;
          }
       ?> 

    

       <p style="font-weight:bold;" >ND Equity Funds</p> <br> //ND Category

       
   <?php

   foreach ($nd as $k => $v) {

          echo '<input type="checkbox" name="nd[]" value="' . $k . '"> ' . $v;
          }
       ?> 

 

 

Option 2- Inside the form tag

    

<form action="handle_CatForm.php" method="post" ;> <br>

 
<?php 

    include('checkbox_data.php'); 

   ?>     

 

<p style="font-weight:bold;"> Check all products that you want:</p><br> //Instructions
 
        <p style="font-weight:bold;" >S&P Equity Funds</p> <br> //SP category
        
   <?php

   foreach ($sp as $k => $v) {

          echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;
          }
       ?> 

    

Thanks.

Jane

 

  

Link to comment
Share on other sites

The include function is a PHP function, not an HTML one (HTML doesn't have functions).

As a result, where you put it in relation to the head element, etc. is irrelevant.

Like you suggested though, the file must be included before you can use the array(s) that are in it in your main script (and in that sense, it should be included before you start the form).

 

The way I always think of include files is to imagine that you literally take all the code in the include file and just drop it into your main script where the include function call is (because that's essentially what you're doing).

In that respect, so long as code is included before you try to use it, you won't have any issues.

  • Upvote 1
Link to comment
Share on other sites

Hello Hartlysan,

I need your help.  I followed your instructions and created a checkbox_data.php.  Codes are as follows:

<?php
 
        $sp = array(1 => 'S&P 100 Fund', 'S&P 200 Fund', 'S&P 300 Fund', 'S&P 400 Fund' ,'S&P 500 Fund');
        $nd = array(1 => 'ND 100 Fund', 'ND 200 Fund', 'ND 300 Fund', 'ND 400 Fund' ,'ND 500 Fund');
        $dj = array(1 => 'DJ 100 Fund', 'DJ 200 Fund', 'DJ 300 Fund', 'DJ 400 Fund' ,'DJ 500 Fund');
        $ru = array(1 => 'RU 100 Fund', 'RU 200 Fund', 'RU 300 Fund', 'RU 400 Fund' ,'RU 500 Fund');
 
?>

Then I added the include ('checkbox_data.php) script  and the foreach codes for each of my 4 product categories in my form script.

 <?php
    include('checkbox_data.php');
   ?>
    <form action="handle_Cat4Form_mailprint.php" method="post" ;> 
    <br>
    <p style="font-weight:bold;"> Check all products that you want:</p><br>
        
    <p style="font-weight:bold;" >S&P Equity Funds</p><br>
   
      <?php 
            foreach ($sp as $k => $v) {
          echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;
          }
 
       ?> 
 
        <br> <br>
 
        <p style = "font-weight:bold;">Nasdaq Equity Funds</p><br>
               
       <?php   
         foreach ($nd as $k => $v) {
          echo '<input type="checkbox" name="nd[]" value="' . $k . '"> ' . $v;
          }
 
       ?> 
       
        <br> <br>
        <p style = "font-weight:bold;">Dow Jones Equity Funds</p><br>
       
        <?php 
        foreach ($dj as $k => $v) {

 

echo '<input type="checkbox" name="dj[]" value="' . $k . '"> ' . $v;
          }
 
       ?> 
        
        <br> <br>
        <p style="font-weight:bold;" >Russell Equity Funds</p><br>
       
       <?php 
           
        foreach ($ru as $k => $v) {
          echo '<input type="checkbox" name="ru[]" value="' . $k . '"> ' . $v;
          }
 
       ?> 
 
Then in my form processing script, I have 
 
<?php
 error_reporting (E_ALL ^ E_NOTICE);
 session_start();
?> 
<html>
<head>
   <title> Handle Cat4 Form</title>
</head>
 
<body>
<?php //this will email the data from Cat1Form.php to Indexcellent and print user confirmation.
 
    include('checkbox_data.php');
    foreach ($_POST['sp'] as $v) {$bodysp= 'SP selection: ' . $sp[$v];}
    foreach ($_POST['nd'] as $v) {$bodynd= 'ND selection: ' . $nd[$v];}
    foreach ($_POST['dj'] as $v) {$bodydj= 'DJ selection: ' . $dj[$v];}
    foreach ($_POST['ru'] as $v) {$bodyru= 'RU selection: ' . $ru[$v];}
  
When I selected products from only SP, and ND and NOT DJ and RU, the following warning is displayed:
Note: line 17 is the foreach code for DJ and line 18 is the foreach code for RU.   
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Indexcellent\handle_Cat4Form_mailprint.php on line 17

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Indexcellent\handle_Cat4Form_mailprint.php on line 18

 

  If I selected all 4 categories, no warning.  
How do I get rid of the warnings?  
 
One more question.  foreach ($_POST['sp'] as $v) {$bodysp= 'SP selection: ' . $sp[$v];}

Is it $bodysp or $bodysp.  (is the  period neccessary after bodysp?)

 

 

Thanks.
Jane

 

Link to comment
Share on other sites

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Indexcellent\handle_Cat4Form_mailprint.php on line 17

 

For each category that you don't check at least one checkbox you will get the above warning because you have not understood how the global array $_POST works. $_POST is an array that gets created by submitting a form with a method of post. Its keys are the names of each input field in the form. The input elements only get inserted into the $_POST array if there is any data in them. So if you don't check a checkbox in the SP selection, $_POST['sp'] will not exist. In your form processing you need to first check if it exists before you do the foreach. If it doesn't exist the foreach statement will be skipped and you won't get the error.

if (isset($_POST['sp'])) {
    foreach ($_POST['sp'] as $v) {
    	$bodysp= 'SP selection: ' . $sp[$v];
    	}
    }
    
    if (isset($_POST['nd'])) {
    foreach ($_POST['nd'] as $v) {
    	$bodynd= 'ND selection: ' . $nd[$v];
        }
    }
    
    if (isset($_POST['dj'])) {
    foreach ($_POST['dj'] as $v) {
    	$bodydj= 'DJ selection: ' . $dj[$v];
    	}
    }

Is it $bodysp or $bodysp.  (is the  period neccessary after bodysp?)

$bodysp is a variable and as such you can name it anything you want but it should meet the standard naming convention - start with a letter or underscore, followed by any number of letters, numbers, or underscores.

 

  • Upvote 2
Link to comment
Share on other sites

Hello,

Thanks to HartleySan and Margaux, I was able to solve my problem.  However, instead of just copying the codes HartleySan gave me, I want to understand what I am doing.   So I hope someone could enlighten me.

 

To recap, I created 4 product categories using checkbox arrays. 

In the beginning, I followed the array's chapter in the book and created the following code for my SP category in my form script.

<input type="checkbox" name="SP[]" value="SP100" /> S&P 100 Fund

 

<input type="checkbox" name="SP[]" value="SP200" /> S&P 100 Fund

and the following code for my SP category in my form processing script

if (isset($_POST['SP']) AND is_array($_POST['SP'])) {
        foreach ($_POST['SP'] as $SP) {
               print " $SP <br>\n ";

 

HartleySan suggested that I have a separate php file for the arrays and then include it in both my form script and my form processing script.

 

 checkbox_data.php

<?php

 

$sp = array(1 => 'S&P 100 Fund', 'S&P 200 Fund', 'S&P 300 Fund');

 

// Other arrays here  .

 

That works great by the way.  My only problem is  I don't understand the codes he suggested as to how to echo the checkbox array in my form script: 

 

foreach ($sp as $k => $v) {

 

 

 

echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;

 

}

He wrote: "That way, the array keys would become the values for the posted data."

 

 

For the array named $SP,  I understand that $k refers to the index so in this case, will be 1, 2, 3, and so on.  $v refers to the value, on in this case, will be S&P 100 Fund, S&P 200 Fund and so on,

it is the echo statement that I have problems with.  I understand name should be "sp[]"  in order to create the $_POST('sp') array, but I don't understand the value part.  value = "'.$k. '"  ?? I understand the value should be enclosed in a pair of double quotes, but

1) Why is there a pair of single quotes enclosing .$k.? 2) Why are there 2 periods before and after $k? i.e. (. $k .) Is that used to echo $k one by one e.g. 1 2 3 and so on?

3) As to ( ' . $v)?  I understand the ' is to indicate the closing of the echo statement,  but can the ' be placed after $v i.e.( .$v' )instead?? In other words, the echo statement does not encompass the .$v?? 

4) Finally, what is the period before $v ?  Is that used to echo $v one by one e.g. S&P 100 Fund, S&P 200 Fund, What is the difference between 1 period before  the $v and 2 periods before and after the $k?

 I know the codes work, but I would appreciate a brief explanation on how it works.  Thank you very much.

Link to comment
Share on other sites

1) The single quotes are used to delimit the string literals. In other words, the single quotes are used to mark the beginnings and endings of the various strings.

 

2) The period is the concatenation operator in PHP. In other words, you have to use a period to join strings together with other strings/numbers.

 

3) $v is not a string. It's a variable, and the value of the variable is what we want to echo out to the screen. Because $v is a variable and not part of a string, we cannot enclose $v in a set of single quotes. As such, we have to end the string right before $v, and then tack the value of $v onto the end by using the concatenation operator mentioned in #2.

 

4) Again, the period is the concatenation operator. The periods around $k mean that we should stick the value of $k between the string before it and the string after it. There is only one period before $v because we want $v to be at the end of the string we are echoing out to the screen.

 

As a final note, some people find it easier to use double quotes instead of single quotes in PHP, since you're able to echo out variable values within double quotes. However, I usually don't like to do that since you then have to escape all of the double quotes in the HTML that you are outputting. For example, if we were to use double quotes instead of single quotes for the expression you are echoing, you'd write the following:

echo "<input type=\"checkbox\" name=\"sp[]\" value=\"$k\"> $v";
Link to comment
Share on other sites

Thank you Hartlysen.  I just need some clarification to make sure I understand what you are saying.

 

1)  The double quote statement you brought up at the end will do the same thing as the single quote statement. ( For me personally, the double quote method statement is much easier to understand.)

 

Single quote:    echo '<input type="checkbox" name="sp[]" value="' . $k . '"> ' . $v;

Double quote :  echo "<input type=\"checkbox\" name=\"sp[]\" value=\"$k\"> $v";

 

2) If I were to use the double quote method in my form script, can i still use the following in my form processing script?  It works if I use the single quote method. 

   

include('checkbox_data.php');
  
      if (isset($_POST['sp'])) {
        foreach ($_POST['sp'] as $v) {$bodysp .='<br>' . $sp[$v];}
      }

 

 

 

3) $k is a variable but is part of the '<input type ...>' string.  So we use single quote in the value section of the '<input type...>' string.  In fact, re: value = "'. $k. '" -  we have two strings.-  the outer double quote string showing what should be contained in the value part of the input type string,  and the inner single quote string encompassing the $k.  Since we have two strings, we need 2 concatenate operators surrounding the $k - we need them to connect the outer and the inner string. 

 

4) $v is a variable and is not part of the '<input type ...>' string.  We only need 1 concatenate operator to connect it with the '<input type  ...>' string. 

Link to comment
Share on other sites

1) Okay. Please use whichever one you are more comfortable with.

 

2) Yes, you can freely use single and double quotes as much or as little as you want. From one statement to the next, you can switch them up as well.

 

3) $k is a variable that is being added to a string. For example, if I have the following:

 

$age = 20;

echo 'Bill is ' . $age . ' years old.';
 
Then the following string would be output:
'Bill is 20 years old.'

 

That's all there is to it. The period is for adding strings to other strings/numbers, and the single quotes are there to end one string before the variable value is output, and the other single quote is there to start the string that comes after the variable value.

 

The double quotes are merely there because they should be there for HTML.

 

4) Both $v and $k are not strings. They are variables being added onto strings. The only reason there is only one period before $v is because $v is at the very end of the string being output. If you decided, for example, to add a label element around the check box input, then $v would no longer be at the end (and would thus require a period on both sides). For example:

echo '<label for="sp_' . $k . '"><input type="checkbox" id="sp_' . $k . '" name="sp[]" value="' . $k . '"> ' . $v . '</label>';
Link to comment
Share on other sites

 Share

×
×
  • Create New...