php programming: php crush course! learn php programming

147

Upload: others

Post on 30-Nov-2021

47 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 2: PHP Programming: PHP Crush Course! Learn PHP Programming

PHPPROGRAMMING

PHPCRUSHCOURSE!LEARNPHPPROGRAMMINGIN4HOURS!PHPFORBEGINNERS-SMARTANDEASYWAYSTO

LEARNPHP&MYSQL

Page 3: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 4: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 5: PHP Programming: PHP Crush Course! Learn PHP Programming

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!

Page 6: PHP Programming: PHP Crush Course! Learn PHP Programming

TableofContent

Introduction

Chapter1-Hour1:InstallingandPHPBasics

Chapter2-Hour2:MorePHPBasics

Chapter3-Hour3:MySQLBasics

Chapter4-Hour4:PHPandMySQL:TheDynamicDuo

Conclusion

Page 7: PHP Programming: PHP Crush Course! Learn PHP Programming

Introduction“Youcannotopenabookwithoutlearningsomething.”-Confucius

PeoplelearnPHPformanyreasons.Everylanguagehasabitofalearningcurveandonecangetboggeddownintwomuchtheorythatitcanmakeitunappealingbecausethetaskaheadseemsodious.Maybeyouwanttobuildasimpleblogorsomethingasadvancedasamassiveonlinee-commercesitewiththousandsofproductsupforsale.Itishardtoknowwheretostartgettingtheneededknowledge.

Ifyouarelookingforawaytogetgoingfastinordertomakeyouvisionsarealitythenyouhavecometotherightplace!ThisbooksaimsatgettingyoustartedonyourjourneytoPHPandMySQLmasteryin4hours!Itdoesthisbytellingyouthemostimportantstuffyouneedtoknowtogetstartedquicklyfortheabsolutebeginner,ineitherPHPorMySQL,soyougettodoingusefulstuffasquicklyaspossible.

ThisisnotacomprehensiveguidetoPHPandMySQLthatcoversalltheaspectsbutacrashcoursethatgivesyouapracticalguideonhowtodoreallycoolbasicthingswithPHPandMySQLontheirownandtogether.Thetwocangetprettyadvancedbutwiththeknowledgeinthisbook,youshouldbeabletogetthatprototypeupandrunningasyoutacklethemoreadvancedtopics.

Page 8: PHP Programming: PHP Crush Course! Learn PHP Programming

AlittleknowledgeofHTMLandCSSwillbeneededbeforebecause,really,PHPisjustalanguagethatisusedtoproducewebpagesanditsfinaloutputisHTML.WewillgooverallthebasicsofPHPandMySQLandfinallyputitalltogetherandbuildsimplewebsitewhereyouwillbeabletostorearecordsofyourfavouriteartistsusingthedynamicduo.

Thebasicsareallyouneedtogetgoingin4hours(andthisbook,ofcourse)isallyouneed.

ButwhatisPHPorMySQLandwhydoyouneedittoaccomplishthispreviouslyimpossibletask?

Page 9: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 10: PHP Programming: PHP Crush Course! Learn PHP Programming

AShortIntroductiontoPHP

PHPstandsforHypertextProcessor.Itisaserversidescriptinglanguagethatisusedtoproducedynamicwebcontentamongotherthings.ThismeansthateverythingPHPdoesisnotdoneonthecomputerthatisusedtoviewthewebpages,calledtheclient,butaspecialisedcomputercalledaserverthathousesallthewebpagesthatyouareviewingontheclientmachine.

BeingascriptinglanguagemeansthatPHPcan’treallybeusedtomakestandaloneapplicationsthatrunonyourcomputerasitisdesignedtoonlydothingswhenaneventhappenswithinwebpageslike;clickingonalinkorgettingformdatawhenawebformissent.

Page 11: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 12: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 13: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 14: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 15: PHP Programming: PHP Crush Course! Learn PHP Programming

WhatWeWillCoverinThisBook

ThisbookisseparatedintofourmainchaptersorhoursthathelpyougettotheheartofPHPandSQLandsendyouonyourwaytobeingamasterinnotime.

InthefirsthourwewillspendtimeinstallingthemuchneededwebserverpackagecalledXAMPP.Irecommendthatyoudownloadithere:

https://www.apachefriends.org/index.htmlbeforewestartthatchapter.Thiswillenableustorunexamplesthroughoutthisbook.ThenweshallpickatexteditorforourPHPcode.ThenwewilllookathowtorunPHPscriptsand,finally,weshallcoversomeofthebasicsofPHP,suchascomments,variables,constantsandoperators.

