You are on page 1of 15

StreamliningtheDataCollectionProcesswithPHP Whiledatacollectioncanbeatediousprocess,compilingthedataand determiningpatternscanbeanequallytimeconsumingenterprise. Whilethereisthetraditionaltechniqueofcollectingdataonpaper(suchas surveys)andlatercopyingallobtaineddatatoaspreadsheetinorderto determinetrends,moderntechnologysuggestsamoreefficientalternative. UtilizingtheInternetandbasiccomputerknowledge,onecaneasilyconstructa meanstonotonlyelectronicallyacceptdata,buttoalsoautomatically compileit.Thistechniquecaninstantaneouslyoutputaverages,commonly usedwords,graphs,andmoreregardingthecollecteddata. ThisguideutilizestheprogramminglanguagePHP.Whilecomputerscience knowledgeiscertainlyhelpful,theprovidedcodesamplesandmethodsshould providebasicfunctionstofitanydatacollectionapparatus.UsingPHPisnot unheardof,andtheremaywellbemoreefficientwaystoachievethistask.

However,thepurposeofthisguideistohelppeopleconsiderthebenefitsof technologyToconsideralternativesthatcanultimatelyimproveandenhance thescientificprocess. SameeVakil 09July2010 Revision02

Page|1

Step1:CreatetheFormPage PHPisaserversidelanguage,meaningthateverythingiscalculatedonline.The techniquedescribedinthisguiderequiresthreeparts:AFormPage,a SubmissionRoutine,andaStatisticsPage.Firsthowever,weneedaplaceto hostourpages.Whileanywebspace(thatallowsPHP)willdo,agreatfree optionforthosewithoutanymeansofwebhostingishttp://www.zymic.com.

UponvisitingtheControlPanelandthentheFileManagersectionsafter registeringanaccount,youwillbepresentedwithapagesimilartotheone above.Goaheadandcreateapagecalledindex.htmlThiswillserveas theFormPagewhichwillacceptdata. Nowifthispagewillbeusedasasurveywhichwillbepresentedtomultiple people,itisagoodideatomakeitpresentable.Thisguidewillnotcoverhow tocreateaproperweblayout,butthereareanumberofsitesthatprovide freelayoutstouse.However,itwilldiscussafewbasictypesofformsthatwill beusefulincreatingasurvey.Tostart,clickthepenciliconnexttothepage Page|2

thathasbeencreatedtoeditit.Forourinputpage,weneedtocreateForms thatwillenableouranswerstobeusedbyourcode.Therearetwomaintypes: TextFields: Theseareboxeswhereyoucaninputtext.Youcanadjustthesizeofthemin ordertofityourpurposesbetter. Thefollowingcodewillcreateone: <inputname="NameMe"type="text"size=5/> ThenameisimportantItwillidentifythefieldlatersonameitsomethinguseful suchasAge.Thesizecanbeadjustedaswelltochangethehorizontalwidth ofthefield. RadioButtons: Thesearebuttonsthatwillletyouselectonlyoneofoutofagroupofchoices, asifyouweretakingamultiplechoicetest.Thefollowingcodewillcreateone:
<input type="radio" name="Married" value="Y">Yes <input type="radio" name="Married" value="N"> No

ThenameisonceagainimportantItwillidentifythefieldlatersonameit somethingusefulsuchasthequestionbeingasked(donotusespaces).The valuewilltellthedatacompilerwhateachbuttonmeanssousedescriptive labels.Thetextaftertheclosingbracket>canbeanythingandwillbeseenon thepage. AllofthesefieldtypescanbeusedmultipletimesonaFormPageaslongasthe namelabelsaredifferent(unlessofcoursetheyareinthesamegroupsuchas withradiobuttons).Onceallthefieldsareplacedinthepage,allthatneedsto beaddedisthesubmitbutton,usingthefollowingcode: <inputtype="submit"value="Submit"/> Thatsit!YouaredonewiththeFormPage.Dontworry,itdoesntdoanything yetuntilwewritetheSubmissionRoutine.

Soputtingitalltogether,wecanhavesomethinglikethisinthepage'scode: Page|3

Howoldareyou? <inputname="Age"type="text"size=5/> <br><br> AreyouMaleorFemale? <inputtype="radio"name="YourSex"value="M">Male <inputtype="radio"name="YourSex"value="F">Female <br><br><br><br> <inputtype="submit"value="Submit"/> Youmaynoticeatagwrittenas<br>.Thistagmeanslinebreakandpushes everythingdownthethenextline.Naturally,usingtwoinarowwillcausethere tobetwolinesinbetweenthenextpartofthepage,creatingagap.Ifweput thatcodeinthewebeditor,wegetthefollowing:

