Upload
others
View
47
Download
5
Embed Size (px)
Citation preview
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.