Theexamplesinthisbookcanbetypedoutor,tosavetime,copiedandthenpastedintoyourcodeeditororcommandlineinterface.

Page 16: PHP Programming: PHP Crush Course! Learn PHP Programming

Inthesecondhour,weshallcontinuewithPHPandcoverconditionalstatements,Loops,Arraysandfunctions.Afterthischapter,youshouldconsideryourselfwellacquaintedwithPHPtotacklefurtheradvancedtopics.

Youcantakeabreakafterthispartandletitallsinkinandmakeanothercupofcoffee.

InthethirdhourwetackleMySQLanditscommands,butfirstwelearnhowtoaccessthecommandline.Thenwemoveontothecommandsthatletuscreateanddeletedatabases;create,alteranddeletetables;insert,select,updateanddeletedatainthetables.

Finally,inthefinalhour,weputPHPandMySQLtogetherandcreateasimplewebsitetoshowyouhowthesetwoworktogetherhandinhand.

Letusgettoit.Grabyourfirstcupofcoffee!

Page 17: PHP Programming: PHP Crush Course! Learn PHP Programming

Chapter1-Hour1:InstallingandPHPBasics“Thewaytogetstartedistotakethefirststepwithdream-poweredoptimism.”-DebasishMridha

Thischapterwewillcover:

InstallingawebserverInstallingatexteditorStartingApachestorunPHPscriptsCreatingandrunningaPHPscriptPHPbasics(comment,variables,operators,constants,strings)

Bearwithmealittle.Iknowthatthefirstchapterofalmosteveryprogrammingbookpilesonthetheorytomakesureyouknowwhatyouaregettingyourselfinto.Iwon’tlie;eveninthisshortbook,westillhavetogothroughitalittle.JustalittlebitofittocoversomebasicsofPHP.Butthatisforlateronduringthehour.FornowyouneedtoinstalltheserverandchooseanappropriatetexteditortousewhenwritingPHPcode!

Page 18: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 19: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 20: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 21: PHP Programming: PHP Crush Course! Learn PHP Programming

InstallingaTextEditor

Now,youwillneedatexteditortowritesomebeautifulPHP.Ideally,anytexteditorwoulddo,eventhedefaultnotepadonwindowsorterminalforMacOSXcanbeusedwhenwritingPHP.Wewillusenotepad++becauseithassomeniftyfeatureswhichcancontributetowardswritingcleanandefficientcodeinafastway,suchassyntaxhighlightingandautocomplete.

Plusit’sfree!

ThistexteditorswillsaveyoutimeandaworldofpainbyjustdownloadingithereInstallingaTextEditorandinstallingit.Justrememberthatanytextwilldo.Soevenifyoudon’thavenotepad++,youcanusewhateveryoulike.

Page 22: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 23: PHP Programming: PHP Crush Course! Learn PHP Programming

StartingApachetorunPHPscripts

NowthatyouhaveinstalledXAMPP,youneedtostarttheapachewebserviceinorderforthebrowsertobeabletorunPHPscripts.Todothis,openuptheControlPanelofXAMPPbydoubleclickingonitsicon.Bydefault,itshouldstartApacheautomatically,butyoucanstartitmanuallybyclicking“Start”asinthepicturebelow:

NOTE:SomeotherapplicationsinstalledonyourcomputercancauseApachenottostartbecausetheyareusingthesameportApacheisconfiguredtoe.g.Skype.Ifthatisthecase,juststopthoseservicesandstartApacheagain.

Page 24: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 25: PHP Programming: PHP Crush Course! Learn PHP Programming

CreatingYourFirstPHPScript

Thispartisfairlyeasytodo.Allyouhavetodoisfollowthesesteps:

Step1-CreatethePHPfile

Openupyourtexteditorandcreatearegulartextfileandplacethefollowingcodeintoit:

<!DOCTYPEhtml><html><body>

<?phpecho“MyfirstPHPscript!”;?>

</body></html>

Page 26: PHP Programming: PHP Crush Course! Learn PHP Programming

ThefilestilllookslikeyourbasicHTMLfileexceptthatyouembedPHPcodebetweentags<?phpand?>.Theechostatementjustoutputseverythingthatcomesafterittothescreen.Inourcase,thiswillbe“MyfirstPHPscript!”.Weshallseethisinactioninamoment.

AndallyouhavetorememberisthateveryPHPstatementendswithasemicolon(Exceptforcomments.Wewilllookatthoselaterinthehour).

Savethefileas“example.php”.

Page 27: PHP Programming: PHP Crush Course! Learn PHP Programming

Step2-PlaceitintheRootDirectoryofXAMPP