Notbad!Withthisinformationalone,youwouldbeabletodeterminethe averageageofyourdatagroup,themodeage,themedianage,theratioof malestofemales,theyoungestmale,theoldestfemale,etc...Allofwhich wouldbedoneautomaticallyoncetheSubmissionRoutineandtheStatistics Pagearefinished.

Page|4

Step2:WritetheSubmissionRoutine Therereallyarenotmanywaystodothis,soyourcodewillbemoreorlesslike theexamplecode.Forthis,wewillhavetocreateaPHPfile.Whileyoucanuse anormaltexteditorsuchasnotepadtodothis,myfavoritetooliscalledGeany (http://www.geany.org/)sinceitcolorsimportantpartsofthecode automaticallyandletsyouknowifyoumisalignedabracket. Forourpurposes,createanewfile,saveitasSubmit.phpandopenitupin thetexteditorofyourchoice.Hereisthecodethatwouldcorrespondwith theaboveFormPage: <?PHP $currentFile="ResponseData.vkil"; $fh=fopen($currentFile,'r'); $theData=fread($fh,filesize($currentFile)); fclose($fh); $fh=fopen($currentFile,'w')ordie("ERROR!Cannotopenfile!"); fwrite($fh,"$theData^SplitEntries^"); $AgeData=$_POST['Age']; $SexData=$_POST['YourSex']; fwrite($fh,"$AgeData^SplitAnswers^$SexData"); fclose($fh); header("Location:http://www.thanks.com"); ?> Theonlypartsthatwillreallyvaryfromformtoformaretheboldedcomponents. Thepatterninthecodeissurelyclear,buttoreiterate,addanentryforeach formusingtheformat: $nameData=$_POST[name]; Thenameintheabovelinewouldbetheuniquenameyouassignedtoeach form(orbuttongroup)intheFormPage!Whatwearedoinghereisputtingthe answersgivenintheformintoitsownvariablewhichwouldbe$namedData. (TIP:InPHPcode,anythingstartingwitha$isavariable!) Forthelinestartingwithfwritefollowthesamepatternandplace ^SplitAnswers^betweeneachformintheline.Thislineistellingtheservertotake Page|5

alloftheformvariablesandwritethemintoaresponsefilecalled ResponseData.vkilwhichwillappearinthefilemanagerofthewebsite.Each variableisseparatedwithadelimitercalled^SplitAnswers^soourdatawillnot getjumbledtogether.OurStatisticsPagewillreadthisresponsefileandoutput thedatainapresentableway,aswellasperformanystatisticalcalculations. Asfortheheaderlineatthebottom,replacethatURLwithanypageyouwish. Itwilldirecttheusertothatpageaftertheyhitthesubmitbutton. Aftersavingthefile,uploadittoyourwebspace Butwearenotdoneyet!WestillneedtotellourFormPagetousethisroutine. Todoso,justadd<formaction="Submit.php"method="post">beforeallofthe formcodeand</form>afterit.

...Done!Thesitenowsavesallresponsestotheform.Notethatthefirsttimeyou useit,itmightthrowanerroratyousincetheresponsefiledoesnotyetexist. Thenexttimeyouuseit,itshouldbefine.Remember,theprovidedcode representsonlythebasics!Byintelligentlychoosingwhichfieldstouseonaform, onecancreateaveryefficientmeansofacceptingdata.Ofcourse,thereare manymoretypesofforms.Agoodplacetolearnhowtocreatemoreformsis http://www.w3schools.com/html/html_forms.asp.

Page|6

Afullfledgedformexample:

Page|7

Step3:DisplayingtheStats Hereisthepartthatcanvarythemost,basedonwhatonewantstodowithhis stats.Whilethisguidewillprovidecommonlyusedmethods,feelfreeto experimentwithPHPtowriteyourownfunctions.TolearnmoreaboutPHP,visit http://www.php.net/manual/en/langref.phpforreferences,documentation andmore.Inaddition,generatingrealtimegraphswillnotbecoveredinthis tutorial,butausefulplacetostartishttp://teethgrinder.co.uk/openflashchart/. Sincethissectionofthetutorialcangetcomplicatedfast,itisbrokendowninto manysmallchunkswhereeachstepwillbuildonthenext.Sincethecodehere isthemostalienlooking,itwillbehelpfultoknowwhatexactlytheiscodedoing withthedata.Suchexplanationswillbewritteninblackandbeprecededwith //,denotingthatthefollowingtextisnotpartofthecode. Tostart,letscreateafilecalledStats.PHPandputdownabasicskeleton: <?php $file=fopen("ResponseData.vkil","r")orexit("Unabletoopenstatsfile!"); //WesavetheResponseDatafiletoavariablecalled$fileforeasyaccess. $subjects=array(); //WecreateanArray,$subjects,whichwillholdtheresponsesforeachperson. while(!feof($file)) { ExplodeRaw(fgets($file)); //ThiscallsthefunctionExplodeRawwiththecontentsofthefile. } fclose($file); functionExplodeRaw($rawline) { $exploded_raw=explode("^SplitEntries^",$rawline); global$subjects; foreach($exploded_rawas$subject) { if($subject!="")array_push($subjects,$subject); } //Theselineshavenowwritteneachperson'sresponsestothearray //$subjects.Ifyouvisualizethis,basedonourform,itmightlook //somethinglike[32^SplitAnswers^F,34^SplitAnswers^M]iftwopeople //hadansweredoursurvey;Oneaged32andfemaleandtheother Page|8

} ?>

