eHow launches Android app: Get the best of eHow on the go.

How To

How to Create a PHP Survey

Contributor
By Eric Tilden
eHow Contributing Writer
(0 Ratings)

Obtaining user feedback is a critical component to every website, whether it is used as market research for a product line, customer experiences from an activity or service, or to help match possible candidates for the perfect job. This tutorial explains the process of creating a form, validates the questions, and emails the results to the poll taker.

Difficulty: Moderate
Instructions

Things You'll Need:

  • Text editor like Source Edit •Document uploading software like FileZilla •Server Space

    XHTML DOCUMENT

  1. Step 1

    Open your text editor and type the following at the top of the document:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    This is the doctype header information, which declares that we are going to create an XHTML document that uses the 'Transitional' rules, which aren't as strict as the 'Strict' rules.

  2. Step 2

    Skip a few lines and type the following tag with attributes:
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    This html tag creates the page. Inside are the attributes xmlns, xml:lang, and lang. The xmlns is a namesake or rule for the document located at http://www.w3.org/1999/xhtml. The other two attributes are declaring that we are speaking the English language.

  3. Step 3

    Type the following tags:
    <head>
    <title>PHP Pagination</title>
    </head>
    The head tag contains information about the page. The title tag declares a title, which appears on the blue bar at the top of the web browser.

  4. Step 4

    Type these remaining tags to complete the blank document:
    <body>
    </body>
    </html>

  5. Step 5
    Completed Code for Section 1
     
    Completed Code for Section 1

    Save and upload your document as survey.php to your webserver.

  6. CREATE THE SURVEY

  7. Step 1

    Type the form tags as shown:
    <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
    </form>
    The form tag contains the attribute action, having the value expressed in a PHP statement $_SERVER['PHP_SELF'];. This tells the server and browser that the instructions for processing the form are contained on this document, and not an external file.
    Setting the 'method' attribute to 'post' protects the data from view. Other methods, like 'get' append the form data to the URL in the address bar.

  8. Step 2

    Surveys are subjective. This form will use an example of every form element that is available in order to show the different scripts that needed to process them. There are [7] different form elements: <input type="hidden" />, <input type="text" />, <input type="checkbox" />, <input type="radio" />, <select></select>, <textarea></textarea>, and <input type="submit" />.

  9. Step 3
     

    Type your questions between the beginning and ending <body></body> tags.
    What is your favorite food?<br />
    Which of the following do you like the best? <br />
    Cabbage
    Brussell Sprouts
    Green Beans
    Green Peppers
    Do you like mint chocolate chip flavored ice cream? <br />
    Yes No
    Select the occupation that you think most kids aspire to be: <br />
    --Select Occupation---
    Doctor
    Lawyer
    Fire Fighter
    Police Officer
    President of the USA
    Internet Entrepreneur
    Describe your happiest experience: <br />

  10. Step 4
     

    Beneath each question, type the following:
    <input type="hidden" name="" value="" />

  11. Step 5

    Name each tag according to the content of the question. The following question is about food, so we have named the form element 'foodquestion'.
    What is your favorite food?<br />
    <input type="hidden" name="foodquestion" value="" />
    Which of the following do you like the best?<br />
    <input type="hidden" name="vegiequestion" value="" />
    Do you like mint chocolate chip flavored ice cream?<br />
    <input type="hidden" name="icecreamquestion" value="" />
    Select the occupation that you think most kids aspire to be: <br />
    <input type="hidden" name="careerquestion" value="" />
    Describe your happiest experience: <br />
    <input type="hidden" name="experiencequestion" value="" />
    Make sure that each name is a single word. It can be any combination of capital and lowercase letters, but I strongly recommend that you relate it back to the question's content in some way.

  12. PHP SURVEY, con't.

  13. Step 1
     

    The value of all the hidden input tags will be the question, as shown:
    What is your favorite food?<br />
    <input type="hidden" name="foodquestion" value="What is your favorite food?"/>
    Which of the following do you like the best?<br />
    <input type="hidden" name="vegiequestion" value="Which of the following do you like the best?" />
    Do you like mint chocolate chip flavored ice cream? <br />
    <input type="hidden" name="icecreamquestion" value="Do you like mint chocolate chip flavored ice cream?"/>
    Select the occupation that you think most kids aspire to be: <br />
    <input type="hidden" name="careerquestion" value="Select the occupation that you think most kids aspire to be:" />
    Describe your happiest experience: <br />
    <input type="hidden" name="experiencequestion" value="Describe your happiest experience:" />

  14. Step 2

    Now it is time to create the interactive form elements that will collect the survey data:
    The first question reads:
    What is your favorite food?<br />
    <input type="hidden" name="foodquestion" value="What is your favorite food?" />
    Type the following after the hidden input tag:
    <input type="text" name="foodanswer" size="60" /><br /><br />
    The input type is text, which creates a text. The name is 'foodanswer', which will help link it up to the question, and the size of the box is 60 characters long.

  15. Step 3

    The second question reads:
    Which of the following do you like the best? <br />
    <input type="hidden" name="vegiequestion" value="Which of the following do you like the best?" />
    Cabbage
    Brussell Sprouts
    Green Beans
    Green Peppers
    Type the following input tags in front of the four answer choices as shown:
    <input type="checkbox" name="vegieanswer[]" value="Cabbage" />Cabbage<br />
    <input type="checkbox" name="vegieanswer[]" value="Brussell Sprouts" /> Brussell Sprouts<br />
    <input type="checkbox" name="vegieanswer[]" value="Green Beans" /> Green Beans<br />
    <input type="checkbox" name="vegieanswer[]" value="Green Peppers" /> Green Peppers<br /><br />
    The input type is checkbox, which will create a small square in front of the choices. Each name of the checkbox has to be the same, in this case, 'vegieanswer', so that when we process the data, we can link any one of these choices to 'vegieanswer'. The value of each input tag is identical to the answer choice the user will see on the webpage. Make sure you add the brackets at the end of the name. These characters will allow PHP to loop through all of the answers, if more than one checkbox is checked.
    Make sure to end each line with a <br /> tag and the last line with two <br /> tags to keep each form element on its own line and to separate each question.

  16. Step 4

    The third question reads:
    Do you like mint chocolate chip flavored ice cream? <br />
    <input type="hidden" name="icecreamquestion" value="Do you like mint chocolate chip flavored ice cream?" />
    Yes No
    Type the following radio type input tags around the Yes and No answers as shown:
    <input type="radio" name="icecreamanswer" value="Yes" />Yes &nbsp; &nbsp;
    <input type="radio" name="icecreamanswer" value="No" />No <br /><br />
    The radio type of input tag creates a small, clickable circle in front of the Yes and No answers. The 'click' produces a small dot in the circle that indicates that the element has been set, or is 'turned on'.
    The &nbsp; characters are used to create a 'non-breaking space' between the questions. A non-breaking space is equivalent to hitting the Space Bar key.

  17. Step 5

    The fourth question reads:
    Select the occupation that you think most kids aspire to be: <br />
    <input type="hidden" name="careerquestion" value="Select the occupation that you think most kids aspire to be:" />
    --Select Occupation--
    Doctor
    Lawyer
    Fire Fighter
    Police Officer
    President of the USA
    Internet Entrepreneur
    Skip a line after the <input type="hidden" /> tag and type the following:
    <select name="careeranswer">
    Enclose all of the answer choices with the <option> tag, as shown:
    <option value="none" selected="selected">--Select Occupation--</option>
    <option value="Doctor">Doctor</option>
    <option value="Lawyer">Lawyer</option>
    <option value="Fire Fighter">Fire Fighter</option>
    <option value="Police Officer">Police Officer</option>
    <option value="President of the USA">President of the USA</option>
    <option value="Internet Entrepreneur">Internet Entrepreneur</option>
    After the last answer choice, hit enter and type the </select> end tag.
    </select><br /><br />
    The select tags create a drop-down menu, filled with choices. We have created a choice with the value of 'none' in order, during the validation process, to make sure that the question is answered. To guarantee that the default answer is 'none' we place the attribute 'selected' in the option tag.

  18. PHP Survey, con't. II

  19. Step 1

    The fifth question reads:
    Describe your happiest experience: <br />
    <input type="hidden" name="experiencequestion" value="Describe your happiest experience:" />
    Type the following after the hidden input tag:
    <textarea name="experienceanswer" rows="10" cols="50"></textarea><br /><br />
    The textarea tag creates a box that allows the user to answer the question in a paragraph, if they choose to. The words that the user types into the box are equivalent to the 'value' attribute found in the input tags.

  20. Step 2
     

    The final form element that you will need is the 'submit' button. It is simply an input tag with the type called 'submit'.
    Type the following, skipping a line after the </textarea> end tag:
    <input type="submit" name="submit" value="Submit Form" />
    The submit type of input tag will create a gray, clickable button. The name of this button can be anything that you want. Use 'submit' as the form element's name in order to eliminate future confusion. The 'value' attribute on a submit button will print words on the button, such as 'Submit', or in other cases, 'Log in'. It can be a single word, or multiple words with punctuation. To be clear, use 'Submit Form' as the button's value.
    Skip a line and type the end tag for form: </form>.
    Save and upload your document. The completed form should look like the attached picture in your browser.

  21. Step 3

    Continued, below.

  22. Step 4

    Continued, below.

  23. Step 5

    Continued, below.

  24. PHP VALIDATION

  25. Step 1
     

    At the very top of your document, where the <!DOCTYPE declaration is, hit the enter key several times. Type the opening and closing tags of PHP, as shown:
    <?php
    ?>

  26. Step 2
     

    Type the following between the opening and closing PHP tags:
    if (isset($_POST['submit'])) {
    }
    This 'if' statement declares that if the button called 'submit', when posted, is set, meaning if someone clicks the submit button, then follow whatever instruction(s) that are after the left curly brace '{' and before the right curly brace '}'.
    The word 'submit' must match whatever name you gave the submit button in your form.

  27. Step 3
     

    Assign the value of 'foodquestion' to the variable called $foodquestion, as shown (in order to keep with readable code, please enter this on the next line):
    $foodquestion = $_POST['foodquestion'];
    This statement assigns the words in quotation marks that the value attribute equals of the form element named 'foodquestion' to a variable called $foodquestion.
    Hit enter twice.

  28. Step 4
     

    Type the following:
    if (!empty($_POST['foodanswer'])) {
    $foodanswer = $_POST['foodanswer'];
    echo "<p>You have chosen: <b>" . $foodanswer . "</b> as your favorite food!</p>";
    } else {
    $foodanswer = FALSE;
    echo "<p><font color='red'>Please tell us your favorite food!</font></p>";
    }
    The statement reads, 'if after posting foodanswer you find that it is not empty, assign 'foodanswer' to the variable $foodanswer and tell the user what they have chosen. Otherwise (else) set the variable $foodanswer to FALSE and ask the user to answer the question.' The exclamation point before the empty() function translates to 'not'.
    Hit enter twice.

  29. Step 5

    Assign the value of 'vegiequestion' to the variable $vegiequestion, as shown below:
    $vegiequestion = $_POST['vegiequestion'];
    Hit enter twice.

  30. PHP Validation, con't.

  31. Step 1

    Type the following:
    if (!isset($_POST['vegieanswer'])) {
    $vegieanswer = FALSE;
    echo "<p><font color='red'><b>Please answer the question!</b></font></p>";
    } else {
    $vegieanswer = $_POST['vegieanswer'];
    echo "<p><font color='navy'>You checked: <b>";
    foreach ($vegieanswer as $v) {
    echo $v . " | ";
    }
    }
    echo "</b></font></p>";
    Checkboxes are a different sort of beast. They allow you to give more than just one answer to a question, so you have to add a specific function called a loop to cycle through all the possible answers.
    Using the isset() function, make sure that the user answered the question. If the checkboxes were not checked, then an error message is displayed to the user, otherwise, 'vegieanswer' is assigned to the variable $vegieanswer and a function called foreach() will list all of the values of $vegieanswer as the variable $v, until all the checkboxes that were clicked on have been displayed.
    Hit enter twice.

  32. Step 2

    Assign the 'icecream' question to the variable $icecreamquestion, and hit enter twice, as shown.
    $icecreamquestion = $_POST['icecreamquestion'];

  33. Step 3

    Type the following:
    if (!isset($_POST['icecreamanswer'])) {
    $icecreamanswer = FALSE;
    echo "<p><font color='red'><b>Please answer the question!</b></font></p>";
    } else {
    $icecreamanswer = $_POST['icecreamanswer'];
    switch ($icecreamanswer) {
    case 'Yes':
    echo "<p><font color='navy'>You said that you <b>do</b> like mint chocolate chip ice cream! </font></p>";
    break;
    case 'No':
    echo "<p><font color='navy'>You said that you <b>DO NOT</b> like mint chocolate chip ice cream!</font></p>";
    break;
    }
    }
    When validating a question that can have two or more right answers, you can create a custom response to those answers using the switch() function. The switch function is like an if/else statement that gives the customer a different response based on what choice they made. The switch function works like this: place the variable of what you'd like to validate between the parentheses, followed by a left curly brace. Type 'case' and a possible answer in single quotes, followed by a colon. On the next line, type the validation's response, then type 'break'. The 'break' statement stops executing the code when the condition is satisfied. If the condition is not met, then it will go onto the next possible value of $icecreamanswer.
    Hit enter twice.

  34. Step 4

    Assign 'careerquestion' to the variable $careerquestion and hit enter twice.
    $careerquestion = $_POST['careerquestion'];

  35. Step 5

    Type the following:
    $careeranswer = $_POST['careeranswer'];
    if ($careeranswer == 'none') {
    $careeranswer = FALSE;
    echo "<p><font color='red'><b>Please answer the question!</b></font></p>";
    } else {
    $careeranswer = $_POST['careeranswer'];
    echo "<p><font color='navy'>You answered that kids mostly aspire to be a(n) " . $careeranswer . "!</font></p>";
    }
    Select menus need to be posted before they can be checked, which is why we built in a value called 'none', so that if the posted answer equals 'none', we can ask the user to answer the question. The double '=' sign means 'has the value of', the single '=' sign means 'establish the value as the following'.
    Hit enter twice.

  36. PHP Validation, cont. II

  37. Step 1

    Assign 'experiencequestion' to the variable $experiencequestion and hit enter twice.

    $experiencequestion = $_POST['experiencequestion'];

  38. Step 2

    Type the following:
    if (!empty($_POST['experienceanswer'])) {
    $experienceanswer = $_POST['experienceanswer'];
    echo "<p><font color='navy'>Your response has been recorded!</font></p>";
    } else {
    $experienceanswer = FALSE;
    echo "<p><font color='red'><b>Please answer the question!</b></font></p>";
    }
    Using a 'textarea' tag in your form calls for the validation function 'empty()'. In this case, we are checking to see if the 'textarea' has any typing in it. If it does, and if the specific answer is rather long-winded, we don't want to take up the whole page with their response, so we just tell them that we have recorded their response. If they did not enter any characters into the field, then we, again, ask them to answer the question.
    Hit enter twice.

  39. Step 3

    Type the following:
    if ($foodanswer != FALSE && $vegieanswer != FALSE && $icecreamanswer != FALSE && $careeranswer != FALSE && $experienceanswer != FALSE) {
    $newV = implode(' | ',$vegieanswer);
    $to = 'youremail@yourdomain.com'
    $subject = 'Poll Results'
    $body = "<html><head></head><body>Hi Your Name!<br />Your poll has just been completed. Here are the results:<br /><br />" . $foodquestion . "<br />Answer: " . $foodanswer . "<br /><br />" . $vegiequestion . "<br />Answer: " . $newV . "<br /><br />" . $icecreamquestion . "<br />Answer: " . $icecreamanswer . "<br /><br />" . $careerquestion . "<br />Answer: " . $careeranswer . "<br /><br />" . $experiencequestion . "<br />Answer: " . $experienceanswer . "<br /></body></html>";
    $headers = "MIME-Version: 1.0\n" . "Content-type: text/html; charset=iso-8859-1\n" . "From: Your Survey donotreply@yourdomain.com";
    mail ($to, $subject, $body, $headers);
    echo "<h2>Your information has been sent to the owner of the survey. Thank you for participating!";
    } else {
    echo "<p><font color='red'><b>Your information could not be sent because of one or more errors. Please try again.</b></font></p>";
    }

  40. Step 4

    EXPLANATION
    If none of the answers equal FALSE, meaning the user answered any question, then email the results to the webmaster, otherwise, list the errors.
    In order to email the answers to the checkbox, however, we must connect the words together and assign the multiple values to one variable. The implode() function connects words into a string. After the words become a string, assign them to a variable, in this case, $newV, and email it to the webmaster.
    The mail function allows four parameters.
    To -- what email address that the email will go to
    Subject -- The subject of the email
    Body -- the body of the email, which can contain HTML
    Headers -- contains the content type, the MIME version, the FROM, CC, and BCC sections of an email.
    This body section, created like an HTML 4.0 document, has all the questions and answers to the survey, separated by <br /> tags, just like one would use on a webpage. After the mail parameters, there are two statements, one, which shows up if there are no errors, the other, if one of the questions of the survey are not answered.
    PHP sends the email, and if you typed all the code properly, it should look like the attached image.

  41. Step 5
     

    CONCLUSION
    Creating a PHP survey can be broken into three major phases. The first phase is creating the HTML form. The second phase is creating the actual survey. The third phase is validating the survey's questions and sending the results to the individual taking the poll.

Tips & Warnings
  • • Compose the survey before you start creating it electronically. This will give you a visual diagram in which to work and streamline the coding process. • Test your validation code after each step to ensure that each step works. First, test to see what happens if the user does not answer the question. Then test the various answers. • Source Edit can be downloaded for free here: http://www.brixoft.net/download.asp#ID1 • FileZilla can be downloaded for free here: http://filezilla-project.org/download.php
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Tags
Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

eHow Computers
eHow_eHow Technology and Electronics