Grabthefile“example.php”thatyoujustcreatedandplaceitintherootdirectoryofyourserverinthefoldernamed“htdocs”,andWhalla!Youarereadytorunitinyourbrowser.

TIP:Tofindtherootdirectory,youcanlookforitonyourlocalmachineoryoucouldjustopenuptheXAMPPControlPanelandclickthe“Explorer”button,asshowninthepicturebelow,tobringuptherootfolderandthenlocatethehtdocsfolderandplacethefileinthere:

NOTE:ThefoldertoplaceyourPHPfileswillbedifferentwitheachserver.Forexample;youplacetheminthefoldernamedwwwifyouareusingWAMP.

Page 28: PHP Programming: PHP Crush Course! Learn PHP Programming

Step3-RunItintheBrowserOpenupyourbrowser(GoogleChromeorFirefoxarerecommended)andtypethefollowing:

http://localhost/example.php

PressEnterandyoushouldseethefollowingwindowbelow:

Thereyougo!Ifyoufollowthosesteps,youshouldbeabletorunallotherscriptscreatedinthischapter.

Page 29: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 30: PHP Programming: PHP Crush Course! Learn PHP Programming

PHPBasics

Comments

Wanttoleavemessagesforyourfutureselforothermembersofyourteam?Thencommentssaveyouthetroubleofhavingtorememberyourtrainofthoughtandmakeforanexcellentwaytodocumentwhatyourthoughtswereatthetime.Theycanalsobeusedtoexcludecertainpiecesofcodealltogether.

//Thisisasinglelinecomment

#Thisisanothersinglelinecomment

/*Thisisacommentblock.Everythinginherewillbeignoredandcanspanmultiplelines.*/

Page 31: PHP Programming: PHP Crush Course! Learn PHP Programming

Variables

Tobuildyourdreamwebsite,youwillneeddataandawaytostorethisdata.Itcanbeaname,anumber,adateorapicture.PHPoffersawayforyoutostoretheminmemorybyusingavariable.

EachvariableinPHPisprecededbythe$signfollowedbythevariablenamewithoutanyspacesinbetweenthesignandvariablename:

$myInt=10;

Letusseesomeofthisinactionwiththefollowingcode:

<!DOCTYPEhtml><html><body><?php$txt=“MysecondPHPscript!”;echo$txt;?></body></html>

Page 32: PHP Programming: PHP Crush Course! Learn PHP Programming

Ifyourunthisscriptinthebrowser,itshouldoutputthefollowing:

“MysecondPHPscript!”;

Fewmorethingstorememberaboutvariables:

Theyarecasesensitive.Thismeans$nameand$naMearetwodifferentvariablesTheymustalwaysstartwithaletterorunderscoreTheycannotstartwithnumbersTheycanonlycontainalphanumericvalues

PHPisalooselytypelanguageandthereforeyoudon’tneedtodefinethedatatypesforvariables.PHPwillautomaticallyconvertthevariabletothecorrectdatatypedependingonthevalueassignedtoit.

Page 33: PHP Programming: PHP Crush Course! Learn PHP Programming

Hereisalistofthecommondatatypesyouwillworkwith:

Integer–WholenumbersFloat–DecimalnumbersString–StringorcharactersBoolean–trueorfalseArray–MultipleitemsObject–AnObjectdefinedbyaclass

Youcanachievethesameresultastheexampleabovebyusingvariables:<!DOCTYPEhtml><html><body><?php$txt=“third”;echo“My”.$txt.”PHPscript!”;?></body></html>

Inthisexamplewearejoiningtwostringstogetherusingtheperiod(.)asitisusedtoconcatenatetwostringstogetherandoutputtingtheconcatenatedstringtothescreen.

Page 34: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 35: PHP Programming: PHP Crush Course! Learn PHP Programming

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)

Page 36: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 37: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 38: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 39: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 40: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 41: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 42: PHP Programming: PHP Crush Course! Learn PHP Programming

Summary

Sofar,wehavecoveredalotofthingsyouneedtoknowinordertogetgoingandseePHPinaction.WehaveinstalledawebserverpackagecalledXAMPPthatcomeswiththeAPACHEwebservicethatallowsustorunPHPscriptsinourbrowser.YoushouldnowbeveryknowledgeableenoughtocreateandrunPHPscriptsandhaveagoodideaonhowtooutputinformationtothescreen.WehavealsocoveredsomeofthebasicsofPHPlikevariablesandconstants,andlookedatsomeofitsoperators;someofthemwillbeusefulinthenexthour.

Solet’smoveon!

Page 43: PHP Programming: PHP Crush Course! Learn PHP Programming

Chapter2-Hour2:MorePHPBasics

“Talkischeap.Showmethecode”–ThomasC.Gale