//aged34andmale.

Nowthatwehavethebasicsdown(datainterpretation),wecanwritesome usefulfunctionstohelpwithstatisticaltrending.First,let'swriteamethodto displayasubject'sanswers. functionDisplaySubject($rawsubject) //WenameourfunctionDisplaySubjectandnamethesubjectwewillbe //lookingat$rawsubject. { $exploded_subject=explode("^SplitAnswers^",$rawsubject); //Wesplitupthesubject'sresponsesforeasyaccess.Thislinewillbe //presentinprettymucheverystatisticfunction.Afterthiscommand, //thedataforsubject1(Age32,Female)canbethoughtofalistlikethis: //0.32 //1.F //CountingbeginswithzeroinPHP.Ifthereweremorequestionsinthe //survey,theywouldberegardedas#2,#3,andsoon. if($exploded_subject[0]!="") echo"Age: $exploded_subject[0]</br>"; //IfthesubjecthasAgedata(linenumber0),printitonthestatspage. if($exploded_subject[1]!="") echo"Sex:$exploded_subject[1]</br>"; //IfthesubjecthasSexdata(linenumber1),printitonthestatspage. } Alright,nextletuswriteafunctiontocalculateaverageage.Youshouldsee somesimilaritiestotheDisplaySubjectmethodabove. functionAverageAge() //ThisfunctionisnamedAverageAge { global$subjects; $sum=0; //Averageiscalculatedbytakingthesumofallitemsanddividingitby //theamountofitems.Here,wesetoursumtozeroinitially. foreach($subjectsas$subject) //foreachisafancywayofsayingthatwewillbegoingthrougheach //subjectandanalyzingthemindividually. { Page|9

} return$sum/sizeof($subjects); //Printoutthesumdividedbytheamountof(sizeof)subjects...the //Average!Nottoobadthistimearound,huh? } Okaythen,nowthatwehavedoneanAveragecalculatingmethod,a Countingmethodshouldbesimple,right?Seeforyourself! functionNumberMales() //Specifythenameofthefunction. { global$subjects; $number=0; //Wehaven'tstartedcountingyet,soournumberiszero. foreach($subjectsas$subject) //Theprogramwillbegoingthrougheachsubjectindividually. { $exploded_subject=explode("^SplitAnswers^",$subject); if($exploded_subject[1]=="M") $number+=1; //Thelinestartingwithifcanbereadas,IftheAgeDataforthecurrent //subjectisequaltoM(line1),addonetoourcount.Guesswhatwe //woulddoifwewerecountingfemales?WewouldsimplychangetheM //toanF! } return$number; //Printoutthenumberonthestatspage. } Now,allthatremainsistocallthefunctions.Allfunctionsmustbecalled otherwisetheyjustsitthere!Onewaytodothisisbyusingthefollowingcode: echo"<h3>QuickStats:</h3>"; //echoplacesthefollowingtextdirectlyonthewebpage.Itwillalsouseany //HTMLtagssuchas<b></b>forbold.SomeHTMLtagscanbefoundhere: Page|10

$exploded_subject=explode("^SplitAnswers^",$subject); //Onceagain,wesplitupthesubject'sresponses.(See //DisplaySubjectcomments). $sum+=$exploded_subject[0]; //Addthesubject'sAgedata(linenumber0)tothesum.

