Another week has passed and it’s time to continue our journey in creating a custom spiritual gifts assessment questionnaire.
Picking up from where we left off from last week’s tutorial, we currently completed the following:
- Created a php form
- Created an excel/csv spreadsheet of spiritual gift questions and a CCB spiritual gifts key
- Parsed excel/csv spreadsheet of display questions for form viewing via a web browser
Today’s tutorial focuses on the following three items:
- Submitting and validating form data
- Excluding certain question categories based on category key
- Summing, grouping, sorting and storing results via an excel/csv spreadsheet
We don’t have time to waste, so let’s jump head over heels in and get started with the next install of this tutorial series.
Setting up initialization variables
To start, set up showNoForm and msg variables before the formFieldData variable used in the last tutorial (as shown below).
1 2 3 4 5 6 7 8 9 10 11 |
<?PHP /** * */ $showNoForm = false; $msg = ''; $formFieldData = prepareQuestions(); ?> |
The showNoForm variable allows for the form to not be displayed upon successful completion and submission when its value is set to true.
The msg variable is used to display both pass and fail text for form validation and submission.
Both variables are covered in more detail later in the tutorial.
Submitting the form and validating form data
You currently have your php form, form questions, and a submit button based on completing the previous tutorial.
Knowing this, to capture the data from a form submission, we must capture the form’s submit button trigger.
To do so, we’ll use an if else statement, meaning if the submit button is pressed or triggered, then we’ll proceed with capturing and validating the form data.
If not, then we simply display the form questions as if the form was never submitted.
Within the if part of the if else statement, we first make sure the form button exists using PHP’s built-in isset function, then we make sure the submit button’s value is equal to a case-sensitive text Submit.
Next, it’s time to capture the form data for the following fields: First Name, Last Name, Email, and each survey answer.
Create the aforementioned variables and set each equal to the form field name using PHP’s super global variable $_REQUEST.
Notice that the cleanInput function is used to sanitize the form input. It’s ALWAYS important to sanitize form input submitted by users. NEVER trust or ASSUME a user to enter the correct information.
After all, the user could be a misfit of some sort attempting to delete your database, take your website down, or hack your website to redirect it to a high risk website.
Nevertheless, although the cleanInput function is used, it’s recommended you use PHP’s built in filters to ensure sanitize and validation of your application receiving the correct input.
Finally, set the else statement and the formFieldData variable from the previous tutorial within it, closing the else statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); } else { $formFieldData = prepareQuestions(); } ?> |
Capturing, summing, grouping, and sorting answers
Okay, it’s time for a bit more heavy lifting. The form has been submitted, and form fields captured, validated, and sanitized.
Next, we must total the values for each spiritual gifting and rank/sort the spiritual gifting in descending order based on their summed value.
The next step in the process is to capture the answers in an array. Create the arrAnsKey variable and set it equal to the prepareAnswerKeyArray function, passing to this function the answer variable as its argument.
In short, the prepareAnswerKeyArray function creates and returns a multi-dimensional array of category and answer bindings using the question-key.csv file to retrieve the category and the form field answer arrays.
Next, create the arrGroupSumSort variable and set it equal to the prepareGroupSumSortArrray function, passing to this function the arrAnsKey variable.
In short, the prepareGroupSumSortArray function groups and sums each spiritual gifting category based on the answers provided for each categorized question ranking of a 1 to 5 value.
Once grouped and summed, the array is sorted in descending order, according to each groups (or spiritual gifting) summed value, using PHP’s built-in arsort function.
Now that we have a ranking for how well a person scored in each spiritual gifting area, let’s discuss how to exclude certain giftings from being viewed via the report that we’ll cover in the coming weeks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); // capture answers in an array $arrAnsKey = prepareAnswerKeyArray($answers); // group, sum and sort answers using key $arrGroupSumSort = prepareGroupSumSortArray($arrAnsKey); } else { $formFieldData = prepareQuestions(); } ?> |
Excluding certain question categories based on category key
Here’s where things get a bit hairy or dicey in conversation. The reason I make this statement is that assessing spiritual gifts can be a tricky conversation to be had in general.
Mix in denominations, bible versions and commentaries, and spiritual maturity or lack of at a personal or corporate level, and we have the making of a war on our hands to say the least.
It’s quite a hot button topic and QUICKER than quick is how we arrive.
Nevertheless, there may be certain spiritual gifts that you or church desire a person to answer but you don’t desire to show or reveal this information to the person immediately.
For instance, Prophecy tends to be a hot button topic. A person could believe they have the gift of prophecy, yet their definition is that they are a Prophet.
See how quick things can go off the rail with such a statement? 🙂
Nevertheless, you may choose not to show a specific category by preparing the survey results to exclude the category and its results.
This is what the prepareResultsData function does. Be sure to set the response_data variable equal to the prepareResultsData function.
Whatever categories are listed in the Excludes column of the question-gift-excludes.csv file used within the prepareGiftExclusions function found in the prepareResultsData function, then those categories are excluded when the data is being prepared to be written to the excel/csv file for reporting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); // capture answers in an array $arrAnsKey = prepareAnswerKeyArray($answers); // group, sum and sort answers using key $arrGroupSumSort = prepareGroupSumSortArray($arrAnsKey); // exclude categories based on key and prepare results to be written to csv file $response_data = prepareResultsData($arrGroupSumSort); } else { $formFieldData = prepareQuestions(); } ?> |
Storing results via an excel/csv spreadsheet
Okay, you’ve made it this far and you’re almost home free. Hang in there…
From the previous section, pass the firstname, lastname, and response_data variables as arguments in their respective order to the createDataFile function.
This function simply creates and writes data to a csv file (e.g. alvin-brown_sga-resluts_123847263.csv) containing the grouped, summed, and sorted spiritual gifting results prepared in the previous section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); // capture answers in an array $arrAnsKey = prepareAnswerKeyArray($answers); // group, sum and sort answers using key $arrGroupSumSort = prepareGroupSumSortArray($arrAnsKey); // exclude categories based on key and prepare results to be written to csv file $response_data = prepareResultsData($arrGroupSumSort); // create and prepare the file, file name and content to be written createDataFile($firstname,$lastname,$response_data); } else { $formFieldData = prepareQuestions(); } ?> |
Displaying the success or failure message
Last but not least, create a showNoForm variable and set it equal to true. Then create a msg variable with the following text string: Thank you for completing the spiritual gifts assessment.
Of course, you could easily turn the string into a variable if you wanted to use this same form format for another type of survey (hint, hint). 😉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); // capture answers in an array $arrAnsKey = prepareAnswerKeyArray($answers); // group, sum and sort answers using key $arrGroupSumSort = prepareGroupSumSortArray($arrAnsKey); // exclude categories based on key and prepare results to be written to csv file $response_data = prepareResultsData($arrGroupSumSort); // create and prepare the file, file name and content to be written createDataFile($firstname,$lastname,$response_data); $showNoForm = true; $msg = 'Thank you for completing the spiritual gifts assessment.'; } else { $formFieldData = prepareQuestions(); } ?> |
And before testing, you’ll need to echo the msg variable inside the form, as well as create a if statement for showing and hiding the form based on the presence of the showNoForm variable, just before the H1 tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Spiritual Gifts Assessment</title> </head> <body> <form method="post" action="<?php echo $_SERVER[" PHP_SELF "];?>"> <? echo $msg; ?> <? if(!$showNoForm){ ?> <h1>Spiritual Gifts Assessment</h1> <p> <label>First Name</label> <input name="firstname" placeholder="Type Here" required /> </p> |
And don’t for get to close the showNoForm variable if statement just before the closing form tag and after the submit button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Your response choices are: <ul> <li>5 — Highly characteristic of me/definitely true for me</li> <li>4 — Most of the time this would describe me/be true for me</li> <li>3 — Frequently characteristic of me/true for me – about 50 percent of the time</li> <li>2 — Occasionally characteristic of me/true for me - about 25 percent of the time</li> <li>1 — Not at all characteristic of me/definitely untrue for me</li> </ul> <? echo $formFieldData; ?> <input id="submit" name="submit" type="submit" value="Submit"> <? } ?> </form> </body> </html> |
Time to save and test your technical prowess
Well, you made it to the end of this tutorial. 😉 As for what’s next…
Next week, I’ll show you how to complete the following:
- Create a page to view a list of completed spiritual gifts assessments
- Email a summary to download spiritual gifts excel/csv file
For now, you’re code should look like the code below in its entirety.
BY THE WAY, I RECOMMEND PLACING ALL FUNCTIONS INTO A SINGLE FILE INCLUDE MUCH LIKE THE PREVIOUS TUTORIALS USE THE GENERAL.PHP FILE.
THIS MAKES FOR A CLEANER AND MANAGEABLE CODEBASE. 😉
Save your file and you’re now ready to open a web browser for viewing and submitting a spiritual gifts assessment.
Rest up, and be ready to expand your knowledge next week. See you next week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
<?PHP /** * */ $showNoForm = false; $msg = ''; if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ $firstname = cleanInput($_REQUEST['firstname']); $lastname = cleanInput($_REQUEST['lastname']); $email = cleanInput($_REQUEST['email']); $answers = cleanInput($_REQUEST['ans']); // capture answers in an array $arrAnsKey = prepareAnswerKeyArray($answers); // group, sum and sort answers using key $arrGroupSumSort = prepareGroupSumSortArray($arrAnsKey); // exclude categories based on key and prepare results to be written to csv file $response_data = prepareResultsData($arrGroupSumSort); // create and prepare the file, file name and content to be written createDataFile($firstname,$lastname,$response_data); $showNoForm = true; $msg = 'Thank you for completing the spiritual gifts assessment.'; } else { $formFieldData = prepareQuestions(); } ?> <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Spiritual Gifts Assessment</title> </head> <body> <form method="post" action="<?php echo $_SERVER[" PHP_SELF "];?>"> <? echo $msg; ?> <? if(!$showNoForm){ ?> <h1>Spiritual Gifts Assessment</h1> <p> <label>First Name</label> <input name="firstname" placeholder="Type Here" required /> </p> <p> <label>Last Name</label> <input name="lastname" placeholder="Type Here" required /> </p> <p> <label>Email</label> <input name="email" type="email" placeholder="Type Here" required /> </p> <h2>DIRECTIONS</h2> <p>This is not a test, so there are no wrong answers. The Spiritual Gifts Survey consists of 80 statements. Some items reflect concrete actions; other items are descriptive traits; and still others are statements of belief.</p> <ul> <li>Select the one response you feel best characterizes yourself and place that number in the blank provided. Record your answer in the blank beside each item.</li> <li>Do not spend too much time on any one item. Remember, it is not a test. Usually your immediate response is best.</li> <li>Please give an answer for each item. Do not skip any items.</li> <li>Do not ask others how they are answering or how they think you should answer.</li> <li>Work at your own pace.</li> </ul> Your response choices are: <ul> <li>5 — Highly characteristic of me/definitely true for me</li> <li>4 — Most of the time this would describe me/be true for me</li> <li>3 — Frequently characteristic of me/true for me – about 50 percent of the time</li> <li>2 — Occasionally characteristic of me/true for me - about 25 percent of the time</li> <li>1 — Not at all characteristic of me/definitely untrue for me</li> </ul> <? echo $formFieldData; ?> <input id="submit" name="submit" type="submit" value="Submit"> <? } ?> </form> </body> </html> <?PHP function createDataFile($fName,$lName,$rData){ // create and prepare the file, file name and content to be written $fileName = $fName.'-'.$lName.'_sga-results_'.time().'.csv'; $rObject = '"Gift","Total"'. "\n"; $f = fopen($fileName , 'w+'); fwrite($f , $rObject.$rData ); fclose($f); } function prepareResultsData($data){ // Time to exclude a few results based on controversial giftings $excludedGifts = prepareGiftExclusions(); $errors = array_filter($excludedGifts); $response_data = ''; foreach($data as $key=>$value){ if(!in_array($key, $errors)){ $response_data .= '"'.$key.'","'.$value.'"'."\n"; } } return $response_data; } function prepareGroupSumSortArray($arrAnswers){ //Summing array values/giftings $sumArray = array(); foreach ($arrAnswers as $k=>$subArray) { foreach ($subArray as $id=>$value) { @$sumArray[$subArray[0]]+=$value; } } // Sorting the summed array values/giftings arsort($sumArray); return $sumArray; } function prepareAnswerKeyArray($ans){ // arrays for capturing answers $newAnsArray = array(); $ansArray = array(); // foreach answers in comparison to key foreach($ans as $key=>$answer){ $id = $key+1; $err_upTmpName = 'question-key.csv'; $row = 0; if (($handle = fopen($err_upTmpName, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { if($row == 0){ $row++; } else { if(!empty($data[1]) && $row == $id){ $newAnsArray[] = array($data[1],$answer); } $row++; } } } fclose($handle); } return $newAnsArray; } function prepareGiftExclusions(){ $err_upTmpName = 'question-gift-excludes.csv'; $row = 0; $formFields = array(); if (($handle = fopen($err_upTmpName, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { if($row == 0){ $row++; } else { // $data[0] = first name; /************************/ if(!empty($data[0])){ $formFields[] = $data[0]; $row++; } } } } fclose($handle); return $formFields; } function prepareQuestions(){ $randNum = false; $err_upTmpName = 'question-key.csv'; $row = 0; $formFields = ''; if (($handle = fopen($err_upTmpName, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { if($row == 0){ $row++; } else { // $data[0] = question; /**********************/ if(!empty($data[0])) $formFields .= outputQuestion($row,$data[0]); $row++; } } } else { $formFields .= 'File could not be opened.'; } fclose($handle); return $formFields; } function outputQuestion($rowNumber,$questionData){ $formFields = ''; $formFields .= '<p style="padding: 4px 2px;">'; $formFields .= '<input name="ans[]" style="padding: 4px 2px; margin: 0px 4px; width: 25px;" min="1" max="5" type="number" maxlength="1"'; $formFields .= ' required /> '; $formFields .= $rowNumber.') '.$questionData.'</p>'; return $formFields; } function cleanInput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> |
createDataFile Function
This function creates and stores the spiritual assessment data for unique individuals in a excel/csv file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<? function createDataFile($fName,$lName,$rData){ // create and prepare the file, file name and content to be written $fileName = $fName.'-'.$lName.'_sga-results_'.time().'.csv'; $rObject = '"Gift","Total"'. "\n"; $f = fopen($fileName , 'w+'); fwrite($f , $rObject.$rData ); fclose($f); } ?> |
prepareResultsData Function
This function prepares the data to be written to excel/csv file, using the prepareGiftExclusions function to not include categories excluded from reporting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?PHP function prepareResultsData($data){ // Time to exclude a few results based on controversial giftings $excludedGifts = prepareGiftExclusions(); $errors = array_filter($excludedGifts); $response_data = ''; foreach($data as $key=>$value){ if(!in_array($key, $errors)){ $response_data .= '"'.$key.'","'.$value.'"'."\n"; } } return $response_data; } ?> |
prepareGiftExclusions Function
This function uses the question-gift-excludes.csv to return an array of categories to exclude from reporting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?PHP function prepareGiftExclusions(){ $err_upTmpName = 'question-gift-excludes.csv'; $row = 0; $formFields = array(); if (($handle = fopen($err_upTmpName, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { if($row == 0){ $row++; } else { // $data[0] = first name; /************************/ if(!empty($data[0])){ $formFields[] = $data[0]; $row++; } } } } fclose($handle); return $formFields; } ?> |
prepareGroupSumSortArray Function
This function sums each category grouping of questions and sorts the array groupings in descending or by value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?PHP function prepareGroupSumSortArray($arrAnswers){ //Summing array values/giftings $sumArray = array(); foreach ($arrAnswers as $k=>$subArray) { foreach ($subArray as $id=>$value) { @$sumArray[$subArray[0]]+=$value; } } // Sorting the summed array values/giftings arsort($sumArray); return $sumArray; } ?> |
prepareAnswerKeyArray Function
This function binds each questions answer value to the category label assigned to each question as a multi-dimensional array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?PHP function prepareAnswerKeyArray($ans){ // arrays for capturing answers $newAnsArray = array(); $ansArray = array(); // foreach answers in comparison to key foreach($ans as $key=>$answer){ $id = $key+1; $err_upTmpName = 'question-key.csv'; $row = 0; if (($handle = fopen($err_upTmpName, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { if($row == 0){ $row++; } else { if(!empty($data[1]) && $row == $id){ $newAnsArray[] = array($data[1],$answer); } $row++; } } } fclose($handle); } return $newAnsArray; } ?> |
cleanInput Function
This function was previously named clean_input function, and was changed to cleanInput function to remain consistent in naming convention. This function sanitizes form input submitted by user. I recommend using PHP’s built-in filters for sanitization and validation of form data.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?PHP function cleanInput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> |