Inthischapterwewillcover:

ConditionalStatementsLoopsArraysFunctions

ThisisthepartwherewedivealittledeeperintothebasicsofPHPandgettodoalotofcoolstuff.Youaredonewithsaladportionofthebasics,thisisthemeatsection.

Page 44: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 45: PHP Programming: PHP Crush Course! Learn PHP Programming

ConditionalStatementsConditionalstatementsallowforabitofdecisionmakingincode.Theyperformdifferentactionsdependingonthewhethertheconditiontheprogrammerspecifiedhasbeenevaluatedastrueorfalse.

HereisalistofconditionalstatementsusedinPHP:

IfstatementsIf…elsestatementsIf…elseif…elsestatementSwitchstatements

Letustakealookateachoneindetail.

Page 46: PHP Programming: PHP Crush Course! Learn PHP Programming

TheifStatementAnifstatementevaluatesanexpressionandexecutesablockofcodeiftheexpressionevaluatedtotrue.Ifitevaluatedtofalse,thecodeblockisignored.

Thefollowingexamplewilloutput“5islessthan10!”iftheconditionistrue,otherwise,thecodeblockwillbeignored:

<?php

$x=5;

if($x<10){

echo“$xislessthan10!”;

}

?>

Output:

5islessthan10!

Page 47: PHP Programming: PHP Crush Course! Learn PHP Programming

Theif…elseifStatementTheif…elseifstatementexecutesacodeifblockiftheexpressionevaluatedastrueandanothercodeifthatexpressionisevaluatedasfalse.

Letusalterthepreviousexampleabit.Thefollowingcodewilloutput“50isgreaterthan20!”whichisonthesecondcodeblockbecauseitsatisfiesthesecondcondition.Thevalueassignedto$xis50anditwillreturnfalseonthefirstcondition:

<?php

$x=50;

if($x<10){

echo“$xislessthan10!”;

}elseif($x>20){

echo“$xisgreaterthan20!”;

}

?>

Output:

50isgreaterthan20!

Page 48: PHP Programming: PHP Crush Course! Learn PHP Programming

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:

Page 49: PHP Programming: PHP Crush Course! Learn PHP Programming

I5isbetween10and20!

Page 50: PHP Programming: PHP Crush Course! Learn PHP Programming

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!”;

}

?>

Page 51: PHP Programming: PHP Crush Course! Learn PHP Programming

Output:

Burgersareyummy!

Page 52: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 53: PHP Programming: PHP Crush Course! Learn PHP Programming

Loops

HereisalistofloopingstatementsinPHP:

whiledo…whileforforeach

Weshallgointoeachoneindetail.

Page 54: PHP Programming: PHP Crush Course! Learn PHP Programming

TheWhileLoop

Thewhileloopexecutesablockofcoderepeatedlyaslongasthespecifiedconditionremainstrue.

Thecodebelowshowsthevalue$xbeingifitislessthanorequalto5.Iftheconditionistrue,itgetsoutputtedtoscreenandthenincrementedagainuntiltheconditionreturnsfalse:

<?php

$x=1;

while($x<=5){

echo“Thevalueofxis:”.$x.“<br/>”;

$x++;

}

?>

Output:

Thevalueofxis:1Thevalueofxis:2Thevalueofxis:3Thevalueofxis:4Thevalueofxis:5

Page 55: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 56: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 57: PHP Programming: PHP Crush Course! Learn PHP Programming

ForeachLoopAloopthatgoesthrougheachelementfoundinanarray.Itexecutesablockofcodewitheachelementfoundinthearrayuntilitrunsout.

Thecodebelowloopsthroughalltheelementsofanarraythenoutputsthevalueoftheelementtothescreen:

<?php

$foods=array(“cereal”,“salad”,“burgers”,“fries”);

foreach($foodsas$food){

echo“$food<br/>”;

}

?>

Page 58: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 59: PHP Programming: PHP Crush Course! Learn PHP Programming

Functions

Afunctionisapieceofcodethatcanbeusedofoverandoverinaprogram.Afunctiontakesoneormoreinputscalledparameters(alsocalledarguments)anddoessomeoperationstothem.Afunctioncansometimesreturnavalueafteritisdoneprocessing.

Afewthingstorememberaboutfunctions:

Theyarenotcase-sensitiveTheyarenotexecutedautomaticallywhenthepageloadsuntiltheyarecalledbyacertainpieceofcodePHPhasmorethan1000builtinfunctionsthatcancatertoyourrequirements

Page 60: PHP Programming: PHP Crush Course! Learn PHP Programming

CreatingaFunction