//http://www.w3schools.com/HTML/html_formatting.asp echo"NumberofSubjects:"; echo"<b>".sizeof($subjects)."</b></br>"; //Herewearecallingthecommandcalledsizeofwhichwesawinthe //Averagefunction.sizeofneedssomethingtocountthesizeofsowetellitto //outputthesizeof$subjectstocounthowmanypeopletookthesurvey. //Whenbeingechoed,functionsneedtobesurroundedbyperiodsand //encasedinquotes. echo"NumberofMaleSubjects:<b>".NumberMales()."</b></br>"; echo"NumberofFemaleSubjects:<b>".NumberFemales()."</b></br>"; echo"AverageSubjectAge:<b>".AverageAge()."yearsold</b></br></br>"; echo"<h3>CurrentData:</h3>"; foreach($subjectsas$subject) { DisplaySubject($subject); echo"</br>"; } //DisplaySubjectisdoneslightlydifferently.Weusetheforeachcommandtogo //througheachsubject'sdataandcallDisplaySubjectsoitwillprintthedatafor //allthesubjectswhotookthesurvey.Sincewewroteecholinesin //DisplaySubject,wedonotneedtowriteitagainhere.Youcouldhave //similarlywrittenecholineswithinthefunctionsfortheAverageAgeorcounting //functionstoo.NotethatyouwouldhavetoechoAverageSubjectAge //separatelyinthatcase.

Puttingitalltogether,andintheproperorder,hereisourcompleteStats.PHP: <?php $file=fopen("ResponseData.vkil","r")orexit("Unabletoopenstatsfile!"); $subjects=array(); while(!feof($file)) { ExplodeRaw(fgets($file)); } fclose($file); echo"<h3>QuickStats:</h3>"; echo"NumberofSubjects:"; Page|11

echo"<b>".sizeof($subjects)."</b></br>"; echo"NumberofMaleSubjects:<b>".NumberMales()."</b></br>"; echo"NumberofFemaleSubjects:<b>".NumberFemales()."</b></br>"; echo"AverageSubjectAge:<b>".AverageAge()."yearsold</b></br></br>"; echo"<h3>CurrentData:</h3>"; foreach($subjectsas$subject) { DisplaySubject($subject); echo"</br>"; } functionExplodeRaw($rawline) { $exploded_raw=explode("^SplitEntries^",$rawline); global$subjects; foreach($exploded_rawas$subject) { if($subject!="")array_push($subjects,$subject); } } functionDisplaySubject($rawsubject) { $exploded_subject=explode("^SplitAnswers^",$rawsubject); if($exploded_subject[0]!="") echo"Age: $exploded_subject[0]</br>"; if($exploded_subject[1]!="") echo"Sex:$exploded_subject[1]</br>"; } functionAverageAge() { global$subjects; $sum=0; foreach($subjectsas$subject) { $exploded_subject=explode("^SplitAnswers^",$subject); $sum+=$exploded_subject[0]; } return$sum/sizeof($subjects); Page|12

functionNumberMales() { global$subjects; $number=0; foreach($subjectsas$subject) { $exploded_subject=explode("^SplitAnswers^",$subject); if($exploded_subject[1]=="M") $number+=1; } return$number; } functionNumberFemales() { global$subjects; $number=0; foreach($subjectsas$subject) { $exploded_subject=explode("^SplitAnswers^",$subject); if($exploded_subject[1]=="F") $number+=1; } return$number; } ?> Noticethatthefunctioncallingecholinescomebeforeallofthefunctions.This doesn'thavetobethecase,butitmakesthingsawholelotneater. Alright!Thatwasn'ttoopainfulwasit?Usingthesimplefunctionsprovided,I'm sureyouwouldbeabletofigureouthowtowriteotherfunctionssuchasone thatwouldfindModeorMedian...It'sallprettymuchthesameroutineonceyou understandhowthedataisbeinghandled.Ifyouneedinformationonitsusage orsyntax,justdropitintoGoogleorcheckoutthePHPdocumentationgivenat thestartofthissection. Wellthisiswherethetutorialends.Yournewstatspagecanbeaccessedby navigatingtothatPHPpageinyourbrowser.Evenifyousimplycopyandpaste Page|13

allthecodepiecesinthisguide,youwillstillgetafullyworkingsurveycapable ofhandlingAgeandSexinformation.Moreadvancedfunctionshowever,are uptoyou.Programmingcanbedifficultandrewardingatthesametime.I challengeyoutoplaywiththeexamplesandendeavortoformulateyourown functions.Ifyougetstuck,therewillalwaysbeaCompScimajoreagertoplay withthecodeorifonecannotask,Googleawaits. Therearesomanyapplicationsoftechnologythatcanstreamlinemundane activities,theyonlyneedbediscoveredfirst. Ihopethistutorialwasatleastofsomehelp,evenpartially.Justimagine:Data instantlycompiledandpresentedtoyouassoonasitisinputted.Yougetto seetrendsandgraphsofthedataatdifferentpointsintime,allwithoutlifting afinger. ExampleofafullfledgedStatisticspage:

Page|14

Page|15

You might also like