PHP Programming: PHP Crush Course! Learn PHP Programming ...
Transcript of PHP Programming: PHP Crush Course! Learn PHP Programming ...
PHPPROGRAMMING
PHPCRUSHCOURSE!LEARNPHPPROGRAMMINGIN4HOURS!PHPFORBEGINNERS-SMARTANDEASYWAYSTO
LEARNPHP&MYSQL
BookDescription“LearnPHPin4Hours!”promisestogiveyoucompleteintroductoryknowledgetoPHPandMySQL.Youwillbeabletogetstartedonyourjourneytobuildingawesomedynamicwebsitesthathelpyouachieveyourdreamsinnotime.
Thisbookcontainsdefinitionsthatarestraightforward,examplesthatareshortandsweetandexplanationsthatensuremasteryofthebasicsveryquickly.
YouwillbeabletoblastthroughthisbookwhilegainingdeepknowledgethatpreparesyoutotackletheadvancedfeaturesofbothPHPandMySQLwhilesimultaneouslybeingabletodosomethingveryusefulwiththebestpractices.Thisisanamazingeducationalbook!
Whatisinthebook?
IntroductiontoPHPProgramming
Chapter1–Hour1:InstallationandPHP
WediscussinstallationofawebserverpackageandshowhowtouseittorunPHPscript.WealsocoversomeofthebasicsofPHP
Chapter2–Hour2:MorePHPBasics
WedivedeeperintothebasicsofPHP
Chapter3–Hour3:MySQLBasics
WediscusshowtoaccessthecommandlinetoenterMySQLcommandsandusethemtoworkwithdatainthedatabase
Chapter4–Hour4:PHPandMySQL
WeconsolidatetheknowledgeandusebothPHPandMySQLtocreateaverysimplewebsitewithdynamiccontent
Let’sgetstarted!
TableofContent
Introduction
Chapter1-Hour1:InstallingandPHPBasics
Chapter2-Hour2:MorePHPBasics
Chapter3-Hour3:MySQLBasics
Chapter4-Hour4:PHPandMySQL:TheDynamicDuo
Conclusion
Introduction“Youcannotopenabookwithoutlearningsomething.”-Confucius
PeoplelearnPHPformanyreasons.Everylanguagehasabitofalearningcurveandonecangetboggeddownintwomuchtheorythatitcanmakeitunappealingbecausethetaskaheadseemsodious.Maybeyouwanttobuildasimpleblogorsomethingasadvancedasamassiveonlinee-commercesitewiththousandsofproductsupforsale.Itishardtoknowwheretostartgettingtheneededknowledge.
Ifyouarelookingforawaytogetgoingfastinordertomakeyouvisionsarealitythenyouhavecometotherightplace!ThisbooksaimsatgettingyoustartedonyourjourneytoPHPandMySQLmasteryin4hours!Itdoesthisbytellingyouthemostimportantstuffyouneedtoknowtogetstartedquicklyfortheabsolutebeginner,ineitherPHPorMySQL,soyougettodoingusefulstuffasquicklyaspossible.
ThisisnotacomprehensiveguidetoPHPandMySQLthatcoversalltheaspectsbutacrashcoursethatgivesyouapracticalguideonhowtodoreallycoolbasicthingswithPHPandMySQLontheirownandtogether.Thetwocangetprettyadvancedbutwiththeknowledgeinthisbook,youshouldbeabletogetthatprototypeupandrunningasyoutacklethemoreadvancedtopics.
AlittleknowledgeofHTMLandCSSwillbeneededbeforebecause,really,PHPisjustalanguagethatisusedtoproducewebpagesanditsfinaloutputisHTML.WewillgooverallthebasicsofPHPandMySQLandfinallyputitalltogetherandbuildsimplewebsitewhereyouwillbeabletostorearecordsofyourfavouriteartistsusingthedynamicduo.
Thebasicsareallyouneedtogetgoingin4hours(andthisbook,ofcourse)isallyouneed.
ButwhatisPHPorMySQLandwhydoyouneedittoaccomplishthispreviouslyimpossibletask?
AShortIntroductiontoPHP
PHPstandsforHypertextProcessor.Itisaserversidescriptinglanguagethatisusedtoproducedynamicwebcontentamongotherthings.ThismeansthateverythingPHPdoesisnotdoneonthecomputerthatisusedtoviewthewebpages,calledtheclient,butaspecialisedcomputercalledaserverthathousesallthewebpagesthatyouareviewingontheclientmachine.
BeingascriptinglanguagemeansthatPHPcan’treallybeusedtomakestandaloneapplicationsthatrunonyourcomputerasitisdesignedtoonlydothingswhenaneventhappenswithinwebpageslike;clickingonalinkorgettingformdatawhenawebformissent.
YoucanembedPHPintoyourHTMLwebpagesandproducepagesthatarecustomisedaccordingtotheinformationyougetfromyourusers.Thisendsupmakingwebpagesmoreexcitingratherthaniftheywerejuststatic.PHPcanbeusedtoproducewebpagesbecauseitsfinaloutputisHTML.
Itisveryefficientintheserverside,widelyused,cross-platform(runsonWindows,Linux,UNIX,MacOSX,etc.)andeasiertolearnthananyotherfullyfeaturedlanguagelikeC,JavaorPerl.
PHPisalsoverypowerful.Ifyoueverdoubtitspower,justlookcarefullyatthelinkinyourbrowsernexttimeyoudecidetologontoFacebook.YouwillnoticethatthelargestsocialnetworkingsiteontheplanetispoweredbyPHP!EvenWikipedia(Thatsitewhichtellsyoueverythingyouneedtoknow)ispoweredbyPHP.ThatisthepowerthatisbehindPHP,anditmakesitagoodalternativetoitscompetitorssuchasMicrosoft’sActiveServerPages(ASP).
Italsohasanactivecommunitythatcanreallyhelpyouinabindandalwaysactive.
Accordingtothehttp://www.w3schools.comPHPpage;thisiswhatPHPwillallowyoutodo:
PHPcangeneratedynamicpagecontent
PHPcancreate,open,read,write,delete,andclosefilesontheserver
PHPcancollectformdata
PHPcansendandreceivecookies
PHPcanadd,delete,modifydatainyourdatabase(thatiswhyitisaperfectmatchforMySQL)
PHPcanbeusedtocontroluser-access
PHPcanencryptdata
AShortIntroductiontoMySQL
MySQLisapopularopensourcerelationaldatabasethatusesSQLasitsbase.Itenablesyoutostore,retrieveandmanipulatedata.Itisahighlyefficientandscalablesolutionthatisalsocosteffective.
Manywebbasedprograms(includingcomputerprograms)usedatabasestostoretheirinformation.Thingslikesocialapplicationsneedaplacetostoreuserinformation,pictures,posts,commentsetc.thatiswhereadatabaselikeMySQLcomesinhandyandmakesstoringandretrievinglargeamountsofinformationabreeze.
SQL,oftenpronouncedassequel,standsforStructuredQueryLanguage.ItissimplyalanguagedesignedformanagementofdatabydatabaseslikeMySQL.TheyuseSQLtosendandretrievedatausingspecialisedcommandsthatreallyaren’tallthathardtolearn.Andmostimportantly,forthisbook,youcanembedSQLintoprogramminglanguageslikePHP.
Also,MySQLisopensourceandisavailableforfreeandcanbechangedbymodifyingthesourcecode,ifparticularfeaturesdon’tsuityourfantacy.
WhatWeWillCoverinThisBook
ThisbookisseparatedintofourmainchaptersorhoursthathelpyougettotheheartofPHPandSQLandsendyouonyourwaytobeingamasterinnotime.
InthefirsthourwewillspendtimeinstallingthemuchneededwebserverpackagecalledXAMPP.Irecommendthatyoudownloadithere:
https://www.apachefriends.org/index.htmlbeforewestartthatchapter.Thiswillenableustorunexamplesthroughoutthisbook.ThenweshallpickatexteditorforourPHPcode.ThenwewilllookathowtorunPHPscriptsand,finally,weshallcoversomeofthebasicsofPHP,suchascomments,variables,constantsandoperators.
Theexamplesinthisbookcanbetypedoutor,tosavetime,copiedandthenpastedintoyourcodeeditororcommandlineinterface.
Inthesecondhour,weshallcontinuewithPHPandcoverconditionalstatements,Loops,Arraysandfunctions.Afterthischapter,youshouldconsideryourselfwellacquaintedwithPHPtotacklefurtheradvancedtopics.
Youcantakeabreakafterthispartandletitallsinkinandmakeanothercupofcoffee.
InthethirdhourwetackleMySQLanditscommands,butfirstwelearnhowtoaccessthecommandline.Thenwemoveontothecommandsthatletuscreateanddeletedatabases;create,alteranddeletetables;insert,select,updateanddeletedatainthetables.
Finally,inthefinalhour,weputPHPandMySQLtogetherandcreateasimplewebsitetoshowyouhowthesetwoworktogetherhandinhand.
Letusgettoit.Grabyourfirstcupofcoffee!
Chapter1-Hour1:InstallingandPHPBasics“Thewaytogetstartedistotakethefirststepwithdream-poweredoptimism.”-DebasishMridha
Thischapterwewillcover:
InstallingawebserverInstallingatexteditorStartingApachestorunPHPscriptsCreatingandrunningaPHPscriptPHPbasics(comment,variables,operators,constants,strings)
Bearwithmealittle.Iknowthatthefirstchapterofalmosteveryprogrammingbookpilesonthetheorytomakesureyouknowwhatyouaregettingyourselfinto.Iwon’tlie;eveninthisshortbook,westillhavetogothroughitalittle.JustalittlebitofittocoversomebasicsofPHP.Butthatisforlateronduringthehour.FornowyouneedtoinstalltheserverandchooseanappropriatetexteditortousewhenwritingPHPcode!
InstallingaWebServer
YourfirstrealsteptoPHPmasteryhasledyouhere.Youcan’tjustrunPHPinabrowserlikeyoudowithHTML.TorunPHP,youaregoingtoneedaserverinstalledonyourlocalmachineinorderforthebrowsertoparsePHPscriptsandrunMySQLqueriestothedatabasetoreturnresults.Alternatively,youcanuseahostthatsupportsPHPandMySQLsothattheycanuploadittotheirserverandyoucantestanddeployyourdreamsiterightthere.ButI’mguessingyoureallywanttotestitlocallyandquickly.So,wewillinstallalocalserverthatmakesyourveryowncomputerbecomeatestserver.
TherearemanyserversyoucaninstallonyourlocalmachinesuchasXAMP,WAMP(forwindows),andMAMPforMacOSX,etc.,butthisbookcoversXAMP.ItisafreeopensourcecrossplatformwebserverpackageavailableforWindows,MacandLinux.
Gotothiswebsite
https://www.apachefriends.org/index.html
anddownloadthelatestversionofXAMPforwindows(thesamestepscanbeeasilytranslatedtoMacOSXorLinux).Oncethedownloadisfinished,locatethefileonyourlocalmachineanddouble-clickittoinstallit.
Simple!NowPHPandMySQLarereadyforuse.
NOTE:Ifyouhaveanantivirusrunningatthistime,itmayinterferewiththeprocess.Youmightwanttoswitchitoffuntiltheserverisdoneinstallingtoavoidanypotentialproblems.
InstallingaTextEditor
Now,youwillneedatexteditortowritesomebeautifulPHP.Ideally,anytexteditorwoulddo,eventhedefaultnotepadonwindowsorterminalforMacOSXcanbeusedwhenwritingPHP.Wewillusenotepad++becauseithassomeniftyfeatureswhichcancontributetowardswritingcleanandefficientcodeinafastway,suchassyntaxhighlightingandautocomplete.
Plusit’sfree!
ThistexteditorswillsaveyoutimeandaworldofpainbyjustdownloadingithereInstallingaTextEditorandinstallingit.Justrememberthatanytextwilldo.Soevenifyoudon’thavenotepad++,youcanusewhateveryoulike.
StartingApachetorunPHPscripts
NowthatyouhaveinstalledXAMPP,youneedtostarttheapachewebserviceinorderforthebrowsertobeabletorunPHPscripts.Todothis,openuptheControlPanelofXAMPPbydoubleclickingonitsicon.Bydefault,itshouldstartApacheautomatically,butyoucanstartitmanuallybyclicking“Start”asinthepicturebelow:
NOTE:SomeotherapplicationsinstalledonyourcomputercancauseApachenottostartbecausetheyareusingthesameportApacheisconfiguredtoe.g.Skype.Ifthatisthecase,juststopthoseservicesandstartApacheagain.
CreatingYourFirstPHPScript
Thispartisfairlyeasytodo.Allyouhavetodoisfollowthesesteps:
Step1-CreatethePHPfile
Openupyourtexteditorandcreatearegulartextfileandplacethefollowingcodeintoit:
<!DOCTYPEhtml><html><body>
<?phpecho“MyfirstPHPscript!”;?>
</body></html>
ThefilestilllookslikeyourbasicHTMLfileexceptthatyouembedPHPcodebetweentags<?phpand?>.Theechostatementjustoutputseverythingthatcomesafterittothescreen.Inourcase,thiswillbe“MyfirstPHPscript!”.Weshallseethisinactioninamoment.
AndallyouhavetorememberisthateveryPHPstatementendswithasemicolon(Exceptforcomments.Wewilllookatthoselaterinthehour).
Savethefileas“example.php”.
Step2-PlaceitintheRootDirectoryofXAMPP
Grabthefile“example.php”thatyoujustcreatedandplaceitintherootdirectoryofyourserverinthefoldernamed“htdocs”,andWhalla!Youarereadytorunitinyourbrowser.
TIP:Tofindtherootdirectory,youcanlookforitonyourlocalmachineoryoucouldjustopenuptheXAMPPControlPanelandclickthe“Explorer”button,asshowninthepicturebelow,tobringuptherootfolderandthenlocatethehtdocsfolderandplacethefileinthere:
NOTE:ThefoldertoplaceyourPHPfileswillbedifferentwitheachserver.Forexample;youplacetheminthefoldernamedwwwifyouareusingWAMP.
Step3-RunItintheBrowserOpenupyourbrowser(GoogleChromeorFirefoxarerecommended)andtypethefollowing:
http://localhost/example.php
PressEnterandyoushouldseethefollowingwindowbelow:
Thereyougo!Ifyoufollowthosesteps,youshouldbeabletorunallotherscriptscreatedinthischapter.
PHPBasics
Comments
Wanttoleavemessagesforyourfutureselforothermembersofyourteam?Thencommentssaveyouthetroubleofhavingtorememberyourtrainofthoughtandmakeforanexcellentwaytodocumentwhatyourthoughtswereatthetime.Theycanalsobeusedtoexcludecertainpiecesofcodealltogether.
//Thisisasinglelinecomment
#Thisisanothersinglelinecomment
/*Thisisacommentblock.Everythinginherewillbeignoredandcanspanmultiplelines.*/
Variables
Tobuildyourdreamwebsite,youwillneeddataandawaytostorethisdata.Itcanbeaname,anumber,adateorapicture.PHPoffersawayforyoutostoretheminmemorybyusingavariable.
EachvariableinPHPisprecededbythe$signfollowedbythevariablenamewithoutanyspacesinbetweenthesignandvariablename:
$myInt=10;
Letusseesomeofthisinactionwiththefollowingcode:
<!DOCTYPEhtml><html><body><?php$txt=“MysecondPHPscript!”;echo$txt;?></body></html>
Ifyourunthisscriptinthebrowser,itshouldoutputthefollowing:
“MysecondPHPscript!”;
Fewmorethingstorememberaboutvariables:
Theyarecasesensitive.Thismeans$nameand$naMearetwodifferentvariablesTheymustalwaysstartwithaletterorunderscoreTheycannotstartwithnumbersTheycanonlycontainalphanumericvalues
PHPisalooselytypelanguageandthereforeyoudon’tneedtodefinethedatatypesforvariables.PHPwillautomaticallyconvertthevariabletothecorrectdatatypedependingonthevalueassignedtoit.
Hereisalistofthecommondatatypesyouwillworkwith:
Integer–WholenumbersFloat–DecimalnumbersString–StringorcharactersBoolean–trueorfalseArray–MultipleitemsObject–AnObjectdefinedbyaclass
Youcanachievethesameresultastheexampleabovebyusingvariables:<!DOCTYPEhtml><html><body><?php$txt=“third”;echo“My”.$txt.”PHPscript!”;?></body></html>
Inthisexamplewearejoiningtwostringstogetherusingtheperiod(.)asitisusedtoconcatenatetwostringstogetherandoutputtingtheconcatenatedstringtothescreen.
Constants
Constantsarelikevariablesexceptthattheirvaluescannotbechangedorundefined.
Whendefineaconstantweusedefine()methodfollowedbyparametersintheparenthesisthatgiveitanameandavalue.Thefollowingexampleshowshowtodefineaconstant:
<?phpdefine(“MESSAGE”,“HappyLearning!”);//functionthatdefinesaconstantechoMESSAGE;?>Output:
HappyLearning!
Unlikevariables,youcanactuallyspecifywhetheryouwanttheconstanttobecase-insensitiveornotbyaddingonemoreparameter,thattakesaBoolean,afterthevalueisdefined(defaultisfalse):
<?phpdefine(“MESSAGE”,“HappyLearning!”,true,);echomessage;?>
Somerulestorememberaboutconstants:
Theymuststartwithaletterandanunderscore(theydon’tneedtostartwiththe$sign)Theyglobalacrosstheentirescriptautomatically
Operators
PHPusesoperatorstoperformvariousoperationsofvariablesandvalues.WeshallnowlookattheoperatorsusedbyPHPingroups.
ArithmeticOperators
Theseareoperatorsthatperformmathematicaloperationsonvaluesandreturncalculatedresults:
EXAMPLE OPERATOR RESULT
$x+$y Addition Sumof$xand$y
$x-$y Subtraction Thedifferencebetween$xand$y
$x*$y Multiplication TheProductof$xand$y
$x/$y Division Thedividendof$xand$y
$x/$y Modulus Theremainderof$xdividedby$y
$x**$y Exponent Resultof$xto$y’thpower(NewtoPHP5.6)
AssignmentOperators
Theseoperatorsareusedtosetvaluestovariables:
ASSIGNMENT SAMEAS:
DESCRIPTION
$x=$y $x=$y Getsthevalueof$yandsetsitto$x
$x+=$y $x=$x+$y Getsthesumof$xand$yandsetstheresultinto$x
$x-=$y $x=$x-$y Getsthedifferenceof$xand$yandsetstheresultinto$x
$x*=$y $x=$x*$y Getstheproductof$xand$yandsetstheresultinto$x
$x/=$y $x=$x/$y Getsthedividendof$xand$yandsetstheresultinto$x
$x%=$y $x=$x%$y Getstheremainderof$xdividedby$yandsetstheresultinto$x
ComparisonOperators
ComparisonoperatorsinPHPareusedtocomparetwovalues:
EXAMPLE NAME RESULT
$x==$y Equal Returnstrueifboth$xand$yareequal
$x===$y Identical Returnstrueifboth$xand$yareequal,andhavethesamedatatype
$x!=$y Notequal Returnstrueifboth$xand$yarenotequal
$x<>$y Notequal Returnstrueifboth$xand$yarenotequal
$x!==$y Notidentical Returnstrueifboth$xand$yarenotequal,oriftheydon’thavethesamedatatype
$x>$y Greaterthan Returnstrueif$xisgreaterthan$y
$x<$y LessThan Returnstrueif$xislessthan$y
$x>=$y Greaterthanorequalto
Returnstrueif$xisgreaterthanorequalto$y
$x<=$y LessThanorequalto
Returnstrueif$xislessthanorequal$y
LogicalOperators
Logicaloperatorsarewhatweusetocombineconditionalstatements(whichwewillcoverinthenexthour)inordertogetatrueorfalseresult:
EXAMPLE NAME RESULT
$x&&$y And Returnstrueifboth$xand$yaretrue
$x||$y Or Returnstrueeither$xor$yaretrue
!$x Not Returnstrueif$xisnottrue
$xand$y And Returnstrueifboth$xand$yaretrue
$xor$y Or Returnstrueeither$xor$yaretrue
$xxor$y Xor Returnstrueif$xislessthan$y
Increment/Decrement(Ternary)Operators
Theseoperators,alsoknownasternaryoperators,increase/decreaseavariable’svaluebyone
EXAMPLE NAME RESULT
++$x Pre-increment Addsonetox,thenreturns$x
$x++ Post-increment Returns$x,thenaddsoneto$x
—$x Pre-decrement subtractsonefromx,thenreturns$x
$x— Post-decrement Returns$x,thensubtractsonefrom$x
StringOperator
Theseareoperatorsthatarespeciallydesignedforstrings:
EXAMPLE NAME RESULT
$str1.$str2 Concatenation Returnstheconcatenationof$str1and$str2
$x$str1.=$str2 Concatenationassignment
Append$str2to$str1
ArrayOperators
Theseareoperatorsthatusedtocomparearrays(whichwewilldiscussinthenexthour):
EXAMPLE OPERATOR RESULT
$x+$y Union Unionof$xand$y
$x==$y Equality If$xand$yhavethesamevalue/keypairs,theresultistrue
$x===$y Identity If$xand$yhavethesamevalue/keypairsinthesameorderandofthesamedatatype,theresultistrue
$x!=$y Inequality Ifthevalueof$xisnotequaltothevalueof$y,itreturnstrue
$x<>$y Inequality Ifthevalueof$xisnotequaltothevalueof$y,itreturnstrue
$x!==$y Non-indentity If$xand$yarenotidentical,itreturnstrue
Summary
Sofar,wehavecoveredalotofthingsyouneedtoknowinordertogetgoingandseePHPinaction.WehaveinstalledawebserverpackagecalledXAMPPthatcomeswiththeAPACHEwebservicethatallowsustorunPHPscriptsinourbrowser.YoushouldnowbeveryknowledgeableenoughtocreateandrunPHPscriptsandhaveagoodideaonhowtooutputinformationtothescreen.WehavealsocoveredsomeofthebasicsofPHPlikevariablesandconstants,andlookedatsomeofitsoperators;someofthemwillbeusefulinthenexthour.
Solet’smoveon!
Chapter2-Hour2:MorePHPBasics
“Talkischeap.Showmethecode”–ThomasC.Gale
Inthischapterwewillcover:
ConditionalStatementsLoopsArraysFunctions
ThisisthepartwherewedivealittledeeperintothebasicsofPHPandgettodoalotofcoolstuff.Youaredonewithsaladportionofthebasics,thisisthemeatsection.
ConditionalStatementsConditionalstatementsallowforabitofdecisionmakingincode.Theyperformdifferentactionsdependingonthewhethertheconditiontheprogrammerspecifiedhasbeenevaluatedastrueorfalse.
HereisalistofconditionalstatementsusedinPHP:
IfstatementsIf…elsestatementsIf…elseif…elsestatementSwitchstatements
Letustakealookateachoneindetail.
TheifStatementAnifstatementevaluatesanexpressionandexecutesablockofcodeiftheexpressionevaluatedtotrue.Ifitevaluatedtofalse,thecodeblockisignored.
Thefollowingexamplewilloutput“5islessthan10!”iftheconditionistrue,otherwise,thecodeblockwillbeignored:
<?php
$x=5;
if($x<10){
echo“$xislessthan10!”;
}
?>
Output:
5islessthan10!
Theif…elseifStatementTheif…elseifstatementexecutesacodeifblockiftheexpressionevaluatedastrueandanothercodeifthatexpressionisevaluatedasfalse.
Letusalterthepreviousexampleabit.Thefollowingcodewilloutput“50isgreaterthan20!”whichisonthesecondcodeblockbecauseitsatisfiesthesecondcondition.Thevalueassignedto$xis50anditwillreturnfalseonthefirstcondition:
<?php
$x=50;
if($x<10){
echo“$xislessthan10!”;
}elseif($x>20){
echo“$xisgreaterthan20!”;
}
?>
Output:
50isgreaterthan20!
Theif…elseif…elseStatement
Sameastheif…elseifstatement.Thedifferenceisthatwhenallotherconditionsfail,thelastcodeblockisexecuted.
InTheexamplebelowwilloutput“I5isbetween10and20!”because$xis15.Itneedstobelessthan10tosatisfythefirstcondition,andgreaterthan20tosatisfythesecondcondition,otherwise,itisbetween10and20:
<?php
$x=15;
if($x<10){
echo“$xislessthan10!”;
}elseif($x>20){
echo“$xisgreaterthan20!”;
}else{
echo“$xisbetween10and20!”;
}
?>
Output:
I5isbetween10and20!
SwitchStatement
Aswitchstatementjustmatchesthevalueofanexpressionwithcasesinthestructure.Ifamatchisfound,thecodeblockassociatedwiththatcaseisexecuted.Whennomatchisfound,thedefaultstatementisused.Thebreakstatementiswhatpreventsthecodefromjumpingintothenextcaseautomatically.
Intheexamplebelowthevalueof$lunchwillbecheckedagainstallthecasestoseeifanyofthemmatch.Inthiscase,theoutputwillbe“Burgersareyummy!”sincethatisthecorrespondingcase.
<?php
$lunch=“burger”;
switch($lunch){
case“cereal”:
echo“Cereal?Youhadbreakfastforlunch!”;
break;
case“salad”:
echo“Saladmakesforahealthylunch!”;
break;
case“burger”:
echo“Burgersareyummy!”;
break;
default:
echo“lookslikeyouskippedlunch.Thatisnotgood!”;
}
?>
Output:
Burgersareyummy!
Loops
HereisalistofloopingstatementsinPHP:
whiledo…whileforforeach
Weshallgointoeachoneindetail.
TheWhileLoop
Thewhileloopexecutesablockofcoderepeatedlyaslongasthespecifiedconditionremainstrue.
Thecodebelowshowsthevalue$xbeingifitislessthanorequalto5.Iftheconditionistrue,itgetsoutputtedtoscreenandthenincrementedagainuntiltheconditionreturnsfalse:
<?php
$x=1;
while($x<=5){
echo“Thevalueofxis:”.$x.“<br/>”;
$x++;
}
?>
Output:
Thevalueofxis:1Thevalueofxis:2Thevalueofxis:3Thevalueofxis:4Thevalueofxis:5
Do…WhileLoop
Executestheblockofcodeatleastoncethenloopsthroughituntilthespecifiedconditionbecomesfalse.
Theexamplebelowshowsthevalueof$xbeingoutputtedtothescreenthensubtractedbyoneatleastonce,thenitischeckedtoseeifitisgreaterthanzero.Ifitis,thenitrepeatstheprocessuntilitbecomeslessthanzero:
<?php
$x=5;
do{
echo“Thevalueofxis:”.$x.“<br/>”;
$x—;
}while($x>=0);
?>
Output:
Thevalueofxis:5Thevalueofxis:4Thevalueofxis:3Thevalueofxis:2Thevalueofxis:1Thevalueofxis:0
ForLoop
Loopsthroughacodeblockaspecifiednumberoftimes.
Therearethreethingsneededinorderforthelooptowork.Andtheexamplebelowhasthemall:
1. Initialization–thisiswhereavariableisdeclaredtostarttheloopcounter.Thisis$x=1inourexample.Thismeanthatthe$xistheinitializeranditissettostartat1
2. Condition–Thisisthesecondpartoftheloopwherewecheckiftheloopcounterstillmatchesacondition.Whenitreturnsfalse,theloopstopsexecutionofthecodeblock.Ourconditionintheexamplebelowis$x<=5
3. Increment–Whentheloopends,thispartofthecodeisexecutedonceandthenthelooprepeats.Thisiswherewecandosomeoperationstotheloopcounter.Inourcaseweincreasethevalueof$xbyonewith$x++
<?php
for($x=1;$x<=5;$x++){
echo“Thevalueofxis:”.$x.“<br/>”;
}
?>
Output:
Thevalueofxis:1Thevalueofxis:2Thevalueofxis:3Thevalueofxis:4Thevalueofxis:5
ForeachLoopAloopthatgoesthrougheachelementfoundinanarray.Itexecutesablockofcodewitheachelementfoundinthearrayuntilitrunsout.
Thecodebelowloopsthroughalltheelementsofanarraythenoutputsthevalueoftheelementtothescreen:
<?php
$foods=array(“cereal”,“salad”,“burgers”,“fries”);
foreach($foodsas$food){
echo“$food<br/>”;
}
?>
Functions
Afunctionisapieceofcodethatcanbeusedofoverandoverinaprogram.Afunctiontakesoneormoreinputscalledparameters(alsocalledarguments)anddoessomeoperationstothem.Afunctioncansometimesreturnavalueafteritisdoneprocessing.
Afewthingstorememberaboutfunctions:
Theyarenotcase-sensitiveTheyarenotexecutedautomaticallywhenthepageloadsuntiltheyarecalledbyacertainpieceofcodePHPhasmorethan1000builtinfunctionsthatcancatertoyourrequirements
CreatingaFunction
Creatingyourownfunctioniseasy;juststartwiththekeywordfunctionfollowedbythefunctionnameandparenthesis.Afterthatplaceyourcodebetweentwocurlybraces{and}calledtheopeningandclosingbraces,respectively.Nowyoucanusethefunctionasmanytimesasyouneedit.Thissavesyouthetroubleofhavingtore-typethecodeeverytime.
Thecodebelowdemonstratesafunctionthatoutputsamessagetothescreen
<?php
functionechoMessage(){
echo“Hello,IamaPHPfunction!”;
}
echoMessage();
?>
Output:
Hello,IamaPHPfunction!
ParametersforFunctions
Sometimesyoucanpassinformationtofunctionssothatoperationsaredoneonthem.Thisinformationisknownasparametersandisplacedintheparenthesis.Youcanaddmultipleparametersbyseparatingthemwithacoma.
Thebelowexampleshowsafunctionthatsubtractstwonumberssuppliedtofunctionasparameters:
<?php
functionsubFunction($num1,$num2){
$diff=$num1-$num2;
echo“Thedifferencebetween$num1and$num2is:”.$diff;
}
subFunction(5,6);
?>
Output:
Thedifferencebetween5and6is:-1
FunctionthatReturnaValue
Afunctioncannotonlyacceptinformation,buttheycanalsogiveitbackinformofareturnvalue.Justwritethereturnkeywordfollowedbythevalueorobjectyouwishthefunctiontoreturn.Thisstopsexecutionofthefunction.
Inthefollowingexampleweusethefunctiontoaddtonumbersandthenreturnthesum.Wethenassignthesumofnumberstothevariable$return_valthenoutputthattothescreen.
<?php
functionaddFunction($num1,$num2){
$sum=$num1+$num2;
return$sum;
}
$return_val=addFunction(20,15);
echo“Thevaluereturnedbythefunctionis:”.$return_val;
?>
Output:
Thevaluereturnedbythisfunctionis:5
DefaultValuesforParameters
Incaseafunctionthatneedsparametersiscalledwithoutanyparameters,wecanspecifyadefaultvalueforthatparameterinstead.
Intheexamplebelow,wecallafunctionthreetimes.Wedon’tpassavalueinthefirstfunctioncalljustsowedemonstratethedifference:
<?php
functionPrintName($name=“Jack”){
echo“Hi,mynameis$name<br/>”;
}
PrintName();//willusethedefaultvalueofJack
PrintName(“Jill”);
PrintName(“Adam”);
?>
Output:
Hi,mynameisJackHi,mynameisJillHi,mynameisAdam
Arrays
Anarrayisdatastructurethatcanstoremultiplehomogenousvaluesinasinglevariable.Eachvalueisassociatedwithakeythatisusedtoidentifyitandreturnit.
NumericArray
Thesearearraysthatusenumbersastheirindex.Theindexbeginsatzerobydefault.
Theyaretwowaystocreatenumericarrays:
1. Thiswayautomaticallyassignstheindex:
$dairy=array(“yoghurt”,“icecream”,“cheesecake”);
2. Thiswayassignstheindexmanually:
$dairy[0]=“yoghurt”
$dairy[1]=“icecream”
$dairy[2]=“cheesecake”
Theexamplebelowshowshowtogetvaluesfromanumericarrayusingindices:
<?php
$dairy=array(“yoghurt”,“icecream”,“cheesecake”);
//accessingvaluesbytheirindex
echo“Itoeat”.$dairy[0].“,”.$dairy[1].“and”.$dairy[2].“!”;
$arrayCount=count($dairy);//PHPbuiltinfunctionthatreturnsthenumberofelementsinthearray
//loopingthroughanumericarrayusingaforloop
for($i=0;$i<$arrayCount;$i++){
echo$dairy[$i].“<br/>”;
}
?>
Output:
Itoeatyoghurt,icecreamandcheesecake!yoghurticecreamcheesecake
AssociativeArrayUsestringsastheirindexthatmakeforastrongassociationbetweenkeyandvalue.
Theyaretwowaystocreateassociativearrays.Wewilldemonstratebyusingpricesoffantasysuits:
1. Firstsmethod:
$suit_prices=array(“batman”=>4000,“arrow”=>1500,“superman”=>0);
2. Secondmethod:
$suit_prices[“batman”]=>4000;
$suit_prices[“arrow”]=>1500;
$suit_prices[“superman”]=>0;
Note:Whenoutputtingvaluesofassociativearrays,don’tputtheassociativearrayinsidedoublequotes,otherwise,thevalueswon’tgetoutputted.
Theexamplebelowdemonstrateshowtoaccessvalueforanassociativearray:
<?php
$suit_prices=array(“batman”=>4000,“arrow”=>1500,“superman”=>0);
echo“TheBatsuitcosts:”.$suit_prices[‘batman’].“<br/>”;
echo“TheGreenArrowsuitcosts:”.$suit_prices[‘arrow’].“<br/>”;
echo“TheSupermanisfree.Itsuitcosts:”.$suit_prices[‘superman’].“<br/>”;
?>
Output:
TheBatsuitcosts:4000TheGreenArrowsuitcosts:1500TheSupermansuitisfree.Itcosts:0
TheothertypeofarrayworthmentioningisamultidimensionalarrayThesearearraysthatcontainotherarrays.Buttheyareanadvancedtopicthatyoucanlookintofurther.
Summary
Congratulations!YouarenowacquaintedwiththebasicsofPHP.BynowyoushouldbeableseethepowerPHPoffersyou.Inthischapterwediscussedconditionalstatementsthatallowthecodeyouwritetomakedecisionsbasedonspecifiedconditions.Thenwelookedatloopsthatexecuteablockofcodeuntilaconditionspecifiedreturnfalseoruntiltheyrunoutelements.Nextwediscussedhowtocallcodemultipletimesinaprogrambyputtingtheminafunction,andalsohowtopasstheminformationandhavethemreturnvaluestous.Finally,welookedintonumericandassociativearrays.Wecreatedthemandreturnedvaluesbyeitheraccessingthemdirectlyorloopingthroughthem.
NowyouarereadytotakeabreatherfromPHPandmakeanothercupofcoffee.Thisonlygetsmoreinteresting!
Chapter3-Hour3:MySQLBasics
“TellmeandIforget,teachmeandImayremember,involvemeandIlearn.”-BenjaminFranklin
Inthischapterwewillcover:
StartMySQLCreateandDeletingDatabasesCreating,Reading,UpdatingandDeletingTables(CRUD)
NowthatwehavelookedintoPHP,let’slookatwhatenablesthePHPtopopulatewebpageswithcontent.ThatwouldbeadatabasesuchasMySQL.WewilllookatmostofthethingsyouneedtoknowinordertoconsideryourselfamasterofthebasicsofMySQLanddowhatyouneedtoforthatnextstepinachievingyourdreams.
Thiswillbeabreezeaswewilllearnhowtodosomereallycoolthingswithdatabases.
Belowisapictureofthetablewewillcreateandbeworkingwithinthedatabase.Wewilljustbeaddingalbumstoamusicdatabase.Youhavethetablenameattheverytopandthefieldsorcolumnsbelowthetablename.
Albums
AlbumIDAlbumNameAlbumArtistAlbumTypeNumberOfTracksDateReleased
StartingMySQLClient
WhatwearetobedoingforthishourisenteringMySQLcommandsusingthecommand-lineoftheMySQLclientthatcomeswithXAMPPbyopeningupWindowscommandpromptandnavigatingtotherootfolderofwhereXAMPPisinstalled.
Whenyouopencommandprompt,enterthebelowcommandtonavigatetothe“C”drive,AssumingXAMPPisinstalledthere,andthenpressenterafterthat:
cd\Now,navigatetowheretheexecutablefortheclientisinstalledtostartit.Thatisinxampp->mysql->binbyenteringthefollowingcommandandthenpressingenter:
cdxampp\mysql\bin
Oncethere,typethefollowingcommand:
mysql-uyour_username-p
Replace“your_username”withyouractualusername.Thisis“root”bydefault.Youwillthenbeaskedtoenteryourpassword.Onceyoudothat,pressenter.Thepasswordisblankbydefaultandyoureallyoughttochangethatforsecurityreasons.Butthatisbeyondthescopeofthisbook.
Ifyounoticewithcommand-lineisbeingpromptedbysomethingcalledMariaDB.Don’tgetconfusedbecauseitisjustacommunity-developedforkoftheMySQLrelationaldatabasemanagementsystem.AlargenumberofSQLcommandswillstillworkandunlikethepreviousMySQLprompt,itletsyouknownwhichdatabaseyouhaveselected.
Nowwearereadytogetstarted!
TIP:Alternativelyyoucanusethephpmyadmininterfacetocreatedatabasesandtablewithjustafewclicks.YoucanalsotypeSQLcommandstherebutsincewewanttogethard-coreasfastaspossible,wewon’tbedoingthat.Besides,nothinginthishourhasbeenhardsofar,Ihope.
CreatingandDeletingaDatabase
Let’sstartbycreatingadatabasebyenteringthefollowingcommand:
CREATEDATABASEmusic;
Alwaysrememberthis:
Fromhereonwards,allstatementsandcommandstypedshouldendwithsemicolonor/g.Otherwisetheclientwillthinkyouarestilltypingthecommandanditwon’texecuteAlthoughnotrequired,becausecommandlineisnotcasesensitive,MySQLcommandsaretypedinuppercaseletterstodistinguishbetweencommandsandthingslikedatabasenames,tablenames,columnsandrows
Todeletethedatabaseitisaseasyasentering:
DROPdatabase_name;
Where“database_name”isthenameofthedatabaseyouwanttodrop.
Nowthatwehavecreatedourdatabase,weneedtoselectitinordertocreatetables.Wetypethefollowingintoyoucommandlinetoselectthedatabasewejustcreated,andthenpressenter:USEmusic;
WARNING:Don’tforgettoselectthedatabaseotherwiseyouwillgeterrorswhenyoutrytocreatetablesetc.
NOTE:thecommand-linepromptwillletyouknowwhichdatabaseyouhaveselected.Itshouldlooksomethinglikethis“MariaDB[music]>”.
Creating,AlteringandDeletingTables
Nowthatwehaveselectedoutdatabase,let’screatesometables.Thefirsttablewewillcreateisaboutinformationontheartist.
Itisgoodpractice(andheadachesaving)tofirstcheckifanytableswiththesamenameexistsbecauseyoucan’tcreatetwotableswiththesamenameinthesamedatabase.Ifoneisfound,itisdeletedalongwithitsdata.So,becarefulwiththiscommandespeciallyifthetableisrelatedtoothertables.
CreatingTables
Wecreatethetableasfollows:
CREATETABLEAlbum
(AlbumIDsmallintunsignedNOTNULLauto_incrementPRIMARYKEY,AlbumNamevarchar(255)NOTNULL,AlbumArtistvarchar(80)NOTNULL,AlbumTypeENUM(‘A’,‘E’,‘M’)NOTNULL,numTracksvarchar(3)NOTNULL,DateReleasedDATENOTNULL);
TIP:Whentypinglargecommandsitiseasytomessup.Especiallywhenusingthecommandline.Ifthishappensjustpresstheuparrowonyourkeyboardtobringuppreviouscommandsandusetheleftandrightarrowstonavigatetowhereyoumessedupandfix.
Toseethelistoftablesinyoudatabase,enterthefollowingpieceofcode:SHOWtables;
Youseethefollowingoutput:+–––––—+|Tables_in_music|+–––––—+|album|+–––––—+
WhenyoupressEnter,thefollowingtablewillbeaddedtothemusicdatabase.Letusbreakdownwhatishappening:
1. CreatingtheAlbumTable
CREATETABLEArtists()createsanewtableandthelinesinsidetheparenthesisdefinethetable’sstructure.
2. GivingEachAlbumaUniqueID
Thefield(orcolumn)AlbumsIDhasthefollowingproperties:
smallintunsigned(unsignedsmallinteger)–thismeanswecanstoreartistsintherange32,278to–32,767.Wewilllookatthecommondatatypesthatyouwillbeworkingwithlateroninthechapter.NOTNULL–thismeansthefieldcannotbeleftblankwhencreatingarecord.auto_increment–thisjustmeansthatyoudon’thavetoenteranythinginthefield.Whenarecordiscreated,itwillbeassignedanewvaluebyMySQL.PRIMARYKEY-EachtablecanonlyhaveonePrimaryKey.Itisusedtouniquelyidentifyarecord/rowinadatabaseand,oncecreated,itcanneverbechanged.Thismakesitquickertofind(attheexpenseofsomestoragespace).
3. AddingtheAlbumNameField
Nextwecreateafieldtostorethenameofthealbum.Thedatatypevarcharstandsforvariablenumberofcharacterandstoresastringofupto225characters.
4. AddingtheAlbumArtistField
Thisfieldalsostoresavariablenumberofcharactersanditsstringislimitedtoonly80characters.
5. AddingtheAlbumTypeEnumeratedTypeField
TheenumeratedtypeENUMisastringobjectthathassetofvaluesthatareallowed.Inourcase,theallowedvaluesare‘L’forLongPlay(LP),‘E’forExtendedPlay(EP)and‘M’foramixtape.
6. AddingthenumTracksField
Ifthisseemswrongtoyou,thenyouhavebeenpayingattention!Thisfieldisusedtostorethenumberoftracksthealbumhasandshouldbeanumerictypeandnotastringtype.Thiswasdoneintentionallytodemonstratehowtochangethedatatypeandnameofafield/columnlaterofinthechapter.
7. AddingDateReleasedField
Thelastlinecreatedstoresthedatethealbumwasreleased.Thedatedatatypeisusedtostoredatevalues.
Letuslookatsomeofthecommondatatypesthatyouwillbeusing:
NumericTypes1. INT:wholenumber2^31to-2^31–12. FLOAT:Decimalspaces1.1E38to-1.1E373. Double:Decimalspaces1.7E308to-1.7E307StringTypes1. CHAR:fixedlengthcharacterstring2. VARCHAR:Characterstringwithavariablelength3. ENUM:Acharacterstringthathasalimitednumberoftotalvalueswhichyou
mustdefineDateandTime1. DATE:YYYY:MM:DD2. TIME:HH:MM:SS3. DATETIME:YYYY-MM-DDHH:MM:SS4. YEAR:YYYY
AlteringTables
Sometimeyoucanmakeamistakeormayjustwishtochangesthingsinyourtable.Luckily,youcandosowithMySQLbyalteringthetableusingMySQLstatements.Wewilllookatchangingtableandcolumnnames,andchangingdatatypes.
Firstweneedtolookatthetablewejustcreatedbythetypingfollowingcommandtodescribeourtable.Weshouldbeabletoseeitsstructureinthecommandline:
DESCRIBEAlbum;
Youshouldseethefollowingoutput:+––––—+–––––––-+––+–—+–––+–––––-+|Field|Type|Null|Key|Default|Extra|+––––—+–––––––-+––+–—+–––+–––––-+|AlbumID|smallint(5)unsigned|NO|PRI|NULL|auto_increment||AlbumName|varchar(255)|NO||NULL|||AlbumArtist|varchar(80)|NO||NULL|||AlbumType|enum(‘A’,‘E’,‘M’)|NO||NULL|||numTracks|varchar(3)|NO||NULL|||DateReleased|date|NO||NULL||+––––—+–––––––-+––+–—+–––+–––––-+
Lookslikewecanindeedchangeafewthings:
1. ChangingtheTableName
Seemsthesingularform“Album”doesn’tmakemuchsenseasatableisusedtostoremultiplerecords.WeshouldusethepluralformandchangeitfromAlbumtoAlbums.Justsoitmakesmoresense.
Hereishowwechangethetablename:RENAMETABLEAlbumtoAlbums;
Ifweentertheshowtablescommandweshouldseethetablenamehaschanged:+–––––—+
|Tables_in_music|+–––––—+|albums|+–––––—+
2. ChangingTheDataTypeofnumTracks
ThefieldnumTracksshouldnotbeastringtypebutnumeric.Thefollowingcodeshouldchangeitsdatatypetotheappropriateone:
ALTERTABLEAlbumsMODIFYCOLUMNnumTrackssmallint(2)NOTNULL;
3. ChangingtheColumnNamefornumTracks
ItseemswearestillnotdonewiththefieldnumTracks.WeneedtochangeittomakeitalittlemorereadablebychangingitfromnumTrackstoNumberOfTracks.
ALTERTABLEAlbumsCHANGEnumTracksNumberOfTrackssmallint(2)NOTNULL;
NOTE:westillhavetodefinethedatatypeevenwhenchangingthenameofthecolumn
Withthefollowingchanges,whenweenterthestatementtodescribethetable,weshouldseethefollowing:
+–––––-+–––––––-+––+–—+–––+–––––-+
|Field|Type|Null|Key|Default|Extra|
+–––––-+–––––––-+––+–—+–––+–––––-+
|AlbumID|smallint(5)unsigned|NO|PRI|NULL|auto_increment|
|AlbumName|varchar(255)|NO||NULL||
|AlbumArtist|varchar(80)|NO||NULL|||AlbumType|enum(‘A’,‘E’,‘M’)|NO||NULL|||NumberOfTracks|smallint(2)|NO||NULL|||DateReleased|date|NO||NULL||+–––––-+–––––––-+––+–—+–––+–––––-+
Thatlooksmuchbetter!
DeletingTablesThecodebelowcanbeusedtodeleteatableandallitsdatafromthedatabase:DROPTABLEtable_name;
Wheretable_nameisthenameofthetableyouwishtodelete.
InsertingRecordsintoaTableWeusetheINSERTINTOstatementinordertoinsertnewrecordsinatable.INSERTINTOAlbumsVALUES
(NULL,“RushofBloodtotheHead”,“Coldplays”,‘A’,12,“2002-08-02”),
(NULL,“DirtyGold”,“AngelHaze”,‘A’,16,“2013-12-30”),
(NULL,“BacktotheWoods”,“AngelHaze”,‘M’,13,“15-09-15”),
(NULL,“Parachutes”,“Coldplay”,‘A’,10,“1999-07-10”),
(NULL,“1989(DeluxEdition)”,“TaylorSwift”,‘A’,15,“2014-10-27”),
(NULL,“ProspektsMarch”,“Coldplay”,‘E’,8,“2008-09-21”),
(NULL,“RandomAccessMemories”,“DaftPunk”,‘A’,14,“2013-05-13”),
(NULL,“X&Y”,“Coldplay”,‘A’,13,“2005-06-01”);
SeemswelikeColdplayabittoomuch.Whodoesn’t?
TheSELECTStatement
TheSELECTstatementallowsyoutoretrievedatafromadatabase.ThefollowingexampledemonstrateshowtouseSELECTstatementtoretrievealltherecordsfromtheAlbumstable:SELECT*FROMAlbums;
Theoutputshouldbesomethinglikethis:+–––+–––––––––+––––—+–––—+–––––-+––––—+
|AlbumID|AlbumName|AlbumArtist|AlbumType|NumberOfTracks|DateReleased|
+–––+–––––––––+––––—+–––—+–––––-+––––—+
|1|RushofBloodtotheHead|Coldplays|A|12|2002-08-02|
|2|DirtyGold|AngelHaze|A|16|2013-12-30|
|3|BacktotheWoods|AngelHaze|M|13|2015-09-15|
|4|Parachutes|Coldplay|A|10|1999-07-10|
|5|1989(DeluxEdition)|TaylorSwift|A|15|2014-10-27|
|6|ProspektsMarch|Coldplay|E|8|2008-09-21|
|7|RandomAccessMemories|DaftPunk|A|14|2013-05-13|
|8|X&Y|Coldplay|A|13|2005-06-01|
+–––+–––––––––+––––—+–––—+–––––-+––––—+
ToselectspecificcolumnsweusethefollowingSELECTstatement:
SELECTAlbumName,AlbumArtist,DateReleased,NumberOfTracks
FROMAlbums;
Theoutputshouldbe:
+–––––––––+––––—+––––—+–––––-+
|AlbumName|AlbumArtist|DateReleased|NumberOfTracks|
+–––––––––+––––—+––––—+–––––-+
|RushofBloodtotheHead|Coldplays|2002-08-02|12|
|DirtyGold|AngelHaze|2013-12-30|16|
|BacktotheWoods|AngelHaze|2015-09-15|13|
|Parachutes|Coldplay|1999-07-10|10|
|1989(DeluxEdition)|TaylorSwift|2014-10-27|15|
|ProspektsMarch|Coldplay|2008-09-21|8|
|RandomAccessMemories|DaftPunk|2013-05-13|14|
|X&Y|Coldplay|2005-06-01|13|
+–––––––––+––––—+––––—+–––––-+
TheWHEREClause
Sometimesyouwillneedtofilteroutrecordsandselectonlythoserecordsthatfulfilacertaincriterion.ThisiswheretheWHEREclausecomesintoplayasthefollowingexampledemonstrates:
SELECTAlbumName,AlbumArtist,DateReleased,NumberOfTracks
FROMAlbums
WHEREAlbumArtist=‘Coldplay’
Thisshouldoutput:
+–––––—+––––-+––––—+–––––-+
|AlbumName|AlbumArtist|DateReleased|NumberOfTracks|
+–––––—+––––-+––––—+–––––-+
|Parachutes|Coldplay|1999-07-10|10|
|ProspektsMarch|Coldplay|2008-09-21|8|
|X&Y|Coldplay|2005-06-01|13|
+–––––—+––––-+––––—+–––––-+
NOTE:Thisexamplewasdoneonatextfield,hence,thesinglequotesonthevaluewewanttocheckagainst.Youcancheckagainstnumericfieldstoo.Justremovethesinglequotesandmakesureyoutypeanumericvaluethatcorrespondstothenumericdatatypeofthatfield.
YoucanfurtherfilterouttherecordusingtheANDandORoperatorstonarrowdowntheresultsfurther:
TheANDoperatordisplaysrecordsthatmatchbothconditionsofthecriterion:SELECTAlbumName,AlbumArtist,AlbumType
FROMAlbums
WHEREAlbumArtist=‘Coldplay’ANDAlbumType=‘A’;
TheoutputshoulddisplayresultswheretheAlbumNameisColdplayandtheAlbumTypeis‘L’.Ifanyrecorddoesn’tmatchthatcriterion,itwillbeexcluded:
+––––+––––-+–––—+
|AlbumName|AlbumArtist|AlbumType|
+––––+––––-+–––—+
|Parachutes|Coldplay|A|
|X&Y|Coldplay|A|
+––––+––––-+–––—+
TheORoperatorisusedtoreturnrecordsthatmatcheitheroftheoneofthecriterionspecified.
SELECTAlbumName,AlbumArtist,AlbumType
FROMAlbums
WHEREAlbumType=‘E’ORAlbumType=‘M’;
Intheaboveexample,anyrecordthathaseitherAlbumTypeof‘E’orAlbumTypeof‘M’willbedisplayed.Therestwillbeexcluded.Theoutputshouldbeasfollows:
+––––––-+––––-+–––—+
|AlbumName|AlbumArtist|AlbumType|
+––––––-+––––-+–––—+
|BacktotheWoods|AngelHaze|M|
|ProspektsMarch|Coldplay|E|
+––––––-+––––-+–––—+
TheORDERBYKeyword
Inordertosorttheresult_set(thetablereturnedbyaSELECTstatement)byoneormorecolumns,weusetheORDERBYkeywordandspecifywhetheritshouldbeindescendingorascendingorder:
SELECTAlbumName,AlbumArtist
FROMAlbums
ORDERBYAlbumArtistASC;
NOTE:Bydefault,theyaresortedinascendingorder.ThismeansthatifweleaveouttheASCkeyword,itwouldnotmakeadifference.WecansortthemindescendingorderbyreplacingASCwithDESCintheaboveexample.
Thatshouldoutputrecordsinascendingorderbasedonthenameoftheartistofthealbum:
+–––––––––+––––—+
|AlbumName|AlbumArtist|
+–––––––––+––––—+
|DirtyGold|AngelHaze|
|BacktotheWoods|AngelHaze|
|Parachutes|Coldplay|
|ProspektsMarch|Coldplay|
|X&Y|Coldplay|
|RushofBloodtotheHead|Coldplays|
|RandomAccessMemories|DaftPunk|
|1989(DeluxEdition)|TaylorSwift|
+–––––––––+––––—+
TheUPDATEStatementLookingbackatthesomeoftherecordswehavedisplayedsofar,itseemswemadeamistakeandnamedColdplayasColdplaysinoneoftherecords.ThiscanbecorrectedbyupdatingthatrecordusingtheUPDATEstatement..
Ifweoutputtherecordnowwiththefollowingcode:
SELECTAlbumID,AlbumName,AlbumArtist
FROMAlbums;
Theoutputshouldbe:
+–––+–––––––––+––––—+
|AlbumID|AlbumName|AlbumArtist|
+–––+–––––––––+––––—+
|1|RushofBloodtotheHead|Coldplays|
|2|DirtyGold|AngelHaze|
|3|BacktotheWoods|AngelHaze|
|4|Parachutes|Coldplay|
|5|1989(DeluxEdition)|TaylorSwift|
|6|ProspektsMarch|Coldplay|
|7|RandomAccessMemories|DaftPunk|
|8|X&Y|Coldplay|
+–––+–––––––––+––––—+
Weupdatethatrecodelikethis:
UPDATEAlbums
SETAlbumArtist=‘Coldplay’
WHEREAlbumID=1;
Warning:Don’tomittheWHEREclauseoralltherecordsinthetablewillbeupdated.
Ifweoutputitnow,weshouldseetherecordhasbeenupdated:
+–––+–––––––––+––––—+
|AlbumID|AlbumName|AlbumArtist|
+–––+–––––––––+––––—+
|1|RushofBloodtotheHead|Coldplay|
|2|DirtyGold|AngelHaze|
|3|BacktotheWoods|AngelHaze|
|4|Parachutes|Coldplay|
|5|1989(DeluxEdition)|TaylorSwift|
|6|ProspektsMarch|Coldplay|
|7|RandomAccessMemories|DaftPunk|
|8|X&Y|Coldplay|
+–––+–––––––––+––––—+
DeletingRecordsinaTables
Todeleterecordsinatable,weusetheDELETEstatement.Thefollowingexampledeletestherecord/rowfromthetablewithanAlbumIDof1:
DELETEFROMAlbums
WHEREAlbumID=1;
Warning:Don’tomittheWHEREclauseoralltherecordsinthetablewillbedeleted.
Nowweoutputtherecordsinthetable.WewilllimitthenumberofcolumnstoonlyAlbumID,AlbumNameandAlbumArtist.TherecordwithanAlbumIDof1shouldbemissingfromtheresult_setbecauseithasbeendeleted.
+–––+––––––––+––––—+
|AlbumID|AlbumName|AlbumArtist|
+–––+––––––––+––––—+
|2|DirtyGold|AngelHaze|
|3|BacktotheWoods|AngelHaze|
|4|Parachutes|Coldplay|
|5|1989(DeluxEdition)|TaylorSwift|
|6|ProspektsMarch|Coldplay|
|7|RandomAccessMemories|DaftPunk|
|8|X&Y|Coldplay|
+–––+––––––––+––––—+
Ifyouwanttodeleteallrecordsinthetable,thefollowingDELETEstatementwilldojustthat:
DELETEfromAlbums;
Summary
Okay,nowthatyouarefamiliarwithbasicsofMySQLandcanaccessitusingthecommandlineanduseittocreateanddeletedatabases;create,alteranddeletetables;select,insert,update,anddeletetabledata;anddootherneatthingswithdatalikefilteringitandorderingitthewayyouwantusingMySQLcommands,itisthetimetomoveonandlookathowwecanusePHPandMySQLtogetherandcreateaverysimplewebsitewhereyouaddrecordstoadatabaseofourfavoriteartists.
Chapter4-Hour4:PHPandMySQL:TheDynamicDuo
“Alanguagethatdoesn’taffectthewayyouthinkisnotworthknowing”–AlanJ.Perils
Inthischapterwewillcover:
CreatingtheFamilyDatabaseCreatingandInsertingValuesintotheFamilyMembersTableCreatingaPHPconfigurationFiletheWebsiteCreatingtheIndexPageCreatingtheFormtoInputDataCreatingtheMemberAddedPage
Thinkofseeingyourtwofavoriteartistsperformingtogether.ThisiswhatitshouldfeellikeatthismovementasweareaboutseePHPandMySQL(mostlyPHP)worktogethertocreateawebsite.Bynowyoushouldbeabletoimaginethegoodmusicthesetwocanmaketogether.
Thewebsiteissimple;let’ssayyouwanttokeeptrackofyourfamilymembersonline.Wewillcreateasimplewebsitethatletsyouaddthem(ifyoulikethem)toadatabasesoyoudon’talwayshavetorememberwhotheyare.Wewillforegoalotofsecurityfeaturesjusttokeepitsimpleandotherfunctionsbutthissimpleexampleshouldbeenoughtogetyouonyourway.
BynowyouhaveafairlygoodgraspofPHPandcanusethecommandlinetotypeSQLcommands.Wewillneedboth.SomakesurebothApacheandMySQLarerunninginXAMPP(SeeChapter1andChapter3onhowtoenableApacheandMySQLrespectively).
Soletusgetstarted!
CreatingFamilyDatabase
OpenupthecommandlineandfireuptheMySQLClientandloginasthe‘root’(seeChapter3).
CreatetheDatabasebyenteringthefollowingcode:CREATEDATABASEFamily;
Thenselectthedatabaseinordertouseit:USEFamily;
CreateandInsertingValuesintotheFamilyMembersTableNowwecreatethetablethatstorestheinformation.Itshouldlooklikethis:
FamilyMembers
MemberID
FirstName
LastName
Age
Gender
Relationship
Thecodetocreatethetableslooksasfollows:CREATETABLEFamilyMembers
(
MemberIDintunsignedNOTNULLauto_incrementPRIMARYKEY,
FirstNamevarchar(80)NOTNULL,
LastNamevarchar(80)NOTNULL,
Ageint(3)unsignedNOTNULL,
GenderENUM(‘Male’,‘Female’)NOTNULL,
Relationshipvarchar(80)NOTNULL
);
Whenwedescribethetablewegetsomethinglikethis:
+––––—+–––––––—+––+–—+–––+–––––-+
|Field|Type|Null|Key|Default|Extra|
+––––—+–––––––—+––+–—+–––+–––––-+
|MemberID|int(10)unsigned|NO|PRI|NULL|auto_increment|
|FirstName|varchar(80)|NO||NULL||
|LastName|varchar(80)|NO||NULL||
|Age|int(3)unsigned|NO||NULL||
|Gender|enum(‘Male’,‘Female’)|NO||NULL||
|Relationship|varchar(80)|NO||NULL||
+––––—+–––––––—+––+–—+–––+–––––-+
Thenweinsertvaluesintothetables:
INSERTINTOFamilyMembersVALUES
(NULL,‘Robert’,‘Williams’,52,‘Male’,‘Father’),
(NULL,‘Martha’,‘Williams’,49,‘Female’,‘Mother’),
(NULL,‘Doreen’,‘Williams’,18,‘Female’,‘Sister’),
(NULL,‘Jace’,‘Williams’,13,‘Female’,‘AdoptiveSister’),
(NULL,‘Benson’,‘Williams’,22,‘Male’,‘Brother’),
(NULL,‘Timothy’,‘James’,23,‘Male’,‘Cousin’);
Whenweselectalltherecordsinthetable,weseesomethinglikethis:+–––-+–––—+–––-+–—+––—+–––––—+
|MemberID|FirstName|LastName|Age|Gender|Relationship|
+–––-+–––—+–––-+–—+––—+–––––—+
|1|Robert|Williams|52|Male|Father|
|2|Martha|Williams|49|Female|Mother|
|3|Doreen|Williams|18|Female|Sister|
|4|Jace|Williams|13|Female|AdoptiveSister|
|5|Benson|Williams|22|Male|Brother|
|6|Timothy|James|23|Male|Cousin|
+–––-+–––—+–––-+–—+––—+–––––—+
Nowwearedonewiththecommandline(butnotMySQL),sowecanclosethat.
CreatePHPconfigurationFilefortheWebsite
Wemustfirstcreateafolderandnameit“Family”andplaceinitinthehtdocsfolder.ThisfolderislocatedintherootdirectoryofourXAMPPinstallation.Thenwecreateafilecalledconfig.phpandplaceitintherootfolderofourwebsite
Warning:forsecuritypurposethisfileneedstobeplacedoutsideoftheserverbecause,whileitisnoteasytoreadPHPthroughthebrowser,itcanhappeniftheserverismisconfigured.Butsincewewanttokeepthisassimpleaspossible,wewillplaceithere.
Nextwedefinetheconstantsneededtoestablishoutconnectionstringthatweshallusetooconnecttothemusicdatabase:
<?phpdefine(‘DB_NAME’,‘Family’);define(‘DB_USER’,‘root’);define(‘DB_PASSWORD’,”);define(‘DB_HOST’,‘localhost’);?>
Warning:forsecurityreason,puttinginaplaintextpasswordisamajorsecurityrisk.Youcanusehash()andstorethehashintheconfigurationfileconfig.php.Thenyoucancheckiftheenteredpasswordmatchesthehashwhenloggingin.
Thenweestablishtheconnectionstringbypassingintheconstants;hostname,username,password,anddatabasenametothemethodthatestablishestheconnection:
<?php
define(‘DB_NAME’,‘Family’);
define(‘DB_USER’,‘root’);
define(‘DB_PASSWORD’,”);
define(‘DB_HOST’,‘localhost’);
$conn=@mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
?>
Nowweneedtocheckiftheconnectionssucceededornot.Ifitdidn’t,wedisplaytheappropriateerrormessageandstopexecutionofthePHPscript:
<?php
define(‘DB_NAME’,‘Family’);
define(‘DB_USER’,‘root’);
define(‘DB_PASSWORD’,”);
define(‘DB_HOST’,‘localhost’);
$conn=@mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
if(!$conn){
die(‘Couldnotconnect:‘.mysqli_connect_error());
}
?>
Andthat’sitforestablishingtheconnectionstring.ThisscriptwillberequiredbyeveryPHPscriptthatneedstoconnecttothedatabasetoworkwiththedata.
CreatingtheIndexPage
Nowweneedtocreatethelandingpagewhichshalllistthefamilymembersthatareinourfamilydatabaseinatable.WearegoingtoaddsomeCSS(bylinkingtoexternalstylesheets)tocreateanattractivetabletodisplayourdatain.
Wecreateafilenamedindex.phpandplaceitrootdirectoryofthewebsite.Thecodeforfileshouldlooksomethinglikethis:
<!DOCTYPEhtml>
<html>
<head>
<linkrel=“stylesheet”type=“text/css”href=“css/main.css”>
<linkrel=“stylesheet”type=“text/css”href=“css/table_styling.css”>
</head>
<body>
<divid=“container”>
<divid=“header”>
<h2>MyFamily</h2>
</div>
<divid=“btn_add”>
<ahref=“form.php”>ADD</a>
</div>
<divid=“content”>
<?php
require_once(‘config.php’);
$sql=“SELECTMemberID,FirstName,LastName,Age,Gender,Relationship
FROMFamilyMembers”;
$response=@mysqli_query($conn,$sql);
if($response){
echo‘<table>
<tr>
<th>MemberID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Gender</th>
<th>Relationship</th>
</tr>’;
while($row=mysqli_fetch_array($response)){
echo‘<tr>
<td>’.$row[‘MemberID’].‘</td>
<td>’.$row[‘FirstName’].‘</td>
<td>’.$row[‘LastName’].‘</td>
<td>’.$row[‘Age’].‘</td>
<td>’.$row[‘Gender’].‘</td>
<td>’.$row[‘Relationship’].‘</td>
</tr>’;
}
echo‘</table>’;
}
else{
echo“Coundnotgetaresponsefromdatabase”.mysqli_error($conn);
}
mysqli_close($conn);
?>
</div>
</div>
</body>
</html>
Thereisquitealotgoingonherebutwewillnotgetintoitall.Wealsowon’tbediscussinganyoftheHTMLandCSSasthisbookassumingyouhavesomebasicknowledgeofthoseandhowtolinkexternalstylesheets.
Firstly,inthePHPcode,weincludetheconfig.phpfilebycallingtherequire_oncefunctionandpassingthepathtothefileasaparameter(wepassinarelativepathsincetheconfigurationfile).Thiswillallowustoaccessourdatabaseconnectionwedefinedinthatfile:
require_once(‘config.php’);
NextwecreatethequerystringthatwillbeusedtoretrievedatafromdatabaseusingSQLandassignittothevariable$sql:
$sql=“SELECTMemberID,FirstName,LastName,Age,Gender,RelationshipFROMFamilyMembers”;
WeuseaSELECTstatementtoselectthefieldswewishtodisplayfromtheFamilyMemberstablefollowingthesamesyntaxruleswewoulduseonthecommandline.
Thenwesendthequerytothedatabaseusingthemysqli_queryfunctionandpassintheconnectionvariable,whichisnowaccessiblebecauseweincludedtheconfig.php,andthequerystringthenassignthereturnvaluetothe$responsevariable:
$response=@mysqli_query($conn,$sql);
Afterthat,wecheckifwegotaresponsefromthedatabaseusinganifstatement:
if($response){
}
Ifwegotaresponsefromthedatabase,wecreateawithatablerowandtableheadersbyembeddingHTMLinPHPcodeandechoingthatinsidetheifstatement:
echo‘<table>
<tr>
<th>MemberID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Gender</th>
<th>Relationship</th>
</tr>’;
Okay,thatdoesitforthecolumns.Nowweneedtodisplaytherowsonebyonedynamicallyincasewehavemany.Thefollowingcodedoesthat:
while($row=mysqli_fetch_array($response)){
echo‘<tr>
<td>’.$row[‘MemberID’].‘</td>
<td>’.$row[‘FirstName’].‘</td>
<td>’.$row[‘LastName’].‘</td>
<td>’.$row[‘Age’].‘</td>
<td>’.$row[‘Gender’].‘</td>
<td>’.$row[‘Relationship’].‘</td>
</tr>’;
}
Intheabovecode,weusealooptogothroughanarraywegetfromtheresponseusingthemysqli_fetch_array()functionandpassinginthe$responsevariableasaparameter.Weassignthevalue(whichisalsoanarraycontainthefieldsoftherow)wegetfromthefunctionintothevariable$rowandembedHTMLaroundthemtocreatenewtablerowsdynamicallyasmanyastheyareelementsinthearray.
Thenwecloseofthetableoffandthatisitfordisplayingthedatadynamically:
echo‘</table>’;
Butwhatiftherewasnoresponseforthedatabasebecausesomethingwentwrong?Thatcouldhappen.Inthatcaseweaddanelsestatementafterourifstatementtodisplaytheerrormessageusingthemysqli_errorfunctionandwepassinourconnectionasaparameter:
else{
echo“Coundnotgetaresponsefromdatabase”.mysqli_error($conn);
}
Lastly,weclosethedatabaseconnectionusingthemysqli_closefunction,passingintheconnectionasaparameterandwearedonewiththeindexpage:
mysqli_close($conn);
Gointothebrowserandenterthatpathtotheindex.phpasfollowsthenpressEnter:https://localhost/Family/index.php
Thebelowwindowshoulddisplay:
Asyoucansee;itisdisplayingtherecordsweenteredpreviousandhasgeneratedthe
tabledynamically.Neathuh!
CSSforindexPageCreateafolderinsidethewebsitesrootfoldercalledcssandcreatetwoCSSfilescalledmain.cssandtable_styling.css.Thesearetheexternalstylesheetsforthepage.
Weenterthefollowingcodeintomain.csstostylethebody,headers,andlinks.Italsocentersthecontent:
body{
background-color:#EEE;
}
#container{
width:900px;
margin-left:auto;
margin-right:auto;
}
#header{
color:#2ca089;
text-align:center;
font-size:2em;
}
/*links*/
a:link,a:visited{
background-color:#2ca089;
color:white;
padding:5px12px;
text-align:center;
text-decoration:none;
display:inline-block;
}
a:hover,a:active{
background-color:#AFDCB1;
}
#btn_add{
padding:5px0px;
text-align:right;
}
Thenweenterthefollowingcodeintotable_styling.csstostylethetable:
table{
border-collapse:collapse;
width:100%;
}
th,td{
text-align:left;
padding:8px;
}
tr:nth-child(even){background-color:white;}
th{
background-color:#2ca089;
color:white;
}
CreatingtheFormtoInputData
Wecreateafilecalledform.phpandplaceittherootfolderofthewebsite.Thenweplacethecodebelow:
<!DOCTYPEhtml>
<html>
<head>
<linkrel=“stylesheet”type=“text/css”href=“css/main.css”>
<linkrel=“stylesheet”type=“text/css”href=“css/form_styling.css”>
</head>
<body>
<divid=“container”>
<divid=content>
<div>
<formaction=“member_added.php”method=“post”>
<divid=“header”>
<h3>AddFamilyMember</h3>
</div>
<divid=“btn_add”>
<ahref=“index.php”>ViewMembers</a>
</div>
<labelfor=“fname”>FirstName</label>
<inputtype=“text”id=“first_name”name=“first_name”maxlength=“80”>
<labelfor=“lname”>LastName</label>
<inputtype=“text”id=“last_name”name=“last_name”maxlength=“80”>
<labelfor=“age”>Age</label>
<inputtype=“number”id=“age”name=“age”min=“1”max=“100”>
<labelfor=“gender”>Gender</label>
<selectid=“gender”name=“gender”>
<optionvalue=“Male”>Male</option>
<optionvalue=“Female”>Female</option>
</select>
<labelfor=“relationship”>Relationship</label>
<inputtype=“text”id=“relationship”name=“relationship”maxlength=“80”>
<inputtype=“submit”name=“submit”value=“ADD”>
</form>
</div>
</div>
</div>
</body>
</html>
Nothingoutoftheordinaryishappeninghere.ThisjustyourbasicHTMLformwhichwewillusetosendthedatainputtedintothefieldstothedatabase.Theformhasthetwoattributeswhichareofinteresttous:
formaction-Thistellstheformtosendtheform-datatothemember_added.phpscript(whichweshallcreateinamoment)thatwillprocesstheinformationwhentheADDbuttonispressed
method=“post”–Tellstheformtosendtheform-dataasanHTTPposttransaction.ThismeansthatthedataisappendedinsidethebodyoftheHTTPrequestURL.Thisisgoodforsendingsensitivedata(thingslikepasswords)unlikethe“get”methodwhichjustappendsthedatatotheURLandanyoneonecanseeit.
Gointothebrowseranddisplaytheindexpage.ClicktheADDbuttonattoprightofthetableandthefollowingpageshoulddisplaywiththeformtoaddfamilymembers:
CSSforFormPage
CreateaCSSfilecalledform_stlying.phpandplaceitintherootdirectoryofthewebsite.Placethefollowingstylerulesinthatfiletostyletheformusingthisexternalstylesheet:
input[type=text],input[type=number],select{
width:100%;
padding:12px20px;
margin:8px0;
display:inline-block;
border:1pxsolid#ccc;
border-radius:4px;
box-sizing:border-box;
}
input[type=submit]{
width:100%;
background-color:#2ca089;
color:white;
padding:14px20px;
margin:8px0;
border:none;
border-radius:4px;
cursor:pointer;
}
input[type=submit]:hover{
background-color:#2ca089;
}
CreatingtheMemberAddedPage
Finally,youneedtocreateonefinalPHPscriptfortoprocessthedatasentbytheform.WecreateanewPHPscriptandcalledmember_addedandplaceintherootdirectoryofourwebsite.Thenweplacethefollowingcodeinthescript:
<!DOCTYPEhtml>
<html>
<head>
<linkrel=“stylesheet”type=“text/css”href=“css/main.css”>
<linkrel=“stylesheet”type=“text/css”href=“css/form_styling.css”>
</head>
<body>
<divid=“container”>
<divid=“content”>
<?php
require_once(‘config.php’);
if(isset($_POST[‘submit’])){
$null_fields=array();
if(empty($_POST[‘first_name’])){
$null_fields[]=‘FirstName’;
}else{
$first_name=trim($_POST[‘first_name’]);
}
if(empty($_POST[‘last_name’])){
$null_fields[]=‘LastName’;
}else{
$last_name=trim($_POST[‘last_name’]);
}
if(empty($_POST[‘age’])){
$null_fields[]=‘Age’;
}else{
$age=$_POST[‘age’];
}
if(empty($_POST[‘gender’])){
$null_fields[]=‘Gender’;
}else{
$gender=$_POST[‘gender’];
}
if(empty($_POST[‘relationship’])){
$null_fields[]=‘Reliationship’;
}else{
$relationship=$_POST[‘relationship’];
}
if(empty($null_fields)){
$null_variable=NULL;
$sql=“INSERTINTOFamilyMembersVALUES(‘$null_variable’,‘$first_name’,‘$last_name’,‘$age’,‘$gender’,
‘$relationship’)”;
if(!mysqli_query($conn,$sql)){
die(‘Error:‘.mysqli_error($conn));
}
echo“Familymemberhasbeenentered!”;
mysqli_close($conn);
}
else{
echo“Youneedtoenterthefollwing
missingdata:<br/>”;
foreach($null_fieldsas$null_field){
echo$null_field.“<br/>”;
}
}
}
?>
<div>
<formaction=“member_added.php”method=“post”>
<divid=“header”>
<h3>AddFamilyMember</h3>
</div>
<divid=“btn_add”>
<ahref=“index.php”>ViewMembers</a>
</div>
<labelfor=“fname”>FirstName</label>
<inputtype=“text”id=“first_name”name=“first_name”maxlength=“80”>
<labelfor=“lname”>LastName</label>
<inputtype=“text”id=“last_name”name=“last_name”maxlength=“80”>
<labelfor=“age”>Age</label>
<inputtype=“number”id=“age”name=“age”min=“1”max=“100”>
<labelfor=“gender”>Gender</label>
<selectid=“gender”name=“gender”>
<optionvalue=“Male”>Male</option>
<optionvalue=“Female”>Female</option>
</select>
<labelfor=“relationship”>Relationship</label>
<inputtype=“text”id=“relationship”name=“relationship”maxlength=“80”>
<inputtype=“submit”name=“submit”value=“ADD”>
</form>
</div>
</div>
</div>
</body>
</html>
Letusbreakthisdownandlookatthemostinterestingbits.
Wehavetocheckiftheinformationwassubmittedbytheformbeforeweworkwithit.Wedothiswithanifstatementandusetheisset()builtinPHPfunctionthatchecksifavariableisnull.Wepassintheassociativearray$_POSTasaparameter.Itcontainsallvaluesinputtedintotheformfoundinform.php.Thearrayispassedtothescriptviathepostmethodoftheform:
if(isset($_POST[‘submit’])){
}
Insidetheconditionalstatement,wethendeclareanarraytocheckifwehappentohavemissedanyiftheforminputs:
$null_fields=array();
Nextwestartcheckingifanythevaluesinthearrayareemptybeforewesendthemtothedatabase.Ifso,weaddthemtothe$null_fieldsarrayifnot,wecreateavariableandstorethemthere.Wewilljustlookatoneoftheif…elsestatementsbecausetherestasimilar:
if(empty($_POST[‘first_name’])){
$null_fields[]=‘FirstName’;
}else{
$first_name=trim($_POST[‘first_name’]);
}
Wedothisfortherestofvaluesinthe$_POSTarray.
Warning:Thismaynotbethemostsecurewayofverifyingdatabeforeitgoestothedatabase.Forthatweneedtouseregularexpressionsandthatisanadvancedtopic.Wearejusttryingtokeepthingssimple.
Nextwehavetocheckifthe$null_fieldsarrayturnedoutempty.Thismeansallthedatawassubmitted:
if(empty($null_fields)){
}
Ifweareinsidethatcondition,itmeansthatallthedatawassubmittedandwecanquerythedatabase.WeusetheINSERTTOstatementtoinsertthedataintotheFamilyMemberstable.Wefollowtherulesusedtoinsertdataintoatablebymakingsurethevariablesareinthesameorderastheyaredefinedinthetables.Wedeclaredanextravariablebeforethecreatingthequerystringtopassinasanullvaluefortheprimary.Wealsomakesurethenumberofparametersmatchthenumberoffieldsinthetable:
$null_variable=NULL;
$sql=“INSERTINTOFamilyMembersVALUES(‘$null_variable’,‘$first_name’,‘$last_name’,‘$age’,‘$gender’,‘$relationship’)”;
Next,weusequerydatabaseusingthemysqli_query(),passingintheconnectionandquerystringasparameters,whilesimultaneouslycheckingforanyerrorsreturnbythefunction.ItreturnsFALSEonfailure.Iferrorsarefound,wedisplaythemsotheycanbefixed.Ifnoterrorsarefound,weechoasuccessmessage:
if(!mysqli_query($conn,$sql)){
die(‘Error:‘.mysqli_error($conn));
}else{
echo“Familymemberhasbeenentered!”;
}
Sonowwearedonewithwhathappenswhentheplayerinputsallthedata,butifhemissesany,weshoulddisplaytohimthefieldshemissedbyloopingthroughthe$null_fieldsarrayusingaforeachloopandechoingthemtothescreen.
else{
echo“Youneedtoenterthefollwingmissingdata:<br/>”;
foreach($null_fieldsas$null_field){
echo$null_field.“<br/>”;
}
}
Thenafterthat,weexittheconditionthatchecksifthe$_POSTarrayisemptyandclosetheconnectiontothedatabase:
mysqli_close($conn);
ThenrightaftertheclosingPHPtagwedisplaytheformagainthatallowsforthePHPscripttocallitselfsothatwecancontinueinputtingdataorre-enterdataincaseweforgotsomefields.
Andwearedone!Nowweshouldbeabletoaddfamilymembersandviewthem.Weshouldalsobeabletonavigatebetweenpagesusingthebuttonsonthetoprightcorneroftheformsortablethatallowyouswitchbetweenthepages.
Startuptheindexpageandgototheformpagetoaddsomedata
ClicktheADDbuttontoaddthemembertodatabase.Youshouldseethesuccessmessage:
ClicktheViewMembersbuttontoverify.Thebelowwindowshoulddisplaywiththenewmemberadded:
SummarySothereyouhaveit!BeforethischapterwelookedatPHPandMySQLseparatelyandinthischapterwasaimedatconsolidatingthetwo,andshowinghowtousethemtoproducedynamiccontent.Itshouldnotbethathardtomodifythewebsitetodowhateveryouneedittodoasyouarenowcapable.
Inthechapterwecreatedaconfigurationfilethatstoredtheconnectiontothedatabaseanduseditallthroughoutthewebsitetoestablishaconnectiontothedatabaseandqueryittostoreandretrievedata.Wecreatedapagethatenablesyoutoviewinformationaboutthefamilymembersyouhaveaddedtodatabase.WealsocreatedapagewithaformforinputtingthedataandapagethathasthePHPneededtoprocessthedatawhentheformissubmitted.
Conclusion
“Educationisthekindlingofaflame,notthefillingofavessel.”―Socrates
Thisistheendofthisbook,butnotyourlearning.YoustillhavetogooutthereandlearnwhatotherthingsyoucandowithPHPandMySQLandgetamoreindepthunderstandingoftheconcept.Atthispointthough,IsincerelyhopeyouhavebeenequippedwithenoughknowledgetodowhatisyouneedtodowithabasicunderstandingofPHPandMYSQL.
Inthefirsthour,wecoveredthebasicsofPHPlikecomments,variables,constantsandoperators.ButnotbeforewelearnedhowtoinstalltheserverpackageXAMPPtothathastheApacheservicefortheserver.WerunaPHPscriptanddisplayedneatmessagestothescreen.WealsochoseacooltexteditortowritebeautifulPHPcode.
Insecondhour,wegotalittledeeperintothebasicsofPHPandlookedathowwecanwriteconditionalstatementsthatallowustoexecuteblocksofcodedependingonaspecifiedcondition.Nextwelookedathowtoloopthoroughcodeuntilacertainconditionismetusingwhileandforloops.Wethenlookedathowweencapsulatedcodeblocksandre-usethemthroughtheprogramusingfunctions.Wepassedinformationtotheintheformofparametersandtheyreturnsomeofitbackafterperformingoperationsonthatinformation.Thenwefinallywesawhowtostorecollectionsofdataintoarraysandhowtoloopthroughthem.
Inthethird,hourwelearnedMySQL.WelearnedhowtobringupthecommandprompttoenterMySQLcommandstoperformvariousoperationssuchascreatinganddeletingdatabases;creating,alteringanddeletingtables;retrieving,inserting,updatinganddeletingthedatainthetables.
InthefourthandfinalchapterwelookedathowwecanusePHPandMySQLtogethertocreatedynamiccontentforasimplewebsiteweweremakingalistofourfavoritefamilymembersandtheirdetails.
Allthisisknowledgefortheabsolutebeginnerwhoneedssomethingtoquicklyguidethemwithclearexamplesandexplanations.IwishyouwellinyourfuturesendeavorsandIbelieveyouarewellonyourwaytoachievingyourdreams.GladIcouldhelp.