Creatingyourownfunctioniseasy;juststartwiththekeywordfunctionfollowedbythefunctionnameandparenthesis.Afterthatplaceyourcodebetweentwocurlybraces{and}calledtheopeningandclosingbraces,respectively.Nowyoucanusethefunctionasmanytimesasyouneedit.Thissavesyouthetroubleofhavingtore-typethecodeeverytime.

Thecodebelowdemonstratesafunctionthatoutputsamessagetothescreen

<?php

functionechoMessage(){

echo“Hello,IamaPHPfunction!”;

}

echoMessage();

?>

Output:

Hello,IamaPHPfunction!

Page 61: PHP Programming: PHP Crush Course! Learn PHP Programming

ParametersforFunctions

Sometimesyoucanpassinformationtofunctionssothatoperationsaredoneonthem.Thisinformationisknownasparametersandisplacedintheparenthesis.Youcanaddmultipleparametersbyseparatingthemwithacoma.

Thebelowexampleshowsafunctionthatsubtractstwonumberssuppliedtofunctionasparameters:

<?php

functionsubFunction($num1,$num2){

$diff=$num1-$num2;

echo“Thedifferencebetween$num1and$num2is:”.$diff;

}

subFunction(5,6);

?>

Output:

Thedifferencebetween5and6is:-1

Page 62: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 63: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 64: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 65: PHP Programming: PHP Crush Course! Learn PHP Programming

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”

Page 66: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 67: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 68: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 69: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 70: PHP Programming: PHP Crush Course! Learn PHP Programming

Summary

Congratulations!YouarenowacquaintedwiththebasicsofPHP.BynowyoushouldbeableseethepowerPHPoffersyou.Inthischapterwediscussedconditionalstatementsthatallowthecodeyouwritetomakedecisionsbasedonspecifiedconditions.Thenwelookedatloopsthatexecuteablockofcodeuntilaconditionspecifiedreturnfalseoruntiltheyrunoutelements.Nextwediscussedhowtocallcodemultipletimesinaprogrambyputtingtheminafunction,andalsohowtopasstheminformationandhavethemreturnvaluestous.Finally,welookedintonumericandassociativearrays.Wecreatedthemandreturnedvaluesbyeitheraccessingthemdirectlyorloopingthroughthem.

NowyouarereadytotakeabreatherfromPHPandmakeanothercupofcoffee.Thisonlygetsmoreinteresting!

Page 71: PHP Programming: PHP Crush Course! Learn PHP Programming

Chapter3-Hour3:MySQLBasics

“TellmeandIforget,teachmeandImayremember,involvemeandIlearn.”-BenjaminFranklin

Inthischapterwewillcover:

StartMySQLCreateandDeletingDatabasesCreating,Reading,UpdatingandDeletingTables(CRUD)

NowthatwehavelookedintoPHP,let’slookatwhatenablesthePHPtopopulatewebpageswithcontent.ThatwouldbeadatabasesuchasMySQL.WewilllookatmostofthethingsyouneedtoknowinordertoconsideryourselfamasterofthebasicsofMySQLanddowhatyouneedtoforthatnextstepinachievingyourdreams.

Thiswillbeabreezeaswewilllearnhowtodosomereallycoolthingswithdatabases.

Belowisapictureofthetablewewillcreateandbeworkingwithinthedatabase.Wewilljustbeaddingalbumstoamusicdatabase.Youhavethetablenameattheverytopandthefieldsorcolumnsbelowthetablename.

Page 72: PHP Programming: PHP Crush Course! Learn PHP Programming

Albums

AlbumIDAlbumNameAlbumArtistAlbumTypeNumberOfTracksDateReleased

Page 73: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 74: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 75: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 76: PHP Programming: PHP Crush Course! Learn PHP Programming

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]>”.

Page 77: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 78: PHP Programming: PHP Crush Course! Learn PHP Programming

Creating,AlteringandDeletingTables

Nowthatwehaveselectedoutdatabase,let’screatesometables.Thefirsttablewewillcreateisaboutinformationontheartist.

Itisgoodpractice(andheadachesaving)tofirstcheckifanytableswiththesamenameexistsbecauseyoucan’tcreatetwotableswiththesamenameinthesamedatabase.Ifoneisfound,itisdeletedalongwithitsdata.So,becarefulwiththiscommandespeciallyifthetableisrelatedtoothertables.

Page 79: PHP Programming: PHP Crush Course! Learn PHP Programming

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:

Page 80: PHP Programming: PHP Crush Course! Learn PHP Programming

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).

Page 81: PHP Programming: PHP Crush Course! Learn PHP Programming

3. AddingtheAlbumNameField

Nextwecreateafieldtostorethenameofthealbum.Thedatatypevarcharstandsforvariablenumberofcharacterandstoresastringofupto225characters.

4. AddingtheAlbumArtistField

Thisfieldalsostoresavariablenumberofcharactersanditsstringislimitedtoonly80characters.

5. AddingtheAlbumTypeEnumeratedTypeField

TheenumeratedtypeENUMisastringobjectthathassetofvaluesthatareallowed.Inourcase,theallowedvaluesare‘L’forLongPlay(LP),‘E’forExtendedPlay(EP)and‘M’foramixtape.

Page 82: PHP Programming: PHP Crush Course! Learn PHP Programming

6. AddingthenumTracksField

Ifthisseemswrongtoyou,thenyouhavebeenpayingattention!Thisfieldisusedtostorethenumberoftracksthealbumhasandshouldbeanumerictypeandnotastringtype.Thiswasdoneintentionallytodemonstratehowtochangethedatatypeandnameofafield/columnlaterofinthechapter.

7. AddingDateReleasedField

Thelastlinecreatedstoresthedatethealbumwasreleased.Thedatedatatypeisusedtostoredatevalues.

Page 83: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 84: PHP Programming: PHP Crush Course! Learn PHP Programming

AlteringTables

Sometimeyoucanmakeamistakeormayjustwishtochangesthingsinyourtable.Luckily,youcandosowithMySQLbyalteringthetableusingMySQLstatements.Wewilllookatchangingtableandcolumnnames,andchangingdatatypes.

Firstweneedtolookatthetablewejustcreatedbythetypingfollowingcommandtodescribeourtable.Weshouldbeabletoseeitsstructureinthecommandline:

DESCRIBEAlbum;

Page 85: PHP Programming: PHP Crush Course! Learn PHP Programming

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|+–––––—+

Page 86: PHP Programming: PHP Crush Course! Learn PHP Programming

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!

Page 87: PHP Programming: PHP Crush Course! Learn PHP Programming

DeletingTablesThecodebelowcanbeusedtodeleteatableandallitsdatafromthedatabase:DROPTABLEtable_name;

Wheretable_nameisthenameofthetableyouwishtodelete.

Page 88: PHP Programming: PHP Crush Course! Learn PHP Programming

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?

Page 89: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 90: PHP Programming: PHP Crush Course! Learn PHP Programming

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|

Page 91: PHP Programming: PHP Crush Course! Learn PHP Programming

+–––––––––+––––—+––––—+–––––-+

Page 92: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 93: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 94: PHP Programming: PHP Crush Course! Learn PHP Programming

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|

+––––––-+––––-+–––—+

Page 95: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 96: PHP Programming: PHP Crush Course! Learn PHP Programming

TheORDERBYKeyword

Inordertosorttheresult_set(thetablereturnedbyaSELECTstatement)byoneormorecolumns,weusetheORDERBYkeywordandspecifywhetheritshouldbeindescendingorascendingorder:

SELECTAlbumName,AlbumArtist

FROMAlbums

ORDERBYAlbumArtistASC;

NOTE:Bydefault,theyaresortedinascendingorder.ThismeansthatifweleaveouttheASCkeyword,itwouldnotmakeadifference.WecansortthemindescendingorderbyreplacingASCwithDESCintheaboveexample.

Page 97: PHP Programming: PHP Crush Course! Learn PHP Programming

Thatshouldoutputrecordsinascendingorderbasedonthenameoftheartistofthealbum:

+–––––––––+––––—+

|AlbumName|AlbumArtist|

+–––––––––+––––—+

|DirtyGold|AngelHaze|

|BacktotheWoods|AngelHaze|

|Parachutes|Coldplay|

|ProspektsMarch|Coldplay|

|X&Y|Coldplay|

|RushofBloodtotheHead|Coldplays|

|RandomAccessMemories|DaftPunk|

|1989(DeluxEdition)|TaylorSwift|

+–––––––––+––––—+

Page 98: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 99: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 100: PHP Programming: PHP Crush Course! Learn PHP Programming

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|

+–––+–––––––––+––––—+

Page 101: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 102: PHP Programming: PHP Crush Course! Learn PHP Programming

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;

Page 103: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 104: PHP Programming: PHP Crush Course! Learn PHP Programming

Summary

Okay,nowthatyouarefamiliarwithbasicsofMySQLandcanaccessitusingthecommandlineanduseittocreateanddeletedatabases;create,alteranddeletetables;select,insert,update,anddeletetabledata;anddootherneatthingswithdatalikefilteringitandorderingitthewayyouwantusingMySQLcommands,itisthetimetomoveonandlookathowwecanusePHPandMySQLtogetherandcreateaverysimplewebsitewhereyouaddrecordstoadatabaseofourfavoriteartists.

Page 105: PHP Programming: PHP Crush Course! Learn PHP Programming

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!

Page 106: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 107: PHP Programming: PHP Crush Course! Learn PHP Programming

CreatingFamilyDatabase

OpenupthecommandlineandfireuptheMySQLClientandloginasthe‘root’(seeChapter3).

CreatetheDatabasebyenteringthefollowingcode:CREATEDATABASEFamily;

Thenselectthedatabaseinordertouseit:USEFamily;

Page 108: PHP Programming: PHP Crush Course! Learn PHP Programming

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

);

Page 109: PHP Programming: PHP Crush Course! Learn PHP Programming

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’);

Page 110: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 111: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 112: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 113: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 114: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 115: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 116: PHP Programming: PHP Crush Course! Learn PHP Programming

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>

Page 117: PHP Programming: PHP Crush Course! Learn PHP Programming

</tr>’;

}

echo‘</table>’;

}

else{

echo“Coundnotgetaresponsefromdatabase”.mysqli_error($conn);

}

mysqli_close($conn);

?>

</div>

</div>

</body>

</html>

Page 118: PHP Programming: PHP Crush Course! Learn PHP Programming

Thereisquitealotgoingonherebutwewillnotgetintoitall.Wealsowon’tbediscussinganyoftheHTMLandCSSasthisbookassumingyouhavesomebasicknowledgeofthoseandhowtolinkexternalstylesheets.

Firstly,inthePHPcode,weincludetheconfig.phpfilebycallingtherequire_oncefunctionandpassingthepathtothefileasaparameter(wepassinarelativepathsincetheconfigurationfile).Thiswillallowustoaccessourdatabaseconnectionwedefinedinthatfile:

require_once(‘config.php’);

NextwecreatethequerystringthatwillbeusedtoretrievedatafromdatabaseusingSQLandassignittothevariable$sql:

$sql=“SELECTMemberID,FirstName,LastName,Age,Gender,RelationshipFROMFamilyMembers”;

WeuseaSELECTstatementtoselectthefieldswewishtodisplayfromtheFamilyMemberstablefollowingthesamesyntaxruleswewoulduseonthecommandline.

Page 119: PHP Programming: PHP Crush Course! Learn PHP Programming

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:

Page 120: PHP Programming: PHP Crush Course! Learn PHP Programming

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>’;

Page 121: PHP Programming: PHP Crush Course! Learn PHP Programming

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

Page 122: PHP Programming: PHP Crush Course! Learn PHP Programming

tabledynamically.Neathuh!

Page 123: PHP Programming: PHP Crush Course! Learn PHP Programming

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;

Page 124: PHP Programming: PHP Crush Course! Learn PHP Programming

text-decoration:none;

display:inline-block;

}

a:hover,a:active{

background-color:#AFDCB1;

}

#btn_add{

padding:5px0px;

text-align:right;

}

Page 125: PHP Programming: PHP Crush Course! Learn PHP Programming

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;

}

Page 126: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 127: PHP Programming: PHP Crush Course! Learn PHP Programming

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>

Page 128: PHP Programming: PHP Crush Course! Learn PHP Programming

<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:

Page 129: PHP Programming: PHP Crush Course! Learn PHP Programming

formaction-Thistellstheformtosendtheform-datatothemember_added.phpscript(whichweshallcreateinamoment)thatwillprocesstheinformationwhentheADDbuttonispressed

method=“post”–Tellstheformtosendtheform-dataasanHTTPposttransaction.ThismeansthatthedataisappendedinsidethebodyoftheHTTPrequestURL.Thisisgoodforsendingsensitivedata(thingslikepasswords)unlikethe“get”methodwhichjustappendsthedatatotheURLandanyoneonecanseeit.

Gointothebrowseranddisplaytheindexpage.ClicktheADDbuttonattoprightofthetableandthefollowingpageshoulddisplaywiththeformtoaddfamilymembers:

Page 130: PHP Programming: PHP Crush Course! Learn PHP Programming

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;

}

Page 131: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 132: PHP Programming: PHP Crush Course! Learn PHP Programming

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’;

Page 133: PHP Programming: PHP Crush Course! Learn PHP Programming

}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’];

Page 134: PHP Programming: PHP Crush Course! Learn PHP Programming

}

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

Page 135: PHP Programming: PHP Crush Course! Learn PHP Programming

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”>

Page 136: PHP Programming: PHP Crush Course! Learn PHP Programming

<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>

Page 137: PHP Programming: PHP Crush Course! Learn PHP Programming

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’]);

}

Page 138: PHP Programming: PHP Crush Course! Learn PHP Programming

Wedothisfortherestofvaluesinthe$_POSTarray.

Warning:Thismaynotbethemostsecurewayofverifyingdatabeforeitgoestothedatabase.Forthatweneedtouseregularexpressionsandthatisanadvancedtopic.Wearejusttryingtokeepthingssimple.

Page 139: PHP Programming: PHP Crush Course! Learn PHP Programming

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!”;

}

Page 140: PHP Programming: PHP Crush Course! Learn PHP Programming

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.

Page 141: PHP Programming: PHP Crush Course! Learn PHP Programming

Andwearedone!Nowweshouldbeabletoaddfamilymembersandviewthem.Weshouldalsobeabletonavigatebetweenpagesusingthebuttonsonthetoprightcorneroftheformsortablethatallowyouswitchbetweenthepages.

Startuptheindexpageandgototheformpagetoaddsomedata

Page 142: PHP Programming: PHP Crush Course! Learn PHP Programming

ClicktheADDbuttontoaddthemembertodatabase.Youshouldseethesuccessmessage:

Page 143: PHP Programming: PHP Crush Course! Learn PHP Programming

ClicktheViewMembersbuttontoverify.Thebelowwindowshoulddisplaywiththenewmemberadded:

Page 144: PHP Programming: PHP Crush Course! Learn PHP Programming
Page 145: PHP Programming: PHP Crush Course! Learn PHP Programming

SummarySothereyouhaveit!BeforethischapterwelookedatPHPandMySQLseparatelyandinthischapterwasaimedatconsolidatingthetwo,andshowinghowtousethemtoproducedynamiccontent.Itshouldnotbethathardtomodifythewebsitetodowhateveryouneedittodoasyouarenowcapable.

Inthechapterwecreatedaconfigurationfilethatstoredtheconnectiontothedatabaseanduseditallthroughoutthewebsitetoestablishaconnectiontothedatabaseandqueryittostoreandretrievedata.Wecreatedapagethatenablesyoutoviewinformationaboutthefamilymembersyouhaveaddedtodatabase.WealsocreatedapagewithaformforinputtingthedataandapagethathasthePHPneededtoprocessthedatawhentheformissubmitted.

Page 146: PHP Programming: PHP Crush Course! Learn PHP Programming

Conclusion

“Educationisthekindlingofaflame,notthefillingofavessel.”―Socrates

Thisistheendofthisbook,butnotyourlearning.YoustillhavetogooutthereandlearnwhatotherthingsyoucandowithPHPandMySQLandgetamoreindepthunderstandingoftheconcept.Atthispointthough,IsincerelyhopeyouhavebeenequippedwithenoughknowledgetodowhatisyouneedtodowithabasicunderstandingofPHPandMYSQL.

Inthefirsthour,wecoveredthebasicsofPHPlikecomments,variables,constantsandoperators.ButnotbeforewelearnedhowtoinstalltheserverpackageXAMPPtothathastheApacheservicefortheserver.WerunaPHPscriptanddisplayedneatmessagestothescreen.WealsochoseacooltexteditortowritebeautifulPHPcode.

Page 147: PHP Programming: PHP Crush Course! Learn PHP Programming

Insecondhour,wegotalittledeeperintothebasicsofPHPandlookedathowwecanwriteconditionalstatementsthatallowustoexecuteblocksofcodedependingonaspecifiedcondition.Nextwelookedathowtoloopthoroughcodeuntilacertainconditionismetusingwhileandforloops.Wethenlookedathowweencapsulatedcodeblocksandre-usethemthroughtheprogramusingfunctions.Wepassedinformationtotheintheformofparametersandtheyreturnsomeofitbackafterperformingoperationsonthatinformation.Thenwefinallywesawhowtostorecollectionsofdataintoarraysandhowtoloopthroughthem.

Inthethird,hourwelearnedMySQL.WelearnedhowtobringupthecommandprompttoenterMySQLcommandstoperformvariousoperationssuchascreatinganddeletingdatabases;creating,alteringanddeletingtables;retrieving,inserting,updatinganddeletingthedatainthetables.

InthefourthandfinalchapterwelookedathowwecanusePHPandMySQLtogethertocreatedynamiccontentforasimplewebsiteweweremakingalistofourfavoritefamilymembersandtheirdetails.

Allthisisknowledgefortheabsolutebeginnerwhoneedssomethingtoquicklyguidethemwithclearexamplesandexplanations.IwishyouwellinyourfuturesendeavorsandIbelieveyouarewellonyourwaytoachievingyourdreams.GladIcouldhelp.