128

Table of ContentsTable of Contents Introduction Introduction What is PHP? Introducing PHP Example A little history Installing and Configuring PHP Introduction Windows Users Using Wampserver

  • Upload
    others

  • View
    20

  • Download
    0

Embed Size (px)

Citation preview

TableofContentsIntroduction

Introduction

WhatisPHP?

IntroducingPHP

Example

Alittlehistory

InstallingandConfiguringPHP

Introduction

WindowsUsers

UsingWampserver

MacUsers

HowDoIKnowitisWorking?

OracleVMVirtualBox

InstallingforaWebSite

Exercise

IntroductiontoHTML

Introduction

BasicHTML

BasicElementsofHTML

Tags

NestedTags

Requiredtags

DocType

Head

OptionalTags

MetaTags

UsefulTags

Headers

DIV

Images/Picture

Links

Lists

Exercise

HTMLTables

HTMLTableHeaders

HTMLForms

TheInputtag

HTMLFormActions&Methods

Introduction-BasicPHPSyntax

YourfirstPHP-enabledpage–HelloWorld!

SomeFunRightAway

ACountdownCounter

Exercise

EditorsandStayingOrganized

Editors

MicrosoftExpressionWeb

PhpDesigner

EditRocket

FreeEditors

Includes

Basicexample

HTMLexample

Codeexample

BestPractices

Variables,Numbers,Dates,andStrings

Variables

VariableNamingConventionsandBestPractices

Numbers

BasicArithmetic

CommonArithmeticShortcuts

UsefulNumericFunctions

Strings

UsefulStringFunctions

SourcesofDocumentation

Exercise

HowtoInterpretPHP.NETdocumentation

ReturnValue

FunctionName

Parameters

Dates

Example:CalculatingAgeinYears

VariableScope

ControlStructures

Introduction

if

if…else

Exercise:OpenHours

PHPSwitch

PHPLooping

PHPwhile

PHPfor

Howtouseadatabase,suchasmySQL

Introduction

WhatareDatabases?

GettingStartedwithphpMyAdmin

WhatisphpMyAdmin?

UsingphpMyAdmintocreateadatabase

IntroductiontoSQL

UsingphpMyAdmintocreateaTableinadatabase

Definingourfirsttable

Whatdefinesanautomobile?

Datatypes

Numbers

Characters

Dates

Exercise:CreateaTable

WorkingwithSQLStatements

INSERTStatements

SELECTStatements

WHEREStatements

ComparisonOperators

ORDERBY

UPDATEStatements

DELETEStatements

UsingmySQLandPHPTogether

Introduction

Code!

CodeListing:createdb.php

CodeExplained:createdb.php

Hey,where’stheHTML?

CreatingformstoDisplay,Add,Edit,andDeletedata

Introduction

FormsthatAddDatatoaDatabase

ABasicForm

HTMLCode

FormAction

PHPCode

ABriefTimeOut…includefilesandSQLInjection

IncludeFiles

SQLInjection

FormsthatDisplaySummaryData

Code

CodeExplained

Exercise:TweakingtheSELECT

ImprovingthelookofthetablewithCSS

CSSExplained

Modifyingtheformtolinktothedetailpage

FormsthatDisplayDetailData

Code

CodeExplained

FormsthatEditData

FormsthatDeleteData

Codetodeletedata

CodeExplained

Exercise

SessionVariables

Introduction

Sessions

StartingaPHPSession

UsingSessionVariables

Storeavariable

Retrieveavariable

Checkingforavariable

DestroyingaSession

WorkingwithImages

Introduction

Exercise:ViewingImages

Pullinganunknownnumberofimagesfromadatabase

Exercise:CreateaDatabaseTabletostoreimages

Exercise:Modifytheviewcar.phppagetoshowmultipleimages

Codeexplained

PHPFileUploads

Introduction

CreateanUploadFileform

CreateaScripttoProcesstheUploadedFile

Code:ViewCarsAddImage.php

CodeExplained

PHPQuirksandTips

Introduction

SingleQuotesvsDoubleQuotes

TheEqualSign

ComparisonOperators

SecurityConsiderations

Introduction

BalancingSecurityandUsability

SQLInjection

AdditionalResources

AppendixA:InstallingPHPonaWebsite

HowtoinstallonaWindowsServer

HowtoinstallonaLinuxServer

Author’sNote

ANotefromoneofmyKickstarterBackers….

-PashaKagan,soon-to-bePHPDeveloper

IntroductionIntroductionThisbookisforthedeveloperwhohasjustcomeacrossPHPandiswonderingwhatthebigdealis,andalsoforthenon-programmerwhoisjuststartingout—anddoesn’tknowwheretobegin.

AsConfuciusoncewiselysaid,“IhearandIforget.IseeandIremember.IdoandIunderstand.”Thisbookwillgetyoudoing.Thebookispresentedasacasestudyof“Sam’sUsedCars,”andyou’llbebuildingawebsiteforSam’sbusinessaswegoalong.Takethetimeanddotheexercises.Strugglealittlebeforeyoulookuptheanswers.

Speakingoftheanswers,thecompanionwebsitetothisbookishttp://www.joyofphp.comwhereyoucanfindallthecodesnippets(andanswerstotheexercises)fromthisbook—plussomeextragoodies.Ifyoulikethebook,pleaselocateitonAmazon.comandgiveitafavorablereview.Ifyoudon’tlikeit,orfindsomethingthatyouthinkneedstobefixed,oryouhaveanideafor“MoreJoyofPHP”,[email protected]

WhatisPHP?introducesPHPinitsmanyandvariedcontexts.ItexplainsthedifferencebetweenaPHPserver,aPHPfile,andPHPthelanguage.ItalsodescribesthepointofPHP,whichistocreatedynamicwebpages.

InstallingandConfiguringPHPdescribeshowtoinstallandconfigurePHPonyourowncomputer.Ofcourse,youcan’tdomuchPHPprogrammingifyoudon’thavePHP,sothisisanimportantprerequisitetotherestofthebook.

IntroductiontoHTMLlaysthegroundworkbydiscussingHTML.PHPisalanguagethatmodifiesandgeneratesHTML,soyouhavetoknowHTMLasthefoundationforusingPHPtomodifyHTML.Wecoverrequiredandoptionaltags,plusenoughextrastogetyougoing.

BasicPHPSyntaxIntroducesthelanguageofPHP.HereweshowhowtointerspersePHPandHTMLinthesamefile,andwhattoexpectwhenyoudoso.

SomeFunRightAwaygivesyouachancetotryoutsomePHPbeforewegomuchfurther,togiveyouanearlysenseofthejoyyouaregoingtoexperiencewhenyoumasterit.

EditorsandStayingOrganizedtalksabouthowtoactuallyeditaPHPfile,andguidesreaderstowardsomeofthetoolsavailabletomakeeditingeasy.Also,stayingorganized

isagoodhabittostartoffwith.

NextwediscussVariables,Numbers,Dates,andStrings.ThischaptercovershowtocreateanduseavariableinPHP,aswellashowtoperformarithmeticandusefulnumericfunctions.Itcoversstringsandusefulstringfunctions,andalsocoversdatesanddatefunctions.ItalsodescribeshowtoreadthePHPdocumentationwhenyouneedmore.

ThechapteronControlStructurescovershowtoaddconditionallogictoyourapplication,andhowtoperformrepeatabletasksinanautomatedfashion.

TheChapterHowtouseadatabase,suchasmySQLiscontentheavy.Hereyoulearnwhatadatabaseis,howtableswork,andhowtoworkwithSQLstatements.IalsointroducethetoolPHPMyAdmin,whichisagreattooltohelpyougetstartedwithmySQL.WeintroduceSam,theusedcarsalesman,whowantsawebsitethatallowsvisitorstoseewhatcarshehasforsale,withouthavingtoconstantlytweaktheHTMLofhissite.Sam’sUsedCarswillbeadatabase-drivenwebsite.

InthechapterUsingmySQLandPHPTogetherwebegintotiethetwotopicstogetherandusePHPandmySQLsimultaneouslytocreatetrulydynamicwebsites.

Asweprogressthroughourcasestudy,we’llshiftfromtheorytopractice.ThechapterCreatingformstoDisplay,Add,Edit,andDeletedatastartstoputsomeofourtheoryintopracticebycreatingspecificexamplesofwebpagesthatperformactionsonourdatabase.

SessionVariablesallowyoutocreateavariabletostoreavaluethatyoucanuseanywhereinyourwebsite.Forinstance,whenyoulogintoAmazon.com,you’llnoticethateverypagesays‘Welcome,Alan‘orsomethingsimilar—except,ofcourse,withyournameratherthanmine.SessionvariablesofferonewaytoachievethiseffectinPHP.

Ausedcarwebsitewouldn’tbeofmuchvalueifyoucouldn’tseepicturesofthecars,sointhechapterWorkingwithImageswecoverpowerfultechniquesforusingyourdatabasetoassociatespecificcarswithspecificimages.

PHPFileUploads.Buildingonthepreviouschapteronimages,weextendourwebsite’sfunctionalitytoallowuserstouploadimagesofthecarsdirectlyfromabrowser,ratherthanhavingtocopytheimagestotheharddrive.

Alllanguageshavetheirquirks,andPHPQuirksandTipsintroducessomeofthefeaturesofPHPthatmightseemoddtosome.

Finally,wediscussSecurityConsiderations.Securityshouldn’tbeanafterthoughtwhenbuildingawebapplication,butitdidcomelastinthebookonlybecauseyoucan’tsecuresomethingunlessyoufirstunderstandhowitworks.Don’tskipthischapter!

WhatisPHP?PHPisaprogramminglanguageyoucanusetocreatewebapplications.It’sfree,powerful,relativelyeasytosetupandlearn,andithasextensionsandframeworksavailabletodoalmostanythingyoucouldimagine.Youcangetstartedquickly,andyouwon’toutgrowitlaterwhenyougetreallygoodatit.Inmyhumbleopinion,PHPisagreatlanguagethatwillbewellworthitthetimeandeffortyouputintolearningit.

Frankly,it’sjustplainfuntoo.

Let’sgetstarted.Themostbasicconceptyouneedtograspisthatawebpageisjustabunchoftext,organizedinacertainway,whichisdisplayedbyabrowser.Onlyafewcompaniesmakebrowsers,butmillionsofpeoplemakewebpages—andsocanyou.

Mostcomputerprogramsneedsomewaytoknowifafileisintendedforthemornot.InthePCworld,thisisaccomplishedbyfileextensions.(Bearwithme,thisnextbitisrelevant).Forexample,afilenamed“mybook.docx”isassociatedwithMicrosoftWordbecauseitsextension(thetextfollowingthedot)is“docx”.Similarly,aPowerPointfilemightendwith.pptor.pptx.Otherprogramsalsohavetheirownuniqueextensions.

Awebpagetypically,butnotexclusively,hasanextensionsuchas.htmor.htmltoindicatethatitisanHTMLfile.AnHTMLfilecanbeonyourowncomputer,oronadifferentcomputersomewhereoutontheInternet.Thebrowserdoesn’tcare.Here’sasimpleexampleofanhtmlfileoutontheInternet:http://www.tsowell.com/columns.htm

ThiswasaboutthesimplestwebpageIcouldfind…justtwolinkstootherpages.Noticethatthelastfourcharactersare.htm,whichindicatesthatitisanHTMLfileintendedfordisplayinabrowser.Ifthatfilewereonyourlocalcomputer,forinstanceinyour“MyDocuments”folder,allyouwouldhavetodotoseeitinabrowserwouldbetodouble-clickonit.

Yourbrowserwouldknowhowtodotherestandyouwouldseesomethinglikethis:

Thisparticularfileisnotonyourlocalcomputer,however.ItisonaserveroutontheInternet.Sohowdoesthefilegetintoyourbrowserwhenyouclickonit?Attheriskof

oversimplifyingit,youdon’thavetoworryaboutthatpartsomuch.Theothercomputer,knownasthe“webserver”,hasthefileanditknowshowtogetittoyou.

InthecaseofanHTMLfilesuchasthisone,theserversendsthefileasiswithoutdoinganythingtoit.Inotherwords,thefilethatthebrowsergetsisexactlythesameasthefileonthefilesystem,regardlessofwhetheritwasoriginallyonyourcomputerorontheserver.

Wewouldcallthisastaticwebpage.

IntroducingPHPNowlet’saddPHPtothepicture.PHPhasseveralmeaningsdependingonthecontextinwhichitisused,soI’mgoingtotrytoexplainthemall.Thereisa“PHPserver”,whichisawebserverthatisrunningPHPsoftwareonit.Let’scontrastaPHPserverwitha“plain”server,onethatisnotrunningPHP.A“plain”webserverjusttakesarequestfromabrowser,locatestheappropriatefile,andsendsittothebrowserasis,withnomanipulation.Inotherwords,itonlyservesstaticwebpages.

OnceyouaddPHPtoawebserver,yougetadditionalfunctionality—withouttakinganyexistingfunctionalityaway.TheservercanstillcontinuetosendstaticHTMLfilestothebrowser,butitcanalsomanipulatethefilespriortosendingthemtothebrowser.

Afilethathasbeenmanipulatedpriortobeingsenttothebrowserisreferredtoasadynamicwebpage.

ExampleHere’sanexample.Let’ssayyouhaveawebpageonwhichyouwantedthecurrentdatetoappear.Withastaticwebpage,youwouldhavetogoinandeditthepageeverysingledaytoupdatethedate.Thatwouldgettiresomeprettyquick!

TheHTMLcodewouldlooksomethinglikethis:

WithPHPyoucanlettheservermakethechangesforyou.Inotherwords,PHPcan

dynamicallyaddthecorrectdatetothepageeverytimethepageisservedifyouinsertalittlebitofPHPcodelikethis:

Noticethatthestatictext7thofOctober2012hasbeenreplacedwith<?phpechodate(‘jS\o\fFY’);?>.Whatwedidwassubstitutethestatictextwithcodethatwillbeconvertedintostatictextbytheserver.(Sneakpreview—PHPcodeappearsinlinewithnormalHTMLcodeandisidentifiedbyappearingwithin<?phpand?>tags).

Ifyouhappenedtoopenthosetwofilesusingyourbrowseronthe7thofOctober2012,thetwopageswouldbeexactlythesame.

Butonthe8thofOctober,theservertakesthecodeaboveandturnitintothis:

Andthecoolthingisthatitworkseveryday,withoutanyfurthermanipulation.Areyoustartingtoseethejoy?

Howdoesaserverknowwhetherapageshouldbedynamicorstatic?Anordinaryserveronlyknowsstaticpages.APHPserverknowsthatafileshouldbemanipulated(itisdynamic)ifitis“PHPfile”andthatitshouldnotbemanipulated(itisstatic)ifitisanHTMLfile.

What’sthedifferencebetweenanHTMLfileandaPHPfile?APHPfileisbasicallyjustanHTMLfilewithsomecodeinsideitthattellstheservertoswapoutthecodepartandinserttext(orHTML)initsplace.APHPfileis“just”anHTMLfilethathasbeensavedwithadifferentextension—“.php”.Here’sanexample:http://php.net/manual/en/tutorial.firstpage.php

Whatisthe“extracode”thatgoesinsideaPHPfileinstructingthepagetobe

manipulated?That’sPHPthelanguage,whichtellstheserverhowandwherethepageshouldbemanipulatedpriortosendingittothebrowser.Inotherwords,PHPisaprogramminglanguagethatisusedtocreatedynamicwebpages.

Howdoestheserverknowwhichpartsofthepageshouldbestaticandwhichpartsshouldbedynamic?Ingeneral,theserverleavesthepagealone.However,ifitseesthetext<?phpthenallthetextthatfollowswillbetreatedlikecode,untilitcomestoa?>whichsignalstheservertogobacktosendingthepageasis.

AlittlehistoryPHPwasoriginallycreatedbyRasmusLerdorfin1995.ThemainimplementationofPHPisnowproducedbyThePHPGroupandservesastheformalreferencetothePHPlanguage.PHPisfreesoftwarereleasedunderthePHPLicense,whichisincompatiblewiththeGNUGeneralPublicLicense(GPL)duetorestrictionsontheusageofthetermPHP.

WhilePHPoriginallystoodforPersonalHomePage,itisnowsaidtostandforPHP:HypertextPreprocessor,arecursiveacronym.

InstallingandConfiguringPHPIntroductionBeforeyoucanbeginusingPHP,youneedtohaveacopyofit.Forthepurposesofthisbook,we’regoingtoinstallPHPonyourlocalcomputersoyoucanplayaroundwithitwithouttoomuchfuss.

Notethatapplicationsyouwriteonyourlocalcomputercanonlybeusedonyourlocalcomputer,orbyothercomputersonyourlocalnetwork.

Fortherestofthisbook,wearegoingtoneedApache,MySQL,andPHP.Together,thiscollectionisreferredtoasAMP.WhenyourunthisonLinux,it’scalledLAMP,andwhenyourunitonWindows,it’scalledWAMP.Somepeoplecallthiscombinationa“stack”,andmayrefertothecombinationasthe“LAMPStack”.

Fortunately,thisisaverypopularcombinationandyoudon’thavetofigureitalloutonyourown.

WindowsUsersAsaWindowsusermyself,IcanpersonallyvouchfortheeaseofinstallationanduseandoftheWampServer,whichcanbefoundathttp://www.wampserver.com/en/

“WampServerisaWindowswebdevelopmentenvironment.ItallowsyoutocreatewebapplicationswithApache2,PHPandaMySQLdatabase.WampServeralsoincludesaprogramcalledPhpMyAdminwhichallowsyoutoeasilymanageyourdatabases.”

Aspartoftheinstallation,the“www”directorywillbeautomaticallycreated(usuallyatc:\wamp\www)

Createasubdirectoryin“www”andputyourPHPfilesinsidethatfolder.

UsingWampserverOnceWampserverisinstalled,youstartitbyselectingstartWampServerfromtheWindowsStartmenu,asshownbelow:

IfitisnotonyourStartmenu,searchforprogramsthatstartwithWAM,asshown

below:

ThisaddsadesktopiconontherightsideoftheTaskbar,circledhereinred:

TheiconwillberedifWampServerisnotrunning,andgreenifitisrunning.Clickingontheiconwillbringupapop-upmenu,similartotheWindowsstartmenu.

Clickonthe“localhost”linkintheWampSevermenuoropenyourInternetbrowserandgototheURL:http://localhost

MacUsersXAMPPforMacOSXisthesimplest,mostpracticalandmostcompletewebserversolutionforMacOSX.ThedistributionincludesanApache2webserver,integratedwiththelatestbuildsofMySQL,PHPandPerl.ItcomesasaMacOSXInstallerpackagethatcontainsallthenecessaryfilesandrequiresnodependencies.

IfyouareanexperiencedwebdeveloperoraMacenthusiastwhoneedstorunawebserver,createdynamicwebpagesorusedatabases,thisisyourluckyday!

ThisversionisforMacOSX10.4(Intel&PPC)andhigher.

XAMPPcanbefoundathttp://www.apachefriends.org/en/xampp-macosx.html

HowDoIKnowitisWorking?OK,thatwaseasy,buthowcanyoucheckthateverythingreallyworks?JusttypeinthefollowingURLatyourfavoritewebbrowser:

http://localhost

Windowsuserswillseesomethinglikethis:

Macuserswillseesomethinglikethis:

OracleVMVirtualBoxIfyouareproficientwithcomputers,youmightliketotryoutapre-configuredvirtualmachine.OracleVirtualBoxisfreeforyoutouse,andfolderscanbesharedbetweenthehostandguestmachineallowingyoutosimplysavethefileyouareworkingonandrefreshyourbrowser,there’snoneedtouploadviaFTP/SFTPtotestyourchanges.Ifthissoundslikeagoodoptionforyou,here’salinktoatutorialonsettingitup.UsingOracleVirtualBoxisoutsidethescopeofthisbook.

InstallingforaWebSiteIfyouwantedtomakeyourapplicationavailabletoeverybodyontheInternet,you’llneedtoinstallPHPandyourapplicationontoapubliclyaccessibleserver.ThistopiciscoveredinAppendixA:InstallingPHPonaWebsite.

ExerciseUseyoureditor(forinstance,Programmers’Notepad)tocreateafilecontainingthefollowingline:

Savethefileasphpinfo.phpinthecorrectplaceonyourharddrive(forinstance,C:\wamp\www).

Finally,openthefilewithabrowserbytypinghttp://localhost/phpinfo.php

IntroductiontoHTMLIntroductionAswehavedescribedit,PHPisalanguageusedforcreatingdynamicwebpages.WebpagesarewritteninHTML,andPHPisusedsothattheHTMLinagivenpagechangesdependingoncertainsituationsthatyoudefine.

SincePHPisusedtogeneratetheHTMLonapage,itonlymakessensethatyouneedtounderstandbasicHTMLbeforeyoucangoanyfurther.

CascadingStyleSheets(CSS)isarelatedtechnologyusedtodefinethelookandfeelofanHTMLpage.SometimesCSSisreferredmoresimplyasastylesheet.

IfyoualreadyunderstandHTMLandCSS,youcanskipaheadtothenextchapter.

BasicHTMLHTMListheprimarybuildingblockoftheweb,soitiscrucialtohaveabasicunderstandingofwhatHTMLisandhowitworks.HTMLisamarkuplanguagethatisusedbybrowserssothattheyknowhowtorenderadocumentasawebpage.RegardlessofwhetheradocumentstartsoffasHTMLwrittenbyhandorisgeneratedusingASP,JSP,orPHP,eventuallythedocumentisturnedintoHTMLandsenttothebrowsertoberenderedfordisplaytoaperson.

HTMLisamarkuplanguagethatdefinesthestructureandoutlineofadocumentandoffersastructuredcontent.Markupisnotintendedtodefinethelookandfeelofthecontentonthepagebeyondrudimentaryconceptssuchasheaders,paragraphs,andlists.

ThepresentationattributesofHTMLhaveallbeendeprecated,whichisafancywordfor‘pleasedon’tusetheseanymore,eventhoughtheystillwork’.ThecurrentbestpracticesinHTMLpagedesignstipulatethatmoststyleshouldbecontainedinstylesheets,whichareasetofrulesthatdescribehowapageshouldlook.Stylesheetsareatopicinthemselves,andnotveryimportantatthisstageinyourlearning.However,you’llwanttoputstylesheetsonyourfuturereadinglist.

WritingandviewingHTMLisincrediblyeasy(andfun),whichofcourseisabigfactorinwhatmadeitsopopular.Ifyouarereadingthisdocumentonacomputer,thenyoualreadyhaveeverythingyouneedtotryitoutrightnow.Allyouneedtobuildawebpage(anHTMLpage)isacomputer,atexteditor(somethingassimpleasNotepadwillsuffice)andabrowser.ToworkwithHTML,youdon’tneedaserveroranyspecialsoftwareatall.Yousimplycreatethefile,saveitwithan.htmor.htmlextension,andopenitdirectlyinyourbrowser.

BasicElementsofHTMLAllHTMLbaseddocumentshavethesamebasicelements.Theyarecomposedoftagsthatdefinethevariouspartsofthedocument—fromwhereitstartsandends,andeverythinginbetween.HTMLuseselements(“tags”)tomarkupsectionsoftext.Thesecanincludeheadings,subtitles,lists,boldorunderlinedtextand,ofcourse,links.HTMLdocumentsreadfromlefttorightandtoptobottom.

Tags

Todistinguishtagsfromordinarytext,tagsappearinsidebrackets:<and>.Mosttagshaveanopenandclosetag,alsoknownasastartandendtag.Theopentagstartswith<andendtagstartswith</.Forexample<b>indicatestostartboldand</b>indicatestostop(end)bold.

Forexamplehereisaparagraphelement:

Inthisexamplethe<p>and</p>arethetags:theyareusedtodelineatethetextcontainedwithinasaparagraph.Somethingworthpointingouthereisthatyoudon’thavetoputeverythingonasingleline.Thecodeaboveworksjustaswellasthisbelow:

Infact,theindentationisn’tneededeither,althoughitcertainlyimprovesthereadability.Keepinmindthatsomeone(maybeyou)mayhavetoedityourHTMLinthefuture,somakingitreadableisagoodidea.

Alltagformatsarethesame.Theybeginwithaless-thansign:<andendwithagreater-thansign:>.Always.Whatgoesinsidethe<and>isthetagname.AbigpartoflearningHTMLislearningthespecifictagsandwhattheydo.

NestedTags

Ingeneral,mosttagscanbenestedinsideothertags,butofcoursetheremaybeexceptionstothisrule.

Hereyouseetheboldtagnestedinsideofaparagraphtag:

Notallelementshavebothanopeningandclosingpiece.Forexample,<br>doesn’t

haveacorresponding</br>,andneitherdoes<hr>.

RequiredtagsAnHTMLpagestartswiththe<html>tagandendswith</html>.Thebodyofthepagegoesinsidebodytags.

DocType

Ifawebpageismissinga<DOCTYPE>tagorhassomesortof“transitional”doctypetag,thepagewillberenderedinwhatiscalled‘quirks’mode.Quirksmodeissomewhatunpredictable,andyoudon’talwaysgetwhatyouexpect.

So,itisimportanttohaveadoctypetagifyouwantyourwebpagetodisplayinStandardsmode,asexpected.

Head

TheheadofthedocumentiswheretheTitleandMetainformationwillgo.Generally,youwouldalsoputanyCSSstyles,scripttags,andlinktagstoexternalfilesintheHeadalso,ifyouhaveany.

OptionalTagsMetaTags

TheMetatag,alongwiththelinktag,areuniqueinthattheyaretheonlyHTMLtagsthatrequireneitheraclosingtagnoraclosing/attheendofthetag,andarestillconsideredsyntacticallycorrect.

Theotherthingaboutmetatagsisthattheyaretheonlytagthat,generallyspeaking,hasnoeffectonthelayoutorprocessingofthepage;theyareusedtogiveinformationaboutthepageand/orsitebeingviewed.Themetatagisessentiallyakey/valuepair,andeachtagcanonlycontainonepairofvalues.Metatagsareusedprimarilybysearchengines.

UsefulTagsHeaders

Headersareusedtoorganizeinformationintohierarchicalgroupings.

<h1>Heading1</h1>

<h2>Heading2</h2>

<h3>Heading3</h3>

<h4>Heading4</h4>

<h5>Heading5</h5>

<h6>Heading6</h6>

Headertagsareblock-levelelements,meaningtheytakeupanentirelinebythemselves,andnoothermarkupisallowedinsideheadingtags.

DIV

TheDIVtagisoneyoucanusetocreatealogicaldivisionwithinyourdocument.DIVsworkwithCSS,andallowyoutowriteCSSrulesthatspecifyhowthetextwithintheDIVshouldbeformatted.

Images/Picture

Toaddanimagetoyourdocument,youusethe“image”tag.Toinsertanimageintoyourhtmldocumentusethefollowingsyntax:

Thevaluethatyouputinthe‘src=’attributecaneitherspecifyagraphicthatisonthelocalfilesystem,oryoucanspecifyafullURL,whichretrievestheimagefromsomewhereelseontheInternet.

Links

Alinktakesausertoanotherplacewhentheyclickonit.Thelinkcanbetoaspecificpartoftheopendocumentortoanewpageentirely.

Takestheusertoanewpage.

Takestheusertoadifferentplace(asindicatedbythetag<aid=“top”>)inthecurrentpage:

Lists

Therearetwokindsoflists—orderedandunordered.Anorderedlistisnumbered,suchas1,2,3,whileanunorderedlistisalistofbulletitems.Therearetagstostartandstopthelist,andtagsforeachiteminthelist.

Anorderedliststartswiththe<ol>tag.Anunorderedliststartswiththe<ul>tag.Eachlistitem,regardlessoflisttype,startswiththe<li>tagandendswith</li>.

ExerciseMakeacoupleofbasicHTMLfilesandplacetheminthecorrectlocationonyourcomputersothatyoucanopentheminabrowser.Includelists,paragraphs,andbothboldanditalictext.Ihaven’ttoldyouhowtomaketaskitalic.Giventhatthetagforboldis<b>,whatdoyousupposeisthetagforitalic?

HTMLTablesTablesareawesome.Theysolvealotofproblems,butshouldnotbeusedforoverallpagelayout.HTMLtablesshouldonlybeusedforrenderingdatathatbelongsinagridorinotherwordswherethedatadescribeanumberofobjectsthathavethesameproperties.Forexample,ifitmakessensetodisplaythedatainMicrosoftExcel,useatable.

Tablesaredefinedwiththe<table>tag.Atableisdividedintorows(withthe<tr>tag),andeachrowisdividedintodatacells(withthe<td>tag).tdstandsfor“tabledata,”andholdsthecontentofadatacell.A<td>tagcancontaintext,links,images,lists,forms,othertables,etc.

TableExample

ThisishowtheHTMLcodeabovewilllookoncetranslatedbyabrowser.ThebrowserwilldrawlinesaroundthecellsbecauseIincludedborder=‘1’intheopening<table>tag.

HTMLTablesandtheBorderAttribute

Ifyoudonotspecifyaborderattribute,thetablewillbedisplayedwithoutborders.Sometimesthiscanbeuseful,butmostofthetime,wewanttheborderstoshow.

Todisplayatablewithoutborders,justdroptheborderattribute:

HTMLTableHeaders

Headersinatable(thetoprowwhichdescribesthedataratherthanbeingthedata)aredefinedwiththe<th>tag.

Allmajorbrowsersdisplaythetextinthe<th>elementasboldandcentered.

HowtheHTMLcodeabovelooksinyourbrowser:

Tablescancreateaccessibilityproblems.Becausetablesareinherentlymeanttobereadlefttoright,onerowatatime,usingthemforlayoutcancausescreenreaderstoreadcontentoutoforderandcauseconfusionfortheuserswhorelyonscreenreaders.

HTMLFormsHTMLformsareaspecialkindofHTMLpagethatcanbeusedtopassdatatoaserver.Oncetheservergetsthedata,itmaymanipulatethedataandsendsomeofitback,oritmaystoreitintoadatabaseforlateruse.

AnHTMLformwillcontaininputelementslikelabels,textfields,checkboxes,radio-selectbuttons,submitbuttons,andmore.Aformcanalsopresentlists,fromwhichtheusercanmakeaselection,oratextareawheremulti-linetypingisallowed.

Thebasicstructureofaformisasfollows:

Theformtagsgoinsidethe<body>tag.Thedataintheformissenttothepagespecifiedintheform’sactionattribute.Thefiledefinedintheactionattributeusually

doessomethingwiththereceivedinput:

We’llcovertheformactionslater.

TheInputtag

Themostcommonformelementisthe<input>element,whichisusedtocollectinformationfromtheuser.An<input>elementhasseveralvariations,whichdependonthetypeattribute.An<input>elementalsohasanameelement,soyoucanrefertoitlater.Ingeneral,thesyntaxis:

An<input>elementcanbeoftypetext,checkbox,password,radiobutton,submitbutton,andmore.Thecommoninputtypesaredescribed.

TextFields:<inputtype=“text”>definesaone-lineinputfieldthatausercanentertextinto:

ThisishowtheaboveHTMLcodewouldlookinabrowser:

PasswordField:<inputtype=“password”>definesapasswordfield.Thepasswordfieldisjustlikethetextfield,exceptthetextthatistypedinisnotdisplayedonthescreen.

Apasswordfielddoesn’tsecurethedata,itonlyhidesitfromhumans.

RadioButtons:<inputtype=“radio”>definesaradiobutton.Radiobuttonsletauserselectone(andonlyone)ofalimitednumberofpresentedchoices:

ThisishowtheHTMLcodeabovelooksinabrowser:

Checkboxes:<inputtype=“checkbox”>definesacheckbox.CheckboxesletauserselectZEROorMOREoptionsofalimitednumberofchoices.

SubmitButton:<inputtype=“submit”>definesasubmitbutton.

Asubmitbuttonisusedwhentheuserhasfilledintheform,andisreadytosend(“submit”)thedatatheyhaveenteredtotheserver.Thedataissenttothepagespecifiedintheform’sactionattribute,whichwillbecoveredinthenextsection.

HTMLFormActions&Methods

Whenyoudefineaform,therearetworequiredattributes:actionandmethod.Theactionattribute(action=)indicatesthenameofthefilethattheformwillbesubmittedto.Themethodattribute(method=)specifieshowtheformwillbesubmitted.

Thefiledefinedintheactionattributeusuallydoessomethingwiththereceivedinput,likeputitintoadatabaseorsendbacksomeofthevaluestotheuser.Here’sanexampleofasimpleformwithactionandmethodattributes.

Forthepurposesofthisbook,wewillassumethattheactionattributespecifiesthenameofaPHPfile.Asyouwillsee,thePHPfilespecifiedintheactionattributewill

haveaccesstoallthevaluesintheformthatwassubmitted.

WewillcoverformactionsingreaterdetailinthesectionCreatingformstoDisplay,Add,Edit,andDeletedata.

BasicPHPSyntaxIntroduction-BasicPHPSyntaxAPHPscriptalwaysstartswith<?phpandendswith?>.APHPscriptcanbeplacedanywhereinthedocument.

APHPfilemusthavea.phpextension.APHPfilenormallycontainsHTMLtags,andsomePHPscriptingcode.Beforewegomuchfurther,itisimportanttonotethatPHPiscasesensitive.Besuretofollowthesamecasingyouseeintheexamples.

YourfirstPHP-enabledpage–HelloWorld!Createafilenamedhello.phpandputitinyourwebserver’srootdirectory(C:\wamp\www?)withthefollowingcontent:

Useyourbrowsertoaccessthefilewithyourwebserver’sURL,endingwiththe/hello.phpfilereference.WhendevelopinglocallythisURLwillbesomethinglikehttp://localhost/hello.phporhttp://127.0.0.1/hello.phpbutthisdependsonyourcomputer’sconfiguration.

Ifeverythingisconfiguredcorrectly,thisfilewillbeparsedbyPHPandmagically

transformedintoHTML.Ifallgoeswell,thefollowingHTMLwillbesenttoyourbrowser:

Thisprogramisextremelysimple,andyoureallydidnotneedtousePHPtocreateapagelikethis.Allitdoesisdisplay“HelloWorld”usingthePHPechostatement.However,thisisconsideredtheclassicwaytointroduceaprogramminglanguage–showingusershowtosay“helloworld”.

Notethatthereisnothingparticularlyspecialaboutthisfile.TheserverknowsthatthisfileneedstobeinterpretedbyPHPbecauseyouusedthe“.php”extension,whichtheserverisconfiguredtopassontoPHP.ThinkofthisasanormalHTMLfilethathappenstohaveasetofspecialtagsavailabletoyouthatdoalotofinterestingthings.

ThepointoftheexampleistoshowthespecialPHPtagformat.Inthisexampleweused<?phptoindicatethestartofaPHPtag.ThenweputthePHPstatementandleftPHPmodebyaddingtheclosingtag,?>.YoumayjumpinandoutofPHPmodeinanHTMLfilelikethisanywhereyouwant.

SomeFunRightAwayACountdownCounterSincemostofyouwhopurchasedthisbookdiditbysponsoringtheprojectonKickstarter,youarefamiliarwiththeideaofacountdowntoaspecificdateandtime.Theideaistocreateexcitementandasenseofurgency.

HowwouldyoucreatesuchathinginPHP?Firstweneedtosetourtargetdate—thetimewearecountingdownto.InthecaseoftheKickstarterprojectthatlaunchedthisbook,thetargettimewas30-September-2012.YoucancreateavariableinPHPtoholdthetargettimebyusingthemktime(maketime)functionasfollows:

Next,weneedtogetthecurrentdate.Wecandothatwiththisline:

Ithinkyoucanfigureoutwhatthetime()functiondoesonyourown.:)

Next,wenowhavetofindthedifferencebetweenthecurrenttimeandthetargettime.Todothatwesimplyneedtosubtract:

Sincethetimestampismeasuredinseconds,weneedtoconvertthisintowhateverunitswewant.Ifwewanthourswecandivideby3,600,howeverinourexamplewewillbeusingdayssoweneedtodivideby86,400(thenumberofsecondsinaday.)Wealsowanttomakesureournumberisaninteger,sowewillusetheintfunction.

Whenweputitalltogether,wegetourfinalcode:

ExerciseBuildacountdowntimertoaneventthatissignificantinyourlife.

EditorsandStayingOrganizedEditorsAneditoristhesoftwareyouusetowriteyourHTMLandcodewith.Forinstance,MicrosoftWordistheeditorthatyouusetowritedocuments.Ifyou’regoingtogetseriousaboutlearningPHPandwritingalotofcode,aneditorthatisspecificallydesignedforPHPwillbeveryhelpful.

Iusetwodifferenteditors,dependingonwhatIamfocusedon.WhenIamwritingHTML,ImostlyuseMicrosoftExpressionWeb4.WhenIamwritingPHPcode,IusesoftwarecalledphpDesigner.

MicrosoftExpressionWeb

What’sniceaboutExpressionWebisthatitoffersasplitscreen—HTMLcodeonthetopandthecodeasitwouldberenderedinabrowseronthebottom.Andyoucanmakeeditsineitherpane,anditautomaticallyupdatestheotherone.

PhpDesigner

WhenIamworkingwithPHPcode,IuseaneditorcalledphpDesigner,whichisshownbelow.What’sniceaboutitisthatitcolor-codesPHPtextandHTML,andthismakesitmucheasiertoseewhatyouareworkingon.

EditRocket

ThoseofyouworkingonMacswillprobablylikeEditRocket

FreeEditorsWhenyouarejuststartingout,itmakessensetostartwithfreeeditors.Then,ifyoulikeworkingwithPHP,itisaloteasiertojustifyspendingmoneyonaneditorbecauseyouknowthatyou’lluseit,andyouwillhaveabettersenseofwhatyouarelookingfor.

Programmer’sNotepadisagoodallpurposeeditor.Notepad++isanotherone.

Dev-PHPisaPHP-specificeditor.

TextWranglerisagoodeditorfortheMac.

Includes

OneofthegreatestfeaturesofPHPistheincludestatement(andtherelated“require”statement).

Whatthisfeatureenablesisthatyoucantakethepartsofapagethatwouldotherwiseberepeatedoverandoverinmultiplepagesandputthosepartsintoaseparatefile,whichyoucaninsertanywhereyouwouldlikeitjustbyusingtheincludestatement.

Usingincludefilescansavealotofwork.Forinstance,ifyourwebsitehasastandardheaderorfooter,orifithasamenufornavigation,thoseelementswouldlikelyappearonvirtuallyeverypage.WithordinaryHTML,thatmeansalotofduplicatedcode.Duplicatedcodeisfine,untilyouneedtochangeit—thenitbecomesamajorpain.

WithPHPandanincludefile,youonlyhavetochangethefileitself,andeverypagethatreferstoitwillbeupdatedautomatically.

Basicexample

Assumeyouhaveafilecalled‘top.php’whichcontainsthehtmlthatyou’dliketoappearonthetopofseveralpages.Youcouldeasilyincludeitonapagelikethis:

HTMLexample

Let’ssayyouhaveastandardmenuthatshouldappearonseveralpages.Here’sthecodethatmakesupthemenu:

Foreverypageonwhichyouwantthemenu,justincludetheredhighlightedtext:

Codeexample

AssumewehaveanincludefilewithsomePHPvariablesdefined,andthatthisfileiscalled(“variables.php”):

Thenthevariablescanbeusedinthecallingfile:

BestPractices

Usingincludefilesisabestpractice.Thelesscodeyouhavetorepeat,thebetter.You’llseethesamplecodethatgoesalongwiththisbookmakesextensiveuseofincludestatements.

Variables,Numbers,Dates,andStringsVariablesAvariableisaplacewhereyoucanstorethings,suchasanumber,adate,orsometext.Youputtextornumbersintovariablessoyoucanretrievethemlater,orsoyoucanmanipulatethem.Variablesarecalledvariablesbecausethevaluethattheyholdcanvary.Hence,variablesarevariable.:)Forexample,tostorethevalue3.89inavariabletotrackthepriceofgasoline,thefollowingsyntaxwouldapply:

Storingthepriceofgasisagooduseofavariablebecauseweknowthepriceofgasolineisanythingbutstatic!Onadifferentdayyourvariablemightcontainadifferentvalue:

Althoughintheoryyoucannameyourvariablejustaboutanythingyouwant,itisabestpracticetogiveyourvariablesanamethatmakestheirpurposeeasyforhumanstounderstand.

Forinstance,inPHPitwouldbeperfectlyOKtonameyourvariables$a,$b,and$ctostoreinformationaboutthecolor,model,andyearofanautomobile,doingsowouldnotresultinveryreadablecode.Seehttp://www.joyofphp.com/variables-bad-form/

Whilethecodeabovemaybesyntacticallycorrect,itisfarbettertotakeamomentortwoandthinkaboutthepurposeofyourvariablesandnamethemfortheirpurpose.Comparetheabovewiththefollowingcode,whichhastheidenticaloutputasthepreviouscode:

Seehttp://www.joyofphp.com/variables-good-form/

Wouldn’tyouagreethatthesecondstyleofcodingisfareasiertoreadandfollow?Inasmallexamplelikethisitdoesn’treallymatterthatmuch,butasyoustartwritinglongerandmorecomplexcode,namingconventionswillmakeabigdifference.

Youdon’thavetodeclareavariableinPHPpriortousingit.Thevariablewillexistassoonasyouassignavaluetoit.

Notethatwhenyouassigntexttoavariable,youputthetextinquotes.

VariableNamingConventionsandBestPracticesVariablesinPHParerepresentedbyadollarsignfollowedbythenameofthevariable.Thevariablenameiscase-sensitive,meaningthatPHPwouldtreat$priceand$Priceastwodifferentvariables.Ican’toveremphasizethisasapossiblesourceofconfusion—variablenamesarecasesensitive,sopayattention.

VariablenamesfollowthesamerulesasotherlabelsinPHP.Avalidvariablenamestartswithaletterorunderscore,followedbyanynumberofletters,numbers,orunderscores.

Whenitcomestobestpracticesfornamingyourvariables,thereareseveralwaystodoit.Oneschoolofthoughtsuggeststhateveryvariableandthefirstwordineveryvariablestartwithacapitalletter,suchas$GasPrice.Otherswouldprefer$gas_price.Itdoesn’treallymatterwhichmethodyouselect,butwhatdoesmatteristhatyouareconsistent.

NumbersIthinkweallknowwhatnumbersare.InPHP,youdon’thavetodeclareinadvancewhetheravariablewillholdanumber,string,ordate.Whenyoudeclareavariableandassignanumbertoit,PHPknowsitisanumber.Therearemanyfunctionsyoucanusetomanipulatenumbers.

BasicArithmetic

+Theadditionoperator

-Thesubtractionoperator;canalsobeusedfornegationlikethis-9

*Themultiplicationoperator

/Thedivisionoperator

%,themodulusoperator,returnstheremainderafterdivision.Forexample,25%3wouldgiveus1.

Youcanassigntheresultofanexpressiontoavariable,andyoucanusevariablesinexpressions.Ifyouwantedtofigureouthowmuchitwouldcosttofillatankofgasoline,youmightwritePHPcodelikethis:

CommonArithmeticShortcuts

+=addsavaluetothecurrentvariable.Forinstance,$a+=1addsonetothevariable$a.

-=subtractsavaluefromthecurrentvariable.Forinstance,$a-=1subtractsonefromthevariable$a.

UsefulNumericFunctions

Therearemanyfunctionsrelatedtonumbers.Hereareafewofthemostcommonanduseful:

abs()returnstheabsolutevalueofanumberpi()returnsthevalueofpiround()roundsanumbertothenearestintegersqrt()returnsthesquarerootofanumber

Ithinkyougettheidea.Ifyouneedanumericfunction,theoddsareveryhighthatPHPhasthat.

StringsAstringisasequenceofcharactersthatarenotnumbers.Inasimplerexplanation,itistext.Anycombinationoflettersandspacescanbeconsideredastring.Thissentenceisastring.

InPHP,itmattersifyoucreateastringsurroundedbysinglequotesordoublequotes.Ifyouencloseastringwithinsinglequotes,PHPwillreturnthatexactstring.Whenyouencloseastringindoublequotes,anyvariableswithinthestringwillbesubstitutedfortheirvalues.

UsefulStringFunctions

ThereisavastarrayoffunctionsinPHPthatcanbeusedtomanipulatestringvariables.Hereareafew:

htmlentities()ConvertsastringtoitsHTMLequivalent

html_entity_decode()ConvertsHTMLcodebacktoastringstr_pad()Padsastringtoanewlengthstr_repeat()Repeatsastringaspecifiednumberoftimesstr_replace()Replacessomecharactersinastring(case-sensitive)strtoupper()convertsastringtoalluppercase

Onceagain,Ithinkyougettheidea.Ifyouneedstringfunction,oddsareveryhighthatPHPhasthat.

SourcesofDocumentationTwogreatsourcestofindspecificfunctionsarehere:

http://www.w3schools.com

http://www.PHP.net

WhenyouvisitPHP.net,attheupperrightcornerofeverypageisasearchbox.Justtypethenameofafunctionhere,oranythingyou’relookingfor,andPHP.netwillreturnalistofpagesthatarerelevant.

Exercise

TrysearchingbothPHP.Netandw3schools.comfor‘substr’.

HowtoInterpretPHP.NETdocumentation

Whenviewingafunctionalreferencepageyouneedtounderstandhowthesyntaxisrepresentedinthedescription,which,inthecaseofthesubstrfunction,willlooklikethis:

Thismaylooklikegibberishatfirst—itcertainlydidtome.Butonceyoulearntodecodeit,you’llseethatitisallthatyoushouldneedtounderstandhowtousethisfunction.Here’sanannotatedversion:

Thedescriptionofwhatafunctiondoesisnotalwaysveryclearatfirst,butasyoureadthroughtheexamplesthatfollow,itbecomeseasiertounderstand.

Thesubstrfunctioncanbebestthoughtofas“substring”or“subsetofastring”.Ingeneral,functionnamesareshortenedversionsofwhattheyactuallydo.Substrletsyouextractpartofastring.

Let’swalkthroughhowtointerpretthefunctionsyntax,shownbelowagaininblue.

Fromlefttoright:

ReturnValue

Totheleftofthefunctionname(substr)isthereturnvalue(string).

Areturnvalueiswhatyougetbackwhenyourunthefunction.Inthiscase,thisfunctionwillreturnastringvalue.Otherfunctionsmayreturnintegers,arrays,objects,etc.Insomecases,youwillseeafunctionreturnsomethingcalledbool,whichisshortforboolean,andthismeansthefunctionwillreturneitherTrueorFalse.

Ifyouseeafunctionthatreturnsvoid,thenthismeansthatnothingisreturned.“Void”MixedmeansthatthefunctioncanreturnamixtureofreturntypeslikeInteger,String,Array,etc.

FunctionName

Thenextpartisthenameofthefunctionitself.Intheblueboxabove,andonthephp.netwebsite,thenameofthefunctionisinboldtext.

Parameters

Thenextpartistheparameterspassedtothefunctionseparatedbycommas.Ineachcase,thereisanexampleofwhattypeofvaluethatshouldbepassed.InthecaseoftheSubstrfunction,thefirsttwoparametersarestring$string,andint$start.Thismeansyoupassthesubstrfunctionastringandaninteger.$stringisthestringyouwantasubsetof,and$startisthepositionwhereyouwanttostartlooking.

Sometimesyouwillseeavaluesetwithinthesyntax.Thismeansthatthisisthedefaultvalue.Inothercases,theparametersarewithinsquarebrackets.Thisindicatesthatthe

parameterisoptional,anddoesnotneedtobeset,butyoucanuseitifyouwantto.

Asyouscrolldowninthedocumentation,youwillseeincreasinglyobscureusesforagivenfunction.Forinstance,inthecaseofsubstr,youcanpassnegativenumberstoeitherofthenumberparameters,anditwillcountfromtheendofthestring,ratherthanthebeginning.Useful?Sure.Common?Notsomuch.

Hereisasimpleexampleuseofthesubstrfunction.

Thiswouldprintout‘Hello’becausethefirstfivecharactersof‘HelloWorld’are‘Hello’.

DatesThereisawidevarietyofdatefunctionsinPHP,withthemostobviousonebeingsimplydate().

Thedatefunctionallowsyoutoformatadateinvirtuallyanywayyoucouldpossiblyimagine.Thefirstparameteristheformattingstring,whichyoucanbuildusinganycombinationofthefollowingcharacters:

ToFormatDays

d–returnsthedayofthemonthas2digitswithleadingzeros,suchas01to31.

D–returnsatextualrepresentationofadayasthreeletters,suchasMonthroughSun.

j–returnsthedayofthemonthwithoutleadingzeros,suchas1to31.

l(lowercase‘L’)–returnsafulltextualrepresentationofthedayoftheweek,suchasSundayorSaturday.

N–returnsanISO-8601numericrepresentationofthedayoftheweek(addedinPHP5.1.0)suchas1(forMonday)through7(forSunday).

S–returnsanEnglishordinalsuffixforthedayofthemonthas2characterssuchasst,nd,rdorth.Youwouldusethisinconjunctionwithwithj(above)ifyouwantedtocreatesomethinglikethe1stofJanuary.

w–returnsanumericrepresentationofthedayoftheweek,suchas0(forSunday)

through6(forSaturday).

z–returnsthedayoftheyear(startingfrom0)suchas0through365.

ToFormatWeeks

W–returnsanISO-8601weeknumberofyear,weeksstartingonMonday(addedinPHP4.1.0)suchas32(forthe32ndweekintheyear).

ToFormatMonths

F–returnsafulltextualrepresentationofamonth,suchasJanuaryorMarch.

m–returnsanumericrepresentationofamonth,withleadingzeros,as01or12.

M–returnsashorttextualrepresentationofamonthasthreeletters,asJanorDec.

n–returnsanumericrepresentationofamonth,withoutleadingzeros,suchas1,2or12.

t–returnsthenumberofdaysinthegivenmonth,suchas28,29,30,or31.

ToFormatYears

L–returnswhetherit’saleapyearas1ifitisaleapyear,0otherwise.

o–returnsanISO-8601yearnumberwith4digits.ThishasthesamevalueasY,exceptthatiftheISOweeknumber(W)belongstothepreviousornextyear,thatyearisusedinstead.ThisoptionwasaddedinPHP5.1.0.

Y–returnsafullnumericrepresentationofayear,againusing4digits.

y–returnsatwodigitrepresentationofayear.

ToFormatTime

a–returnslowercaseamorpm.

A–returnsuppercaseAMorPM.

g–returns12-hourformatofanhourwithoutleadingzeros.

G–returns24-hourformatofanhourwithoutleadingzeros,as0through23.

h–returns12-hourformatofanhourwithleadingzeros,as01through12.

H–returns24-hourformatofanhourwithleadingzeros,as00through23.

i–returnsminuteswithleadingzeros,as00to59.

s–returnsseconds,withleadingzeros,as00through59.

ToFormatTimeZones

e–returnstimezoneidentifier(addedinPHP5.1.0),suchasUTC,GMT,Atlantic/Azores.

I(capitali)–returnswhetherornotthedateisindaylightsavingtimeas1ifitisDaylightSavingTime,and0otherwise.

O–returnsthedifferencetoGreenwichtime(GMT)inhours,suchas+0200.

P–returnsthedifferencetoGreenwichtime(GMT)withcolonbetweenhoursandminutes(addedinPHP5.1.3),suchas+02:00.

T–returnsthetimezoneabbreviation,suchasEST,MDT,CET,etc.

ToFormatFullDate/Time

c–returnsanISO8601date(addedinPHP5)suchas2013-02-12T15:19:21+00:00.

r–returnsanRFC2822formatteddate,suchasThu,21Dec200016:01:07+0200.

U–returnsthenumberofsecondsthathavepassedsincetheUnixEpochtime,whichisJanuary1197000:00:00GMT.

Unrecognizedcharactersintheformatstringwillbeprintedas-is.TheZformatwillalwaysreturn0whenusinggmdate().

Example:CalculatingAgeinYears

Assumingthataspartofaregistrationprocedureyouaskedforabirthday,thisfunctionwillreturntheirageinyears.

SeetheexamplescriptAgeInYears.php

VariableScopeThescopeofavariabledefineswherethevaluecanbeaccessed.Ifavariableisdeclaredonitsownlineonapage,itisavailableanywhereonthatpage.Ifavariableisdeclaredwithinafunction,itwillonlybeavailablewithinthatfunction.

Ifyouwantaparticularvariabletobeavailableeverywhere,declareitusingtheglobalkeyword,suchas

global$a=‘Hello’;

Thereisaspecialkindofvariablethatcanbeaccessedoneverypagethatmakesupyourwebapplication.ThistopiciscoveredinSessionVariables.

ControlStructuresIntroductionThewholepointofPHPistomakeawebpagedynamic.Dynamicmeansthatyoudon’tnecessarilygetthesameresultwhenyouviewthesamepagefromtimetotime.Sometimesthewebpagewilldisplayonegroupoftext,andothertimesitwilldisplayanothergroup.Controlstructuresallowyoutocontroltheconditionsthatspecifytherulesthatdefinewhenandhowthishappens.

ifTheifstatementisoneofthemostimportantfeaturesofmanylanguages,PHPincluded.Itallowsforconditionalexecutionofcodefragments.InPHP,thesimpleformoftheifstatementisasfollows

Theexpressionisevaluatedtoitsbooleanvalue.IfexpressionevaluatestoTRUE,PHPwillexecutestatement,andifitevaluatestoFALSE–PHPwillignoreit.

Ifyouwouldliketoexecutemultiplestatementsiftheconditionistrue,thengroupthestatementswithinacodeblockusingthecurlybraces,asshown

Thefollowingexamplewoulddisplay‘aisbiggerthanb’if$aisbiggerthan$b:

if…elseOftenyouwillwanttoexecuteastatementifacertainconditionismet,andadifferentstatementiftheconditionisnotmet.Thisiswhattheelsestatementisfor—fordefiningtheactioniftheconditionisnotmet.

Moreformally,elseextendsanifstatementtoexecuteastatementincasetheexpressionintheifstatementevaluatestoFALSE.

Forexample,iftodayisMondaythestoreisclosed.Otherwiseitisopenfrom10AMto9PM.Thefunctiondate_default_timezone_setdefineswhichtimezonetouse.

Exercise:OpenHoursLet’sassumethatyourunastoreofsomekind(agym,adonutshop,afarmstand,usedcarlot,whatever),andthehoursitisopenvaryeachday.SaturdaysandSundaysarethebusiestdays,soitisopenfrom9AM–9PM.Mondayisyourdayoff,andtherestoftheweek,thehoursare10AM–6PM,exceptinthesummer(JulyandAugust)whenyoustayopenuntil7PM.

YouwouldlikethehomepageofyourwebsitetoprominentlydisplayToday’sHours,similartothescreenshotbelow:

PHPSwitchTheswitchstatementissimilartoaseriesofIFstatementsonthesameexpression.Onmanyoccasions,youmaywanttocomparethesamevariable(orexpression)withmanydifferentvalues,andexecuteadifferentpieceofcodedependingonwhichvalueitequalsto.Thisiswhattheswitchstatementisfor.

PHPLoopingPHPwhile

ThewhileloopisoneofthesimplesttypesofloopsinPHP.Basically,itcontinuestodosomethingaslongasaconditionistrue.

Thebasicsyntaxofawhileloopisasfollows:

Here’sanexample:

Thiscodewouldprintoutthenumbers1to10.Acommonuseofawhileloopistocontinuetoprintsomethingaslongasyouhaddatabaserecordstoprocess.

PHPfor

Forloopsareabitmorecomplex.Thesyntaxforaforloopisasfollows:

Thefirstexpression(expression1)isexecutedonce,nomatterwhat,atthebeginningoftheloop.

Atthebeginningofeachiterationthroughtheloop,expression2isevaluated.Ifexpression2evaluatestoTRUE,theloopcontinuesandthenestedstatement(s)areexecuted.IfitevaluatestoFALSE,theexecutionoftheloopends.

Attheendofeachiteration,whichistosayafterallthestatementshavebeenexecuted,expression3isexecuted.

Considerthefollowingexample,whichalsodisplaysthenumbers1through10:

Here’showitworks.Expression1assigns$ithevalueof1.Thishappensnomatterwhat.Expression2teststoseeif$iislessthan10.Since1islessthan10,PHPexecutesthestatementsthatfollow.If$iwasnotlessthan10,noneofthestatementswouldhaveexecuted.

Inthiscasethereisonlyonestatement,whichisecho$i.’<br>’.Afterthestatement(s)haveexecuted,itexecutesexpression3,whichincrements$ibyone.Now$iis2,whichislessthan10,soitechoes2,andsoon.

Howtouseadatabase,suchasmySQLIntroductionSuretheideaofdynamicwebpagesiscool,butyoucanonlygofarwithwhat’sbuiltintoPHP,likechangingthepagebasedonthedayoftheweek.Whatyou’dreallyliketodoismakeawebpageuniqueforeachvisitor,andthat’swheredatabasescomein.

WewillbeginthischapterassumingthatthereaderhasabsolutelynoknowledgeofMySQLordatabases.First,we’llexplaindatabases,thenwe’llcreateonetheeasyway—usingphpMyAdmin.Thenwe’llcoverhowtocreatedatabasesandtablesusingSQL,andinthenextchapterwe’llshowhowallthiscanbedoneusingPHP.

WhatareDatabases?Let’sbeginourtutorialwithanintroductiontoourtestsubject,Sam,whorunsausedcardealership.Whenhefirststartedhisbusiness,heonlyhadafewcars—sokeepingtrackofthemwasprettyeasy.Butafterawhile,hisdealershipbegantogrow.Soonhehad10carsonhislot,andayearlaterhehad25cars.

Everycarhasanumberofuniqueattributestotrack,suchmake,model,color,year,VIN,numberofpassengers,bodystyle,MPG,acquisitioncost,askingprice,etc.Asyoucanimagine,atsomepointahumanjustcan’tkeeptrackofallthatinformation,andevenifSamcouldkeepitallstraight,healsoneedstoconveythatinformationtohissalespeople,whodon’talwayshavethesamepassionforSam’sbusinessthatSamhas.SoSamneedstheabilitytoquicklyprintouta“CheatSheet”foreachcarthatasalespersoncanrefertowhenaprospectwandersontothecarlot.

Andofcourse,Samwouldreallyliketohaveawebsitethatallowspeopletosearchforthetypeofcartheywanttoseeifhehasanycandidates,andtobrowsealltheavailablecarsthathehas—which,ofcourse,isalwayschanging.

Becausetheinventoryofcarsisalwayschanging,astaticwebsiteisn’tgoingtobethesolution.Adatabase-basedwebsiteisthesolution.

Databaseshelptoorganizeandtrackthings.Databasesallowyoutousecreativitytogroupthingstogetherinmeaningfulways,andtopresentthesamesetofinformationindifferentwaystodifferentaudiences.

Databasesarecomposedofoneormore“tables”.Tablesarecomposedofpartscalled“rows”and“columns”similartowhatyouwouldseeinaspreadsheet.Thecolumnssectionofeachtabledeclaresthecharacteristicsofeachtablewhileeachrowcontainsuniquedataforeachelementinthetable.

Itmaysoundcomplicatedbutactuallyitisquitesimple.Taketheexamplebelow,whichisonewaythatSamcouldbegintoorganizehiscarcollection.(Notethatforbrevity,notallpossiblecarattributesareshown.)

Table:Cars

WecanclearlyseethattheelementsinthistablehassevencolumnsdefinedasID,VIN,Make,Model,Style,Year,andPrice.Thetablehasfourrowsthatdescribefourdifferentcars—aFordExplorer,DodgeRAM,Mazda6,andaSubaruOutback.

Hereisaquickreviewofwhatwehavelearned.

Tablesarejustacollectionofthingsthatyouwanttokeeptrackof.Tablesconsistofrowsandcolumns.Columnsholdthedifferentattributesofeachelementinthattable.Rowsinatableholddifferentinstancesuniquelydefinedbythetable’scolumns.Databasesareacollectionoftables.

GettingStartedwithphpMyAdminRecallfromthesectionHowDoIKnowitisWorkingonpage23thatifyounavigatetohttp://localhostyouwillseeapagethatwascreatedbyyourlocalserver.InmycaseitisWAMPSERVER.

AtthebottomofthepageyoushouldseealinkforYourAliases

IamnotsureifMacsseethis,butifyoudon’tseethelink,justenterthisaddressintoyourbrowserorclickonthislink:http://localhost/phpmyadmin/

Clickingthatlinkshouldtakeyoutoapagethatissimilartothis:

WhatisphpMyAdmin?

phpMyAdminisafreesoftwaretool—thatjusthappenstobewritteninPHPitself—thatisintendedtohandlemanycommonadministrationtasksofMySQLusingabrowser.phpMyAdminsupportsawiderangeofoperationswithMySQL.Themostfrequentlyusedoperationsaresupportedbytheuserinterface(managingdatabases,tables,fields,relations,indexes,users,permissions,etc),andyoustillhavetheabilitytodirectlyexecuteaSQLstatementifyouprefer.

phpMyAdmincomeswithagoodsupplyofdocumentation,andusersarewelcometoupdatethewikipagestoshareideasandfeedback.ThephpMyAdminteamwilltrytohelpyouifyoufaceanyproblem,butIhaven’tpersonallyhadanyproblemswithit.Whatitdoes,itdoeswell.

UsingphpMyAdmintocreateadatabase

FirstnavigatesuchthatyouhavephpMyAdminonthescreen.ClickonthelinkthatsaysDatabases:

IntheboxthatsaysCreatenewdatabase,typetheword‘Cars’,thenclickontheCreatebutton.Ifitworkedproperly,youshouldseeayellowconfirmationboxappearonthescreenbriefly,asbelow:

IntroductiontoSQL

ThisisequivalenttoissuingtheSQLcommand

and,infact,phpMyAdminactuallyexecutedthatexactSQLcommandinthebackgroundforyouwhenyouclickedonthebutton.Inotherwords,youcanthinkofphpMyAdminasatoolthatbuildsSQLcommandsforyou.

UsingphpMyAdmintocreateaTableinadatabase

Nowthatthedatabaseiscreated,wewouldliketouseit.Findthecarsdatabaseinthelistofdatabases,thenclickonthedatabasename.

phpMyAdminwillprovideapagesimilarto:

ThisistheequivalenttotheSQLcommand:

ThistellstheMySQLdatabasethatyouaregoingtoworkinthedatabase*cars*untilyousayotherwise.

Youhavejustcreatedthedatabaseforourfictionalusedcarlot.Wewilldevelopthisdatabasemoreaswegoalong.

DefiningourfirsttableSofar,youhavecreatedyourdatabase,andfiguredoutthegeneralstructureofPHPMyAdmin.Nowyouwillneedtoputatableinsideofthedatabaseyouhavecreated.Inthecaseofourcarsdatabase,wewillneedtodefinethetabletodescribethecarsandtrucksthatSamhasforsaleonhisusedcarlot.

Here’sascreenshotthatItookfromwww.cars.comthatdescribesacar.

Beforecreatingyourtable,thinkaboutwhatyouaregoingtoputintothetableandwhatarethevariousattributesthatmightdistinguishonerow(car)fromanother.

Whatdefinesanautomobile?

Icanthinkofanumberofpropertiesorattributesthatdistinguishonecarfromanotheronausedcarlot.

VehicleIDNumber(VIN)YearMakeModelTrimExteriorcolorInteriorcolorAskingPricePurchasePriceMileageTransmissionPurchaseDateSaleDateSalePrice

Thatshouldbeenoughtoatleastletusgetstarted.Nowwehavetofigureoutwhatkindofdatawearegoingtoputinthesecategories.

DatatypesForlearningpurposes,therearereallyonlythreetypesofdatayouwillneedtouse.Theyare:

1.Numbers

2.Characters

3.Dates

Numbers

Numbers,asthenameprobablygivesaway,areanykindofnumericinformation.Will

youneedtouseanykindofdecimalsforthedatathatyouaregoingtostore?Inthatcase,youwillneedtousethedatatypedecimalorfloat.Ifnot,youcanusethedatatypeint(shortforinteger)orbigint(abiginteger—whichtakesupmorespace,butcanhandlebiggernumbers).

Characters

ThecharactertypeinMySQListhedatatypeyouusetostoreStrings.Charactersareusedtostoretherepresentationofaletter,word,orseriesofwords.ForexampletheletterAandthephrase‘HelloWorld’wouldbothbeofacharactertype.MySQLcallsthisaVARCHAR,shortforvariablecharacters.Itisvariablebecauseyouonlysetthemaximumnumberofcharactersthatthefieldcanhold,andifyouputinavaluewithfewercharacters,theshortervaluewillbestored.Otherdatabases,suchasMicrosoftSQLServer,offertheCHARdatatype,whichwillfillinanyunusedcharacterswithspaces.WhyanyonewouldwantthatIcan’timagine,soforsimplicitywe’llsticktoVARCHARfornow.

Usethedatatypevarchar(n)todefineacolumnthatyouwouldliketorepresentwithacharacter.Substitutetheninvarchar(n)withthemaximumamountoflettersacolumninyourtablecanhave(upto255).Spaces,tabs,andnewlinesinaparagraphallcountascharacters.

Dates

Datesareawaytostoredatesinthedatabase.Doyoujustwanttostorethedateandnotthetime?Usethedatatypedate.Doyouwanttostorethetimeandnotthedate?Usethedatatypetime.Wanttostorethedateandthetime?Usethedatatypedatetime.

Let’slookbackatourcharacteristicsofcarstodecidewhatkindofdatatypetheyshouldbe.

VehicleIDNumber(VIN)–Allover-the-road-vehicleshavea17-characterVIN,whichdoesnotincludethelettersI(i),O(o),orQ(q)(toavoidconfusionwithnumerals1and0).Varchar(17)Year-Consistsofnumberswithoutadecimalpoint.IntMake–Consistsoftext.Varchar(25)Model–Consistsoftextandtheoccasionalnumber.Varchar(25)Trim–Consistsoftext.Varchar(25)Exteriorcolor–Consistsoftext.Varchar(25)Interiorcolor–Consistsoftext.Varchar(25)AskingPrice-Consistsofnumberswithdecimalpoint.DecimalPurchasePrice-Consistsofnumberswithadecimalpoint.DecimalMileage-Consistsofnumberswithoutadecimalpoint.IntTransmission–Consistsoftext.Varchar(25)Purchase(Acquisition)Date-DateSaleDate-Date

SalePrice-Consistsofnumberswithoutadecimalpoint.Int

Thataboutsumsupthetablethatweneedtocreatetotrackourcars.SincetheVINistheonlytrulyuniqueelementinthelist,wewillmakethisthe“PrimaryKey”.

Definingacolumnasaprimarykeymeansthatthecolumnwillonlybeabletohaveuniquevalues(i.e.nothingcanrepeatitself).Inthecaseofthisspecifictable,itmeansthatyoucan’tentertwocarswiththesameVINintothedatabase,becausewehavejusttoldmySQLthatthisisn’tallowed.Someexamplesofthisineverydaylifearelicenseplatenumbers,creditcardnumbers,andsocialsecuritynumbers.Allofthesenumbersaresupposedtouniqueforeachperson.Thesameconceptappliestotablesindatabases.Wheneverpossible,itisgoodpracticetomakesurethatthetableyouarecreatingcontainssomeformofprimarykeytogivesomethingtouniquelyidentifyarow.

HowdoImakeatablewiththisinformation?Greatquestion.AlthoughwecreatedthedatabaseusingthephpMyAdminwizard,fromnowonwe’rejustgoingtouseSQL.

InyourwindowwithphpMyAdmin,makesurethatthecarstableisselected(seeitcircledinredbelow),thenclickontheSQLtabtobringupthecommandbox.Makesurethatyouseelocalhost->carsabovethebox.Ifyoudonot,justclickonthecarslinkontherightsideandthentheSQLtabtogetyourselfthere.

Typethefollowingcommandintotheboxandclickgo.

Congratulations!YouhavecreatedtheINVENTORYtable.

Here’sanincrediblyusefultip:Clickthelink“CreatePHPCode”locatedontherightsideofthescreenandwhatyou’llgetbackis:

ThereasonthereissuchalinkisbecauseanythingyoucandoinmySQLusingaSQLcommand,youcantellPHPtodoforyouincode.ThisrepresentsavalidlineofPHPcodeinwhichthevariable$sqlisassignedastringvaluetoholdtheSQLstatement.Ofcourse,thereismorethatwouldneedtobedonebeyondthissinglelineofcode,butdon’tworry—wewillcoverthisshortly.

Exercise:CreateaTable

CreateatableusingaSQLstatement,thendeletethetableandcreateitagainusingphpmyAdmin.Whichiseasier?

WorkingwithSQLStatementsINSERTStatements

Nowthatyouhaveatablecreated,thenextlogicalstepistoputsomedataintoourtable.IntheworldofSQL,thisisaccomplishedwiththeINSERTcommand.

ClickontheSQLtabagain,typethefollowingcommand(ifyoucan),andpressenter.

Obviously,writingSQLisn’tconceptuallydifficult…butitistediousandpronetoerror,especiallyasthestatementgetslonger.Thisstatement:

isprettyeasytofollow,butthisnextoneisabittougher:

Theonlydifferenceisthenumberoffields.Thesyntaxisthesame,butthechallengebecomesmakingsurethatthereisaone-to-onerelationshipforeachcolumnnameandvalue,andthattheyareintherightorder—thecolumnnamesandtheirrespectivevalues,thatis.

Asyoucansee,writinganINSERTstatementiseasytogoofup.Wealldoit.Luckily,phpMyAdminmakesiteasytogenerateperfectSQLstatements.Simplyclickonthetable,thenclicktheInsertbuttonandentervaluesintotheboxes,asshown:

OnceyouclicktheGobutton,phpMyAdminwillcreateaSQLstatementforyouandinserttherecord,andevenoffertoconvertitintoalineofPHPcodeforyou.

Here’satrickusedbytheprofessionals:onceyouhaveonelineofSQLthatworks,it’sprettyeasytocopyandpasteitandtweakthevaluesforthenextcar.Goaheadandentersomemorevaluesuntilyouget5or6carsenteredintoyourtable.Here’sanotherone:

Don’tworryifyoumessup.MySQLwillwarnyou,andpreventyoufromrunningincorrectcommands.Youdon’tneedtoenter10or20cars;thesamplecodeincludesa

scriptthatdoesthatforyou.Justdoitenoughtimesthatyougetit.

SELECTStatements

ThesyntaxofSQLisprettystraightforward,atleastsyntactically.Wehaveuseditthusfartocreateadatabase,createatablewithinthatdatabase,andinsertdataintothetable.

Therearejustafewbasictransactionsleftforustomaster:readingdata,updatingdata,anddeletingdata.SomepeoplerefertothiswiththecheeryacronymCRUD,forCreate,Read,Update,andDelete.

ReadingdataisaccomplishedusingtheSELECTstatement.TheSELECTstatementselectsavalueorgroupofvaluesfromatableandreturnsthosevalue(s)totheuser.Here’saneasywaytorememberit:TheSELECTstatementallowsyoutobeselective.Clever,eh?

Let’sstartoutwithasimpleSELECTstatement.InphpMyAdmin,clickonthecarsiconontheleftsideandthenclickontheSQLtabatthetopofthepage.TypeinthefollowingcommandandpressGo.

SELECT*FROMinventory;

Ingeneral,theasteriskcharacter(*)incomputerlingoiscalledawildcardandbasicallymeans“everything”,sotheresultofthecommandaboveshouldreturnallrowsandcolumnsoftheinventorytable,andlooksimilarto:

Ifyoutypedoutthisstatementcorrectly,youshouldseetheentirecontentsofyourtable‘inventory’.Toselectonlycertaincolumnsofatable,typeoutallofthecolumnsyouwanttoseeinthattableseparatedbyacomma.TypeinthefollowingcommandandpressGo.

Youshouldseesomethinglikethis:

NotethatIaddedtheredcircleandlinetoshowyouwheretolook.ThemySQLdatabaseonlyreturnedthecolumnsyouspecifiedusingtheSELECTstatement.

WHEREStatements

Sofar,youhavelearnedhowtogetalltherowsandcolumnsfromatable,andhowtogetselectedcolumnsfromatable,butwhataboutselectedrows?

ThisiswheretheWHEREstatementcomesintoplay.TheWHEREstatementgivesaspecificsetofcriteriatotheMySQLdatabasesothattheresultsaremuchmorecontrolledandrelevanttowhatyouwant.Forexample,saythatyouwanttoselectalltheFordExplorersthatareintheinventory,oralltheToyotasunder$15,000.TheWHEREclausemakesthispossible.

TheresultsshouldbeeveryautomobilemadebyFordinthedatabase.IfyouwantedjustFordExplorers,youwouldneedtohaveWHEREMake=‘Ford’ANDModel=‘Explorer.

Ofcourse,ifyouwerelookingtobuyacar,youwouldonlybeinterestedinthosecarsthathaven’talreadybeensold,sothefollowingquerymightbebettersuited:

NULLisaspecialwordmeaningthatthefielddoesnotcontainavalue,andforsomereasonyoucan’tsay=NULL,youhavetosayISNULL.I’msurethereisareasonforthis,butitdoesn’treallymatter.Itiswhatitis.

ComparisonOperators

Therearemanydifferentcomparisonoperatorsinadditionto=andIS.

RemembertosurroundastringwithquotationsorparentheseseverytimeyouwishtousetheminSQLstatements.Theywillnotworkotherwise.Also,theWHEREcommandalwaysgoesaftertheSELECTstatementinMySQL.

Tofindalloftheautomobileswithayearthatisa2010ornewer,itisfairlyobviousthatweneedtousetheGreaterThanOrEqualTooperatordefinedabove.TypethefollowingcommandintoyourcompilerandpressGo.

ORDERBY

TheORDERBYstatementisprobablyoneoftheeasiestandhandiestcommandsinSQL.YoucanattachitattheendofanySELECTstatementtoputtheresultsintheorderofthecolumnthatyouspecify.

Theabovestatementshoulddisplaytheautomobilesinorderofthecolumn‘Year’withthenewestcarsatthetop.ThisisbecausethemodifierDESC,ordescending,isplacedattheendofthecommand.

Theabovestatementshoulddisplaytheautomobilesinorderofthecolumn‘Year’withtheoldestcarsatthetop.ThisisbecausethemodifierASC,orascending,isplacedattheendofthecommand.

TheORDERBYmodifiercanalsobeusedwithaWHEREstatementsuchas:

JustrememberthattheWHEREcommandalwaysgoesbeforetheORDERBYcommand.Ifyoumixthemup,youwillgetanerror.

TolimithowmanyresultsyoureceiveinanORDERBYstatement,usethelimitclauseafteryouwrite‘asc’or‘desc’,suchas

SELECT*FROMinventoryORDERBYYEARDESClimit10;

Thenumberafterlimitdetermineshowmanyresultsarereturned.

UPDATEStatements

Toupdateexistingrecordsinadatabase,youusetheUPDATEstatement.Thiswouldbeuseful,forexample,whenacarintheinventorygoesonsalewithaloweraskingprice.

Thesyntaxforanupdatestatementis

Tochangetheaskingpriceforacarinourdatabase,youcanuseastatementsuchas:

DELETEStatements

TodeleterecordsfromadatabaseyouusetheDELETEstatement,specifyingthetablenameandaWHEREclausethatspecifieswhichrecordstodelete.

Forexample,todeletetheCaravancarsfromtheinventoryyoucoulduseacommandsimilarto

Ifyouwantedtodeleteeverythingfromadatabasetable,youcouldskiptheWHEREclauseanduseourfriendthewildcardwithastatementlike

UsingmySQLandPHPTogetherIntroductionInthepreviouschapter,welearnedallthebasicsofusingadatabase,inourcasemySQL.AlltheSQLstatementsthatwelearnedsofarwouldlikelyworkwithotherdatabasesystems,suchasMicrosoftSQLServer.Ingeneral,commonSQLcommandsworkacrossalldatabases.Occasionallyyou’llfindminordifferences,butotherdatabasesystemsarebeyondthescopeofthisbook.

ThusfarwecreatedourSQLstatementseitherbyhand,mostly,orwiththeaidofphpmyAdmin.Inthischapter,we’regoingtousePHPandmySQLtogether.Thisiswhereitreallystartstogetgood.

Code!ThePHPcodelistingthatfollowswillautomateallthestepswecoveredinthepriorchaptertocreateadatabase,createatable,andinsertrecordsintothetable.

Ifitallworksasintended,youshouldseeascreenlikethis:

Thecodethatfollowsisnumberedfortheconvenienceofexplainingit,butrememberthatyoucangetthesamplecodefromthewebsite,http://www.joyofphp.com.Thisparticularscriptiscalled‘createdb.php’.

Youdon’tneedtostudyeverylineasitispresentedhere.Justgiveitaquicklookover.Inthenextsection,Iwillgoovertheentirescriptlinebylineandexplaineachone.

CodeListing:createdb.php1.<?php

2./**

3.*JoyofPHPsamplecode

4.*Demonstrateshowtocreateadatabase,createatable,andinsertrecords.

5.*/

6.

7.$mysqli=newmysqli(‘localhost’,‘root’,‘mypassword’);

8.

9.if(!$mysqli){

10.die(‘Couldnotconnect:‘.mysqli_error($mysqli));

11.}

12.echo‘ConnectedsuccessfullytomySQL.<BR>’;

13.

14.

15./*Createtabledoesn’treturnaresultset*/

16.if($mysqli->query(“CREATEDATABASECars”)===TRUE){

17.echo“<p>DatabaseCarscreated</P>”;

18.}

19.else

20.{

21.echo“ErrorcreatingCarsdatabase:”.mysqli_error($mysqli).”<br>”;

22.}

23.//selectadatabasetoworkwith

24.$mysqli->select_db(“Cars”);

25.Echo(“SelectedtheCarsdatabase”);

26.

27.$query=”CREATETABLEINVENTORY

28.(VINvarchar(17)PRIMARYKEY,YEARINT,Makevarchar(50),Modelvarchar(100),

29.TRIMvarchar(50),EXT_COLORvarchar(50),INT_COLORvarchar(50),ASKING_PRICEDECIMAL(10,2),

30.SALE_PRICEDECIMAL(10,2),PURCHASE_PRICEDECIMAL(10,2),MILEAGEint,TRANSMISSIONvarchar(50),PURCHASE_DATEDATE,SALE_DATEDATE)”;

31.//echo“<p>***********</p>”;

32.//echo$query;

33.//echo“<p>***********</p>”;

34.if($mysqli->query($query)===TRUE)

35.{

36.echo“Databasetable‘INVENTORY’created</P>”;

37.}

38.else

39.{

40.echo“<p>Error:</p>”.mysql_error();

41.}

42.//DatesarestoredinMySQLas‘YYYY-MM-DD’format

43.$query=“INSERTINTO`cars`.`inventory`

44.(`VIN`,`YEAR`,`Make`,`Model`,`TRIM`,`EXT_COLOR`,`INT_COLOR`,`ASKING_PRICE`,`SALE_PRICE`,`PURCHASE_PRICE`,`MILEAGE`,`TRANSMISSION`,`PURCHASE_DATE`,`SALE_DATE`)

45.VALUES

46.(‘5FNYF4H91CB054036’,‘2012’,‘Honda’,‘Pilot’,‘Touring’,‘WhiteDiamondPearl’,‘Leather’,‘37807’,NULL,‘34250’,‘7076’,‘Automatic’,‘2012-11-08’,NULL);”;

47.

48.

49.if($mysqli->query($query)===TRUE){

50.echo“<p>HondaPilotinsertedintoinventorytable.</p>”;

51.}

52.else

53.{

54.echo“<p>ErrorinsertingHondaPilot:</p>”.mysqli_error($mysqli);

55.echo“<p>***********</p>”;

56.echo$query;

57.echo“<p>***********</p>”;

58.}

59.

60.//InsertaDodgeDurango

61.

62.$query=“INSERTINTO`cars`.`inventory`(`VIN`,`YEAR`,`Make`,`Model`,`TRIM`,`EXT_COLOR`,`INT_COLOR`,`ASKING_PRICE`,`SALE_PRICE`,`PURCHASE_PRICE`,`MILEAGE`,`TRANSMISSION`,`PURCHASE_DATE`,`SALE_DATE`)

63.VALUES

64.(‘LAKSDFJ234LASKRF2’,‘2009’,‘Dodge’,‘Durango’,‘SLT’,‘Silver’,‘Black’,‘2700’,NULL,‘2000’,‘144000’,‘4WDAutomatic’,‘2012-12-05’,NULL);”;

65.

66.If($mysqli->query($query)===TRUE){

67.echo“<p>DodgeDurangoinsertedintoinventorytable.</p>”;

68.}

69.else

70.{

71.echo“<p>ErrorInsertingDodge:</p>”.mysqli_error($mysqli);

72.echo“<p>***********</p>”;

73.echo$query;

74.echo“<p>***********</p>”;

75.}

76.

77.

78.$mysqli->close();

79.?>

CodeExplained:createdb.phpNextI’llwalkyouthroughthecode,linebyline.Pleasetakethetimetofollowalongwithme,asthisistheonlywaytoreallygetit.Yes,everylinedoesmatter.1.<?php

line1isthestarttagforPHP,andittellsthePHPinterpreterthatwhatfollowsiscode,notHTML.

2./**

3.*JoyofPHPsamplecode

4.*Demonstrateshowtocreateadatabase,createatable,andinsertrecords.

5.*/

6.

lines2-5arecomments.Commentsaregood,soputlotsofcommentsinyourcode.7.$mysqli=newmysqli(‘localhost’,‘root’,‘mypassword’);

line7createsavariablecalled$con(forconnection)andsetsitequaltoabuilt-infunctionforconnectingtomySQL.Youneedtosupplythehostname,username,andpasswordforyourmySQLserver.Ifyoudonothavethecorrectusernameandpassword,youwillseethis:

9.if(!$mysqli){

line9isthestartofanifstatement,sayingbasically“ifyouarenotconnected”.Theexclamationpointisthenotoperator.Thepointofthislineistotesttoseeifline7succeeded.10.die(‘Couldnotconnect:‘.mysqli_error($mysqli));

line10iswhattodoiftheconnectionfailed.‘die‘isacommandthatstopsfurthercodeexecutionandprintsoutthetextthatfollows.IfIhadbeentheonewhoinventedPHP,Imighthavenamedthatcommand‘stop’ratherthan‘die’,butitdoesmakethepoint.11.}

12.echo‘ConnectedsuccessfullytomySQL.<BR>’;

line12printsout“ConnectedsuccessfullytomySQL”.Thisisthefirstlineyouseeinthebrowser.

15./*Createtabledoesn’treturnaresultset*/

16.if($mysqli->query(“CREATEDATABASECars”)===TRUE){

17.echo“<p>DatabaseCarscreated</P>”;

18.}

19.else

20.{

21.echo“ErrorcreatingCarsdatabase:“.mysqli_error($mysqli)).”<br>”;

22.}

Line15isacommentthatexplainsthefunctionofthenextline.

Line17printstothebrowseriftheSQLstatementinline15ranwithouterror.

Line21printserrorinformationtothebrowseriftheSQLstatementinline15didnotrunsuccessfully.23.//selectadatabasetoworkwith

line23isacomment.Commentsaregood.24.$mysqli->select_db(“Cars”);

line24createsavariablecalled$selectedwhichusesabuilt-infunctionforselectingamySQLdatabase,usingtheconnectioncreatedinline7.

25.Echo(“SelectedtheCarsdatabase”);

line25prints“SelectedtheCarsdatabase”tothebrowser.27.$query=”CREATETABLEINVENTORY

28.(VINvarchar(17)PRIMARYKEY,YEARINT,Makevarchar(50),Modelvarchar(100),

29.TRIMvarchar(50),EXT_COLORvarchar(50),INT_COLORvarchar(50),ASKING_PRICEDECIMAL(10,2),

30.SALE_PRICEDECIMAL(10,2),PURCHASE_PRICEDECIMAL(10,2),MILEAGEint,TRANSMISSIONvarchar(50),PURCHASE_DATEDATE,SALE_DATEDATE)”;

lines27-30createsavariablecalled$querywhichholdsanSQLstatement.RecallthatphpMyAdmincreatedthislineofcodeforus.Goodthingtoo,asitisaneasyonetogoofup.

31.//echo“<p>***********</p>”;

32.//echo$query;

33.//echo“<p>***********</p>”;

lines31-33arecommentsnow,butpreviouslytheywerepartofthescriptthatprintedoutthevalueofthevariable$query.Ihadthisintheretohelpmefigureoutwhyitdidn’tworkatfirst,andIleaveitinthereasanexampleofwhattodowhenasscriptdoesn’tdoquitewhatyouthoughtitwould.Ithencopiedtheoutputofline32totheclipboardandpasteditintophpMyAdminforsyntaxadvice.

34.if($mysqli->query($query)===TRUE)

line34executesaSQLstatement“query($query)”thentestsfortheresultoftheSQLstatementheldinthevariable$mysqli.35.{

36.echo“Databasetable‘INVENTORY’created</P>”;

37.}

line36printsthemessage“Databasetable‘INVENTORY’created”ifline34isasuccess.

38.else

39.{

40.echo“<p>Error:</p>”.mysqli_error($mysqli));

41.}

line40printsthemessage“Error:”andthemySQLerrorifline34fails.Hopefullythevaluereturnedbymysql_error()willtellyousomethinghelpfulaboutwhyitfailed.Sometimesitactuallydoes.42.//DatesarestoredinMySQLas‘YYYY-MM-DD’format

line42isacommenttoremindme(andyou)toformatdatesthewaymySQLexpectsthem43.$query=“INSERTINTO`cars`.`inventory`

44.(`VIN`,`YEAR`,`Make`,`Model`,`TRIM`,`EXT_COLOR`,`INT_COLOR`,`ASKING_PRICE`,`SALE_PRICE`,`PURCHASE_PRICE`,`MILEAGE`,`TRANSMISSION`,`PURCHASE_DATE`,`SALE_DATE`)

45.VALUES

46.(‘5FNYF4H91CB054036’,‘2012’,‘Honda’,‘Pilot’,‘Touring’,‘WhiteDiamondPearl’,‘Leather’,‘37807’,NULL,‘34250’,‘7076’,‘Automatic’,‘2012-11-08’,NULL);”;

lines43-46changesthevalueof$querytoanewSQLstatement,thistimeanINSERT.49.if($mysqli->query($query)===TRUE){

line49testsfortheexecutionoftheSQLstatementheldinthevariable$query

50.echo“<p>HondaPilotinsertedintoinventorytable.</p>”;

line50printsthemessage“<p>HondaPilotinsertedintoinventorytable</p>”ifline49isasuccess.The<p>tagsputthemessageonitsownline.

51.}

52.else

53.{

54.echo“<p>ErrorinsertingHondaPilot:</p>”.mysql_error();

55.echo“<p>***********</p>”;

56.echo$query;

57.echo“<p>***********</p>”;

58.}

lines54-57printamessageifline49fails.

60.//InsertaDodgeDurango

61.

62.$query=“INSERTINTO`cars`.`inventory`(`VIN`,`YEAR`,`Make`,`Model`,`TRIM`,`EXT_COLOR`,`INT_COLOR`,`ASKING_PRICE`,`SALE_PRICE`,`PURCHASE_PRICE`,`MILEAGE`,`TRANSMISSION`,`PURCHASE_DATE`,`SALE_DATE`)

63.VALUES

64.(‘LAKSDFJ234LASKRF2’,‘2009’,‘Dodge’,‘Durango’,‘SLT’,‘Silver’,‘Black’,‘2700’,NULL,‘2000’,‘144000’,‘4WDAutomatic’,‘2012-12-05’,NULL);”;

65.

66.If($mysqli->query($query)===TRUE){

67.echo“<p>DodgeDurangoinsertedintoinventorytable.</p>”;

68.}

69.else

70.{

71.echo“<p>ErrorInsertingDodge:</p>”.mysql_error();

72.echo“<p>***********</p>”;

73.echo$query;

74.echo“<p>***********</p>”;

75.}

76.

lines60-76doesthesamethingas43-58,exceptforadifferentcar.78.$mysqli->close();

79.?>

line78closestheconnectiontomySQL.

line79istheendtagforPHP,andanytextthatfollowedwouldbetreatedasHTML,ratherthancode.

Hey,where’stheHTML?

Theastutereadermighthavenoticedthatthisscriptdidn’tappearinsidetheusualpatternof<HTML><Body><htmlcodehere><phpcodehere></Body></HTML>.

Yetitworked.Howcome?Idiscoveredthisquitebyaccident,actually.It’snotafunctionofPHPbutapparentlysomebrowserswillfillintheHTMLframeworkforyouifyou“forget”todoso,whichIdidonetime.Tryityourself.Itworks.Isthisabestpractice?No,Ican’timaginethatitis.ButwhileyouarelearningitdoesletyoufocusonthePHPcode.

CreatingformstoDisplay,Add,Edit,andDeletedataIntroductionSofarwe’velearnedhowtouseSQLtocreatedatabases,addrecords,editrecords,deleterecords,andselectrecords.ThenwelearnedhowtousePHPtoperformthosesameoperations.

Nextwe’llgetevenmoreawesome.We’lllearnhowtouseHTMLformsalongwithPHPtocreatetheSQLstatementsthatperformtheoperation.

FormsthatAddDatatoaDatabaseABasicForm

Let’sstartwithasimpleexamplethatiseasytofollow.Here’sasimple,four-fieldform:

Obviously,itdoesn’thavealltheattributesofacarthatwehavepreviouslyidentified,andit’snotveryprettytolookat,butitissimple,anditwillillustratethepointwithoutanyextrajunktogetinthewayofyourunderstandingoftheconcept.

HTMLCode

Thecodetoproducesuchaformfollows<HTML>

<head>

<title>JoyofPHP</title>

</head>

<body>

<h1>Sam’sUsedCars

</h1>

<form>

VIN:<inputname=“VIN”type=“text”/><br/>

<br/>

Make:<inputname=“Make”type=“text”/><br/>

<br/>

Model:<inputname=“Model”type=“text”/><br/>

<br/>

Price:<inputname=“Asking_Price”type=“text”/><br/>

<br/>

<inputname=“Submit1”type=“submit”value=“submit”/><br/>

&nbsp;</form>

</body>

</html>

SofarwhatwehaveisjustHTML,andinfacttheformwon’tactuallydoanythingifyoupressthesubmitbutton…yet.

FormAction

Tomaketheformactuallydosomething,weneedtomodifythe<form>tag.Changethelineofcodeabovesothatinsteadofsaying<form>itsays<formaction=“SubmitCar.php”method=”post”>

Thistellsthebrowserthatwhentheformissubmittedbypressingthesubmitbutton,itshouldpassthisformtothePHPscriptentitled‘SubmitCar.php’andusethe‘Post’methodtodoso.

Formscanbesubmittedeitherusingmethod=‘post’ormethod=‘get’.There’sreallynogoodreasontouse‘get’whensubmittingaformsotokeepthingssimple,we’lljustuse‘post’wheneverwesubmitaform.

We’llusegetlaterinthebookforadifferentpurpose,though.

PHPCode

Here’swhatwearegoingtoaccomplish.Wewantthescriptreferencedbytheformtogetthevaluesfromtheform,produceaSQLINSERTstatementusingthosevalues,writetheSQLstatementtothebrowsersowecanseeit,executetheSQLstatementthatwejustcreated,andfinally,letusknowifitworked.

Ifallgoeswell,thescriptshouldoutputsomethingsimilartothis:INSERTINTOInventory(VIN,Make,Model,ASKING_PRICE)

VALUES(‘9T4BF3EKXBR153775’,‘Ford’,‘Fiesta’,800)

ConnectedsuccessfullytomySQL

SelectedtheCarsdatabase.

YouhavesuccessfullyenteredFordFiestaintothedatabase.

Here’sthecodefortheSubmitCar.phpfile,whichisalsoavailableinthesamplecode.Again,youdon’thavetostudyitherebecauseIwillwalkyouthroughitnext.Fornow,justgiveitaquicklookover.

Line1istheopening<html>(whichisclosedonline53).

Lines2–4constitutetheHeadtag,whileline3setsthepagetitle.

Line5opensthebodytag(whichisclosedonline52).Notethatweusedtheoptionalparametertosetthebackgroundandtextcolors.

Line7istheopening<php>tag,tosignifythatthetextthatfollowsiscoderatherthanHTML.

Line8isacomment.Youcanneverhavetoomanycommentsinyourcode.Getinthehabitearlyofover-commentingyourcode.Ihaveneverheardanyonecomplainthatthecodetheyweretryingtofigureouthad“toomany”commentsdistractingfromtheeleganceofthelogic.

Lines10–13getthevaluesthatwereontheformandassignthemtovariablesinPHP.$_REQUESTisaspecialvariablethatisusedtocollectdataaftersubmittingHTMLforms.YoufollowitwiththenameofthefieldontheHTMLformthatyouwanttoretrieve.

Anumberofreadersofthefirsteditionofthisbookhavecommentedthatyoushouldnevertrusttheinformationthatusersgiveyou,eveninacorporateapplicationlikethisone,wheretheusersaregenerallytrusted.SoasaferwaytoacheivewhatwedidabovewouldbetousethePHPfunctioncalledmysql_real_escape_stringtostripoutanythingdangerousthatusersmighttrytoenter.Forinstance,$Make=mysql_real_escape_string($_POST[‘Make’]);

Line15isacomment.Commentsaregood.

Lines17–24buildaSQLINSERTcommand.Itcouldhavebeenallononeline,butitiseasiertoreadthisway.Noticethatthevariables$VIN,$Make,$Model,and$Priceareputintotheformulaastheyare.Later,whenthecodeisactuallyexecuted,PHPwillsubstitutethevariablenameswiththeiractualvalues.

Line26isacomment.Commentsaregood.

Line27writestheSQLstatementouttothebrowser,onitsownline.The.”<br>”afterthe$queryaddsa<br>totheendoftheline.That’swhatputsitonitsownline.Line27wasnotrequiredforthefunctiontowork.ItistheresoyoucanseehowPHPtranslatedthevariablesintotheirvalueswhenproducingtheSQLstatement,whichinturnisstoredinthevariable$query.

Line29makesaconnectiontothemySQLdatabasebypassingthenameoftheserver(‘localhost’),username(‘root’),password(‘password’),andinitialdatabase(‘cars’).Noteyourpasswordwilllikelybedifferent.

Line30isacomment,usingthealternatesyntaxfordenotingacomment.

Lines31–34testtoseeiftheconnectionmadewithline29workedornot.Ifnot,itprintsanerrormessagethenstopsfurthercodeexecution(line33–exit).exit()isanalternativetothecommanddie.

Line36printstothebrowserthemessage‘ConnectedsuccessfullytomySQL’.Thislinewouldnotexecuteifline33wascalled.Sincewemadeitthisfar,wecanconcludethatwedidinfactconnect.

Line38isacommentthatexplainsthepurposeofthenextline.

Line39selectsthe‘cars’database,andline40printsthisfact.

Line42isacomment.Youseeathemehere,right?Themorecommentsyouadd,theeasieritwillbetofigureoutyourcodewhenyoucomebacklatertolookatit.

Line43isthegrandfinale.HereweactuallyexecutetheSQLstatementagainstthecarsdatabase.Line43isthestartofanifstatementandline44printsasuccessmessagewhileline48printsafailuremessage.

Note:Line48reallyshouldreaduse‘mysqli_error($mysql)’notmysql_error().Thisiscorrectedinthesamplecode.Asanastutereaderofthefirsteditionpointedout,youcan’tmixmysqlandmyslqiinthesamescript–theyarenotthesame.Inanycase,the

mysqlextensionhasbeendeprecatedinfavorofthemysqliextension.

Line50closestheconnectiontothemySQLdatabase.Thisisnotstrictlyrequired,asthepagewillstillworkifyoudon’tdoit,butapparentlyit’sagoodideabecauseifyoudon’tdoit,eventuallytheserverwilldevelopproblemsandultimatelyrequireareboot.

Line51closesthePHPtagthatwasopenedonline7,signalingthatthelinesthatfollowarehtmlnotPHPcode.

Lines52and53closethebodytagandtheHTMLtags,respectively.

Wow,wemadeitthroughthewholescript.Ifyouarestillwithme,youhaveagoodfutureinPHPdevelopment!Staywithit!

ABriefTimeOut…includefilesandSQLInjectionIncludeFiles

YoumayrecallfromtheearliersectiononIncludesthenotionofreusingcodebyincludingthecontentsofonefileinanother.Thisisagoodtimetorevisitthisimportanttopic.

Sofarwe’vemadetwodifferentPHPfiles—thefirstonetocreateadatabaseandtable,andthesecondoneinthesectionabovetoinsertdataintothedatabaseusingawebform.Asyoucanguessfromthesectionheadingscominguplaterinthischapter,we’reabouttomakeevenmorescriptsthatwillallowustoeditanddeletedataaswell.

Eachofthesescriptswillhaveasomethingincommon—codethatconnectstothemySQLdatabase,andineachcasethatcodewillbeexactlythesame.Sofar,we’vebeendevelopingonourowncomputer,sothehostnamehasbeen‘LocalHost’.Imagineyourself,sometimeinthenearfuture,havingwrittenadozenormorescriptsintothefuture,andsuddenlyyoudecidetomoveyourapplicationtoanothercomputer—oneaccessiblefromtheInternet.Thehostnamewillnotbethesame.Nor,mostlikely,willtheusernameandpasswordbethesame.Whatifyourpasswordgotoutandyouneededtochangeit?

Withoutmyhelpfulinterventionrighthere,youwouldbefacingtheprospectofchangingdozensof.phpfiles—searchingforthelinethatreadssomethinglike…

…andchangingittoreflectthenewhostname,username,orpassword.Uck—therewouldbenojoyinthattaskatall.

Fromnowon,we’regoingmovethepartofthecodethatconnectstothedatabasetoaseparatefile,andallournewscriptsfromthispointforwardwillsimplyrefertothatcodeusinganincludestatement.Ifanyofthevalueschange,wewillonlyhavetochangeitinoneplace…thefilethatalltheotherspointto.

Justimaginethejoyofchangingonelineofcodeandseeingthatchangepropagateacrossdozensofpages.That’swhatI’mtalkingabout.TheincludefeatureisoneofthemosthelpfulandimportantfeaturesofPHP,inmyhumbleopinion.

We’llusetheline…

…totellPHPtoinsertthecontentsofthedb.phpfileintothecurrentscript.Besuretouseincludefileswheneveryoucan,astheextrafewminutesittakestomovesomecodeouttoaseparatefileismorethanpaidbackwhenthatcodehastochange.

SQLInjection

Ingeneral,itisnotagoodideatotakewhatevertheuserentersintoaformandpassthatdirectlytoaSQLscriptaswedidintheaboveexample.Iftheuserweremalicious(andskilled)theymightenterSQLcodeintooneofyourformsandthiscouldhaveabigimpactonwhatthescriptactuallydoes.Forexample,imagineabasicusername/passwordformandtheuserentering‘or1=1–intothePasswordfield,asshown:

Nowthestatementthatisexecutedinthedatabaseisthefollowing:

SELECT*FROMUsersWHEREUsername=‘Brian’andPassword=”or1=1—’

Because1=1isalwaystrue,thisquerywillreturnallusers.(Notethatthelastquotationiscommentedout.)So,inthescriptabove,sqlsrv_has_rowsistrue,andalltheusernamepasswordrowswillbereturned.

SQLinjectionispossibleherebecauseuserinputisconcatenatedwiththeexecutedSQLcode.Onewaytopreventagainstthisistostripoutanyslashesorquotemarksfromthetheuser’input.Thefollowingcodesnippetdemostratesthis://ToprotectagainstSQLinjection

$make=stripslashes($myusername);

$model=stripslashes($mypassword);

$make=mysql_real_escape_string($myusername);

$model=mysql_real_escape_string($mypassword);

Attheriskofstatingtheobvious,thestripslashescommandremovesanyslashestheusersandmysql_real_escapecommandremovesthequotecharacters.

AnevenbetterwaytoreducethechanceforSQLinjectionistousepreparedstatements,butthisisatopicthatisbeyondthescopeofthisbeginner’sbook.Ifyouwanttolearnmore,here’sagoodplacetostart—>http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/

FormsthatDisplaySummaryDataOneofthefirstthingswe’llwanttodoforSam’sUsedCarsistodisplayalistofallthecarsthatmeettheselectedcriteria.Atfirst,ourcriteriawillbetoselectallthecars,butlateronyoucanmodifythequerytoreturnonlycertaincarssimplybymodifyingtheSELECTstatementinthecode.

ThewaythiswillworkisthatwewillexecuteaSQLSelectstatementtoretrievethecarsthatmatchthecriteria,thenloopthroughalltherows.We’llputeachrowofdataintoanicelyformattedtable.

Thesourcecodecanbefoundasviewcars.php.Ifallgoeswellthepageshouldlooklikethis:

Ofcourse,theoutputofasimplescriptisnotparticularlyattractivetolookat,butwiththeadditionofabitofCSSwecanmakeitlooklikethis:

Butlet’snotgettoofaraheadofourselves.First,hereisthecodethatproducesthebasicversionofthetable.Theoutputofthisscriptismoreinterestingifyouhavealotofcarsinyourdatabase,soifyouhaven’tdonesoalready,usethescript“createdb.php”includedwiththesamplecodetopopulateyourinventorytablewithalotofcars.

Code

CodeExplained

Iwon’twalkyouthrougheverylineanymore,asInolongerthinkyouneedit.Fromnowon,I’lljustexplaintheimportantones.

Line11isourfirstuseoftheincludeoptionwhichreferstoanexternalfilenameddb.phpwhichwillbeincludedinthisscriptjustasifitwerepartofthesamefile.Ihighlightedline11aboveinblueandthecodebelowinblue,inhopesthatyouwouldbetterunderstandhowitworks.Thecontentoftheblueboxbelowissubstitutedintothecodefortheblueline(11)above,sothatbothfilesarecombinedintoasinglescript.

Thecontentsofthe‘db.php’fileareshownbelow:

Thecodeinthedb.phpfileisidenticaltothecodeexplainedasline29intheprevioussection,soIwon’texplainitagainhere.That’sanotherkeybenefitofincludefiles.Oncethecodeinsideitworks,youdon’treallyhavetothinkaboutitmuchanymore.

Line12isthequerythatproducesthelistofcarstobedisplayed.Inthissimplecase,weareselectingallthecars.

Lines14–20runsthequeryanddisplaysanerrormessageifthequeryfails.

Line23isanopeningtagtocreateatablewiththeIDof‘grid’.TheIDisoptionalbutmakesiteasytoapplystylestothetablelater.style=width:80%preventsthecolumnfromextendingtofilltheentirescreen;insteadittakes80%ofthewidth.<tr>startstheTableRowwiththeopening<tr>tag.

Lines24–27createthefirstrowofthetable,therowthatcontainsthecolumntitlesofmake,model,andprice.Line27isaclosingTableRowtag,followedbyanewline.

Line29setsthevalueofavariablecalled$classto‘odd’becausethefirstdatarowinourtablewillbeodd.Asweloopthrougheachrowofdata,we’llalternatelysetthe$classtothevalueofeither‘odd’or‘even’.Wedothissowecanstylethetablelatertohavealternaterowsshowdifferentcoloringtomakeiteasierontheeyes.

Lines31to37createarowintheHTMLtabletocorrespondwitheachrowinthe

databasetablethatweextractedusingthequery.EachtablecellcontainsdatafromthemySQLtable.Forinstance,line34(echo“<td>”.$result_ar[‘Make’].“</td>”;)shouldproducesomethinglike<td>Ford</td>

because$result_ar[‘Make’]saysgetthevalueofMake(oneofthecolumnsinthetable,andinthiscase‘Ford’)andputitherebetweenthe<td>tags.Takethetimetoreallyunderstandwhatthatlineisdoing,becauseifyoucanunderstandthis,youcandovirtuallyanything!Rememberthe.charactermeansjointhesetwostrings.

Lines39–46justalternatethevalueof$classfromeventoodd.

Line47closestheWhileloop.

Line48closesthetablewiththe</table>tag.

Line49closesthemySQLdatabase.

Line50indicatestheendofthePHPcode.

Line51istheendofthebodyintheHTMLpage.

Finally,line53indicatestheendoftheHTML.

Exercise:TweakingtheSELECT

Gobackandmodifythiscodesothatitdoesn’tselectallthecarsbutratherasubsetthat

pleasesyou.

ImprovingthelookofthetablewithCSS

Here’stheCSSthatimprovesthelookoftheform.Thisstyleinformationisaddedtothe<head>sectionofthepage,butoftenpeopleputstylesintoaseparatestylesheettoo.Seethefileviewcarswithstyle.phptoseetheforminaction.

ExplaininghowCSSworksisbeyondthescopeofthisbook,andatopicinitself.ButtheimportantthingistoseehoweasilywewereabletochangethelookoftheHTMLtableusingalittlestyleinformation.Takealookatthecompletestylesheethere,andI’llexplainitnext.

CSSExplained

Line1opensthe<style>tag,tellingthebrowserthatwhatfollowsisastylesheet.Line2isacomment.

Line3saystoselectanitemonthepagewiththeidofGrid.The#symbolistheselectortoselectsomethingdefinedusinganid,andwhatfollowsisthenameofthespecificthingyouwanttoselect.Seeline23ofthepreviousPHPscript,whichsettheidofourtableto‘grid’withthelineecho“<tableid=‘Grid’style=‘width:80%’>;Sincewehaveatablewithanid=‘Grid’,thisstylewillapply.

Everythingthatfollowsbetweenthe{andthe}symbolsdefinethestyleforthatitem.Wepickfont,border,margin,etc.

Line11specifiesthatthefollowinglinesonlyapplyto<td>and<th>tags,iftheyappearwithinanitemwithanIDof‘Grid’.

Eachlinethatfollowsgetsmorespecificabouthowanitemshouldbeformatted.Aspecificselectoroverwritesageneralone.SowestartedoffspecifyingdefaultformattingforGrid,butlaterwemodifiedspecificelementsofthegriditem.Thenextbitishowwecoloralternaterowsdifferently:

Line27saystoselectsa<td>tag,withinatablerow<tr>ifitisamemberoftheclassodd.LookattheHTMLthatisoutputbythescript.You’llseeatablerowforthetabledefinedlikethis:<trclass=‘odd’>or<trclass=‘even’>.

Thereisanotherselectorforthetableheaders.Itdoesmakesenseifyoulookatitlongenough.The#symbolinCSSisaselector.OK,that’sitfornow.MaybesomedayI’lldoa“JoyofCSS”book.Letmeknow…

Modifyingtheformtolinktothedetailpage

Thelastthingthisformneedsiswaytolinktoaspecificcar.Whenthesitevisitorclicksonaspecificcarinarow,itshouldtakethemtomoredetailaboutthatspecificcar.Inotherwords,itshouldtakethemtothe‘cardetail’page.We’regoingtohavetomakethatpage,ofcourse.

Notethatforthistoworkwewillneedtobuildthedetailpagebecauseotherwisethelinkwillnaturallyfail.Nothinghappensautomatically.Assumingthatthedetailpageexists,wecanmodifythecodeonline34thatreadsas:

toinsteadreadas:

Whatthisdoesiscreatean‘anchor’oralinkwhichmakesthefirstcolumnofeachrowaclickablelink.ItshouldoutputHTMLsimilarto:

YoucanseethattheURLcreatedwillbesimilarto/viewcar.php?VIN=123234FE221asshownabove.Thistellsthebrowsertoopentheviewcar.phpfileandpassitthequerystringofVIN=followedbyaVIN.ItiscalledaquerystringbecausetheprimarypurposeofpassingdatatoaformthiswayissoitcanusethedatainaSQLquery—andthat’sexactlywhatwearegoingtodo.

RememberbackwhenIsaidtouse‘Post’ratherthen‘Get’whensubmittingaform?Ifyouhadusedget,clickingthesubmitbuttonwouldsendtothebrowserareallylongURLwithallthefieldnamesandvaluesappendedtotheendofitasaquerystringinaformatsimilarto?Make=Ford&Model=Explorer,etc.Wearegoingtotakeadvantageofthattechniquetocreateourownquerystringandpassittoascript.

Fornow,clickingonthelinkwillonlytriggeranerror,becausetheviewcar.phpfiledoesnotyetexist,butthat’swhatwe’regoingtobuildnext.

FormsthatDisplayDetailData

Onceasitevisitorhasidentifiedacarthattheywantmoreinformationabout,thecarshopperwillwanttoclickonaparticularcartolearnmoreaboutit.Sowe’llmakeaPHPpagetohandlethis.We’llcallthistheCarDetailpage,anditsfilenamewillbeviewcar.php.

Again,we’llkeeptheexamplerelativelysimpleforthepurposeoffollowingthelogic.Ifallgoeswell,clickingonacarfromthepreviousscreenwillbringupaformsimilarto:

Code

CodeExplained

Line1openstheHTMLtagandstartsthedocument.

Lines2–4aretheheadtags,andinbetweenspecifiesthedocumenttitle,‘Sam’sUsedCars’.

Line8isordinaryHTML;itprintsSam’sUsedCarsatthetopofthepageinaheadlinestyletype.

Line9specifiesthatthecurrentscriptincludethedb.phpfile,whichlogsintothemySQLdatabase.

Line10createsavariablecalled$vinandassignsitthevaluethatfollowsVIN=intheURLstring.Remember,forthisformtowork,youhavetopassittheVINlikethis:/viewcar.php?VIN=123234FE221.Weusethecommand$_GETbecausewhenyousubmitaformusinggetthevaluesareappendedtotheURLinasimilarfashion.

Line11buildsaqueryusingthevaluepassedtotheformintheQueryString,andassignsittothecleverlynamedvariable$query.Seewhywecallita‘querystring’?

Lines12–19runthequeryagainstthemySQLdatabaseandcreatesomethingcalleda‘resultset’.Aresultsetisthesetofdatathatresultsfromtherunningofaquery.Thisresultsetisassignedtothevariable$result.

Lines20–31loopthrough‘all’therowsreturnedasaresultofthequery.Inourcase,sinceVINsareuniquewewouldonlyexpecttogetonerowofdataback,butweareusingbasicallythesametechniquewelearnedinthepriorsection–FormsthatDisplaySummaryData.

Lines22to30assignaseriesofvariableswiththevaluesofthespecifieddatacolumns,whichmatchthenamesofthecolumnsinthedatabasetable‘inventory’.

Line31closesthewhileloop.

FormsthatEditDataIfyouunderstandhowtomakeFormsthatAddDatatoaDatabase,andyouunderstandFormsthatDisplayDetailData,itisn’tmuchofastretch(conceptuallyanyway)tomakeaformthatEditsdata.Simplycreateaformjustliketheoneyoumadetoadddata,butbeforedisplayingitretrievedatafromthedatabaseandpre-populateitwithvalues.

InsteadofexecutingaSQLInsertcommandwhentheuserclickssubmit,insteadexecuteanUpdate.

FormsthatDeleteDataTodeleteaspecificrecordfromadatabase,youneedawayfortheusertoselectthedatatheywanttodelete.YoualreadylearnedhowtodothisinthesectionFormsthatDisplaySummaryData.InthesectionModifyingtheformtolinktothedetailpagewecreatedan<HREF>linkthattakestheusertoadetailpage,andyoucanusethatsametechniquetotakethemtoadeletepage,suchastheoneshownbelow:

Codetodeletedata

CodeExplained

Lines1–6setupthebasicsofthepage.Weopenan<html>,openandclosethe<head>tags,andstartthebodywithaheadlineproclaiming“Sam’sUsedCars”.

Lines6–7arealsofamiliartousbynow.WeopenthephptagandaddtheinsertlinetoconnectustoourmySQLdatabase.

Line9getstheVINfromthequerystring.Remember,thispagewillbecalledwith?VIN=‘23ABC..’appendedtotheend.Line10buildsaSQLdeletestatementusingtheVIN,soweknowwhichvehicletodelete.Line11simplywritesthequerytoscreensowecanseethequerywebuilt.Itisnotstrictlyrequiredforthefunctiontowork.

Lines14through20dotheactualwork.Line14performsthequery,andreturnsTrueifthequerysucceeds.Ifso,line15printsasuccessmessagetothescreen,andifnot,line19printsafailuremessagetothescreen.

Therestofthepageclosethedatabaseconnection,closesthephptag,closesthebodytag,andfinallyclosesthehtmltag.

ExerciseToaddeditanddeletefunctionality,simplyaddtwonewcolumnstothetablewiththelinksforeditanddelete,andcalltheappropriatephppage.deletecar.phphasbeenprovided,whileeditcar.phpyouwillhavetomakeyourself.Ifyouabsolutelycan’tgeteditcar.phptowork,Ididincludeitinthesamplecode.JustdoyourselfafavorandTRYtomakeit.

Fortheanswertothischallenge,lookatthesamplepageviewcarswithstyle2.php,whichisincludedinthesamplecode.

SessionVariablesIntroductionVariablesinPHPtypicallyhaveaspecificandlimitedscope—generally,avariableisonlyavailableonthepageonwhichitwasdeclared.Theprimeexceptiontothisruleiswhenyoudeclareavariableinsideafunction,itonlyworksinthatfunction.

Butwhatifyouwantaccesstothesamevariableacrossmultiplepagesinyourapplication?Forinstance,I’maregularshopperonAmazon.com.Ifyouaretoo,youmayhavenoticedthatonceyou’reloggedin,everypagehasyournameonthetopofit.

Presumably,thereisavariableinascriptsomewherecalledsomethinglike$FirstNamecontainingthevalue‘Alan’.Bynow,youcouldprobablyeasilywritesuchascript.Here’sahint:

Buthowdoesthatvalue$FirstNamepassfrompagetopageasIwanderaboutthesite?Andhowdoesthesitekeeptrackofhundredsofunique$FirstNamevariablesforalltheuniquecustomerswhohappentobeonthesiteatthesametime?Theanswerissessionvariables.

SessionsAsessionvariableisaspecialkindofvariablethat,onceset,isavailabletoallthepagesinanapplicationforaslongastheuserhastheirbrowseropen,oruntilthesessionisexplicitlyterminatedbythedeveloper(you).

ThegreatthingaboutsessionvariablesisthatPHPwillmagicallykeeptrackofwhichparticularsessionvariablegoeswitheachparticularuser.SowhilemyAmazon.comexperiencewillalwayssay“Alan’sAmazon”,yourswillsaysomethingdifferent(unlessyournamealsohappenstobeAlan,ofcourse.)Sessionsworkbycreatingauniqueid(UID)foreachvisitorandstoringvariablesbasedonthisUID.TheUIDistypicallystoredinacookie.

Itdoesn’treallymatterhowtheywork,theimportantthingisthattheydowork.And,theyareverycool.Theyopenupawholerealmofpossibilitiesforcustomizingyourwebapplicationforaspecificcustomer.Forexample,inthecaseofSam’sUsedCars,youcouldaskacustomertheirpreferredcarcolor,make/model,features,etc.Fromthatpointon,youcancustomizethepagestoreflectthecustomers’preferences.Forexample,Heylook,thiscarhasasunroof!(Andit’sredtoo!)It’sjustasampleapp,soit’sOKtocodeannoyingfeaturestolearnsomethingvaluable.

Onceauserclosestheirbrowser,thecookiewillbeerasedandthesessionwillend.Sosessionsarenotagoodplacetostoredatayouintendtokeepforlong.Therightplacetostorelong-termdataisinadatabase.Ofcourse,sessionsanddatabasescanworktogether.Forinstance,youcanstoreauser’spreferencesinadatabase,andretrievethemfromthedatabasewhentheuser“logsin”ortypesintheiremailaddressordoeswhateveritisthatyoucodedforthemtoidentifythemselves.Oncethedataisretrieved,assignthepreferencestothesessionvariablesandtheywillbeavailablefromthenon.

StartingaPHPSessionBeforeyoucanstoreuserinformationinyourPHPsession,youmustfirststartupthesessionusingthesession_start()function.Thesession_start()functionmustappearBEFOREthe<html>tag,oritwon’twork.

Thecodeabovewillstarttheuser’ssessionwiththeserverandallowyoutostartsavinguserinformationintosessionvariables.

UsingSessionVariablesThecorrectwaytostoreandretrievesessionvariablesistousethePHP$_SESSIONvariable:

Storeavariable

Retrieveavariable

Output:Alan’sAmazon

Checkingforavariable

Youcanchecktoseeifasessionvariableisavailableornotbyusingtheisset()function.

Here’sanexample:

DestroyingaSession

Ifyouwishtodeletesomesessiondata,youcanusetheunset()function.Ifyouwanttodeleteitall,usethesession_destroy()function.Theunset()functionisusedtodeleteaspecificsessionvariable:

Youcanalsocompletelydestroyallthesessionbycallingthesession_destroy()function:

Note:session_destroy()willresetyoursessionandyouwillloseallyourstoredsessiondata.Thisisaneasywaytoimplementalogoutfunction.

IfyouwouldliketolearnmoreaboutSessionVariables,Ihaveawholebookonthistopictitled“TheJoyofPHP:DeepDiveintoSessions”.

WorkingwithImagesIntroductionAusedcarwebsitewouldnotbeofmuchusetothetypicalcarshopperwithoutprovidingimagesofthecars,sointhischapterwewillcoverhowtoaddimagestooursite.Itwouldberathersimpleifeachcarhadasingleimageassociatedwithit—inthatcase,wecouldsimplyaddanadditionalcolumntoourinventorytablecalled‘image’(orsomethingequallydescriptive,suchas‘primary_image’)whichwouldstorethefilenameoftheimageassociatedwiththeparticularcar.

ThenwewouldbuildPHPtoretrievetheimagenameandinsertitintoanHTMLimagetagonthecardetailspage.

Ofcourse,PHPwouldbewellsuitedforthis.WewouldreadthefilenamefromthedatabaseandusePHPtocreatetheimagetagdynamically.

Forinstance,wecouldmodifyourearlierexample,whichshowsthedetailforaspecificcarbyaddingthelineshighlightedinredasfollows:

ThisexampleassumesthatwehaveacolumninourdatabasecalledPrimary_Image,whichcontainsthefilenameofanimagefilethatisstoredonourserver.Thesamplefileshomepagecontainsascriptthatmakesthismodification,ifyouaresoinclined.

Iftheimageswereinafoldercalled‘images’,thelinewouldread:

Exercise:ViewingImages

Gettheaboveexampletowork.Createanimagesfolderunderneaththefolderthatisrunningthecarlotapplicationandputsomeimagesintoit.ModifyyourinventorytabletoaddaPrimary_Imagefieldandentersomevaluesinthatfieldtoassociatespecificcarswithspecificimages.

Makeacopyoftheviewcar.phpscript(callitviewcar-backup.phpincaseyouneeditlater),thenmodifytheviewcar.phpasshowninredabovesothatitreadstheimagelocationoutofthedatabaseandinsertstheimageintothepageusingthe<img>tag.

PullinganunknownnumberofimagesfromadatabaseAssumingyougottheaboveexercisetowork,youmustadmitthatitisprettyslick.Congratulations,youareofficiallyawesome.But,wecandomuchmore.Justhavingoneimageofacardoesn’treallyreflecttherealityofavisitor’sexpectationofacarsite.MorelikelyavisitortoSam’sUsedCarswebsitewouldwanttoseemanyimagesofacarheorsheisinterestedin,andoursitewillhavetoaccommodatethis.Somecarsmighthaveonlyoneimage,butsomemighthave10ormore.Itwillbedifferentforeachcar.Sohowwouldweaccomplishthis?HavingasinglecolumncalledPrimary_Imageisobviouslynotthepermanentsolution.AssoonasyoushowittoSam,he’llsurelysay‘ButwhatifIhavetwopicturesofthecartoshow?’That’sthenatureofwebdevelopmentsometimes.Onegoodideasparksanother.Don’tget

frustratedwhenthishappens,butratherthinktoyourself,‘Wow,Iinspiredanevenbetteridea!’Theeasiestwaytohandleavariablenumberofimageswouldbetocreateadatabasetabletostorethemin.

Let’saddatablecalled‘images’toourcarsdatabase.ItshouldhavethecolumnsID,VIN,andImageFile.

Exercise:CreateaDatabaseTabletostoreimages

UsephpMyAdmintocreatethistable,likeso.

Nowyouneedtopopulatethetablewithsomesampledata.Here’swhatIdid.Gotohttp://www.cars.comandsearchforsomecars.CopytheVINtotheclipboard,andsavesomethepicturesofthecartoyourharddrive.Enterarowintheimagestableforeachoftheimagesyousave,andentertheVINofthecarforeachone.Thereshouldalsobeacorrespondingentryintheinventorytableforthatcar,withtheexactsameVIN.It’seasytodoinphpMyAdmin.Don’tworryabouttryingtoautomatethatpartofityet.

Exercise:Modifytheviewcar.phppagetoshowmultipleimages

OnceyouhavesomesampledatathatmatchesupspecificVINswithspecificimages,it’sactuallyprettyeasytodisplaythoseimagesonthepagealongwiththedescriptionofthecar.Here’sacodesnippetyoucanappendtotheviewcars.phpformtoextractthenamesoftheimagesfortheselectedcar.

TheassumptionofthisscriptisyouhavetheVINofthecarinthevariable$vin,andthatyouhaveincluded‘db.php’toestablishthedatabaseconnection.

Codeexplained

Line2setsupthequerywherebyweselectallthefieldsintheimagestableforthespecificcar(WHEREVIN=).

Line4runsthequeryandcheckstoseeifanyresultswerereturnedfromthedatabase.

Lines7–10loopsthroughtheresultsetasmanytimesastherearerows.Inotherwords,iftherewerefiveimagesforaspecificcar,therewouldbefiverowsofdatareturnedandthewhileloopwouldgoaroundfivetimes.

Line11closestheifstatementandtheline12closestheconnectiontothemySQLdatabase.

PHPFileUploadsIntroductionIntheprevioussection,wecapturedimagesforourcarsandthensavedthemmanuallyontotheharddrive.That’scool,buttedious.Whatwouldbereallycoolwouldbetosimplyselectacarinourinventoryandclickabuttoncalled“AddImage”,andletthescripthandletherest–puttingthefileintherightplaceandcreatingthecorrectrowintheimagestableusingtheVINoftheselectedvehicle.

That’swhatwe’lldonext.

CreateanUploadFileformInitsmostbasicincarnation,hereisanHTMLformyoucanusetouploadafile.

Thereareacoupleofthingsworthpointingout.

First,noticetheformattributes:action=‘upload_file.php’meansthatwhenyouclickthesubmitbutton,theresultoftheformpostwillbepassedtotheupload_file.phpscriptforfurtherprocessing.Next,theenctype=“multipart/form-data”isanewoneforus.Herewearespecifyingtheencodingtypetobeusedbytheform.Youhavetospecifythatitismultipart/form-dataifyouareincludingafileuploadcontrolonaform,sothebrowserknowstopassthefileasafile,andnotasjustanotherbigblockoftext.

Wealsohaveanewtypeofinputbox.Inthepast,we’vebeenusingtheinputboxesmostlytoallowuserstotypeintext.Whenyouspecifythataninputtype=“file”,thebrowserhandlesitdifferently.Itwillputabrowsebuttonnexttotheinputfield,

allowingtheusertoselectafilefromhisorhercomputer.

CreateaScripttoProcesstheUploadedFileTheformabovespecifiedthatthepostbeprocessedby‘upload_file.php’.Thisscriptisusedtodosomethingwiththefileonceit’sbeenuploaded.Thescriptthatfollowssimplyechoesbacktothebrowsersomeoftheattributesofthefilethathasjustbeenuploaded.Thereare,ofcourse,otherfileattributesthatwewon’tcover,becauseyouprobablywon’teverneedtousethem.

Ihighlightedinyellowthepartsthatneedtomatch.Inotherwords,ifthenameoftheinputcontrolontheuploadformreferstothefileas‘foo’,like<inputtype=“file”name=“foo”>youwouldalsohaverefertoitasfooonthescriptthatfollows,suchas$_FILES[“foo”][“name”].Theactualnamedoesn’tmatter,butwhatdoesmatterisconsistency.

WhenyouuploadafileusingPHP,thefileisstoredinatemporaryfolder.Unlessyouspecificallydosomethingwiththefile,itwillsoondisappear.

ForSam’sUsedCars,theidealthingtodowouldbetouploadthefile,copythefileintoaspecificfolder,andthencreatearecordintheimagestablethatinsertsthepropervehicleVINandthefilenameoftheimagewejustuploaded.Inthesampledata,seethescriptViewCarsAddImage.phptoseethisexactconceptinaction.

Code:ViewCarsAddImage.php

CodeExplained

Line1opensthephptag,andline2addsthenecessaryincludefiletoconnecttoourdatabase.

Line3createsavariablecalled$vinandassignsitthevaluethatwaspassedtoitusingwhenaformwasposted.Again,seethisinactionwiththesamplescriptsincludedwiththisbook.Thisisnottheonlywaywecouldhavedonethis.WecouldalsohavepassedtheVINinaquerystring,thetechniqueweusedinviewcar.php

Lines4–7testtoseeifafilewas,infact,uploaded.Ifnot,anerrorisprintedusingline6.

BeginningwithLine9,thescriptbeginstoprocesstheuploadedfile.

Lines10–12printinformationaboutthefile,andline13printstheVIN,justtomakesurewegotitwithoutanyproblems.

Line14tellsusthenamethatPHPusedtotemporarilystoretheuploadedfile.

TIP:NoticethatontheendofthelineIalsohaveitwrite“\n”,whichmeanstoaddanewlineattheendofthis.Thisdoesn’taffectthescriptatall,butitdoesputanewlineontheHTMLthatiscreatedbythescript.Putting\nattheendofthelineonscriptsmakestheHTMLcodeeasiertoreadwhenyoulookatapageandselectViewSource—somethingthateveryPHPdeveloperhastodofromtimetotime.

Line15usesthecommandgetcwd()tofigureoutthenameofthefolderinwhichthecurrentscriptisrunning.WhydidIwantthat?BecauseIwanttoputtheuploadedfileintoafolderthatisunderthecurrentfolder,andtodothatyouneedtoknowwhereyouare.Line16outputswhatitjustlearned.

Inline17,wecreateavariablecalled$target_pathandassignitavaluebyaddingtwostringstogetherusingthe.character.Thetwostringsweaddedarethecurrentdirectoryand/uploads/.Wearecreatingthetargetpathtospecifywherewewanttheuploadedfiletobeput—intheuploadsfolder.

Line18outputstheresultofthecalculationtosetthetargetpath.

Inline20wetweakthetargetpathyetagain,thistimeappendingtheoriginalfilenameoftheuploadedfiletoit.

Line21calculatesthenameofjusttheimagefilewithouttheentirefilepath.ThisisbecausewhenyouareworkingwithHTML<img>tags,youdon’thavetospecifytheentirepathoftheimage;youonlyneedtospecifywhereitisrelativetowhereyouare.

Lines22and24outputthevaluesofthesecalculationssoyoucanseewhatwastheresult.Ofcourse,ifthiswasa“real”websiteforausedcarlot,youwouldn’twantallthisextrainformationgoingtothebrowser.

Lines26movestheuploadedfilefromthetemporarylocationassignedbyPHPintothetargetpaththatyoucalculatedinline20.Line27informsyouofthisfact.

Next,wewanttocreatearecordintheimagestablethatpointstothisnewimagefile.Lines29to35setthestageforthistohappen.

Inline36wegetjustthenameoftheuploadedfile,withoutanypathinformationatall.Thisisbecausewejustwanttoinsertthenameofthefileintothedatabase.Whenreferringtothefilelaterwithan<IMG>tag,wecanalwaysspecifyapathifneeded.

Line37buildsthequerytoinserttherecordintothedatabase,andline38writesoutwhatthequeryis.Line38wasveryhelpfulwhileIwasoriginallywritingthisscript,becauseofcourseitdidn’tworkthefirsttimeItriedit.Seeingtheactualqueryisthefirststeptofiguringoutwhyaparticularquerydidnotwork.

Lines39to41createalinkthatallowsustoeasilyaddanotherimageforthiscarifwehaveone.

Lines42to51executethequeryandprintsouteitherasuccessorfailuremessage.Line52closestheconnectiontomySQL.

Line52createsanimagetagforthefilewejustuploadedsoyoucanseewhatitlookslike.WhenIfirstcreatedthistheimagesweresobigtheytookoverthewholescreen,soIaddedtheattributewidth=‘150’tokeeptheimagestoareasonablesize.Thistellsthebrowsertoresizetheimage.

PHPQuirksandTipsIntroductionEverylanguagehasitsquirks.AsIencounterthoseaspectsofPHPthatarenotimmediatelyintuitive,orifIfindagreattipthatcouldmakeyourlifeeasier,itwillgointothissection.

SingleQuotesvsDoubleQuotesWhenworkingwithstrings,itisimportanttounderstandthedifferenceinhowPHPtreatssinglequotes(echo‘Hello$name’;)ascomparedwithdoublequotes(echo“Hello$name”;)

Singlequotedstringswilldisplaythingsexactly“asis.”Variableswillnotbesubstitutedfortheirvalues.Thefirstexampleabove(echo‘Hello$name’;)willprintoutHello$name.

Doublequotestringswilldisplayahostofescapedcharactersandvariablesinthestringswillbesubstitutedfortheirvalues.Thesecondexampleabove(echo“Hello$name”)willprintoutHelloAlanifthe$namevariablecontains‘Alan’.

Thisisaneasythingtomixup,soreaditagain.:)

TheEqualSignTheequalsigncanoftenbeasourceofconfusion.Asingleequalsignisusedtoassignavaluetoavariable,forinstance$FirstName=‘Alan’;

Theequalsigncanalsobeusedtocomparetovalues,ifyouputtwoofthemtogetherandincludeitinanifstatement.Forinstance,$FirstName==‘Alan’willreturntrueforme,asthefollowingcodedemonstrates

Seethesamplecodecomparisons.php

ThequirkythingaboutthedoubleequaltestisthatPHPwillattempttoconvertthetwovariablesbeingcomparedintodifferenttypestoseeifitgetsamatch.Forinstance,if$a=1and$b=“1”youmightthinkthattheyarenotequalbecausetheyaredifferenttypes.(Oneisanumberandtheotherisastring.)

However,comparing$aand$busingthe==comparisonwillreturntrue,becauseifyouconvert$bfromthetypestringtothetypenumberthetwovariablesareequal.

Ifyouwanttotestiftwovaluesarethesamevalueandthesametype,youcomparethemusingthreeequalsigns.Thisway,$a===$bwouldreturnfalse.

ComparisonOperators

Ifyoucompareanumberwithastringorifthecomparisoninvolvesnumericalstrings,theneachstringisconvertedtoanumberandthecomparisonperformednumerically.Theserulesalsoapplytotheswitchstatement.Thetypeconversiondoesnottakeplacewhenthecomparisonis===or!==asthisinvolvescomparingthetypeaswellasthevalue.

SecurityConsiderationsIntroductionAswehaveseen,PHPisaveryeasylanguagetolearn,andmanypeoplewithoutanysortofformalbackgroundinprogrammingwilllearnitasawaytoaddinter-activitytotheirwebsites.

Unfortunately,thatoftenmeansPHPprogrammers,especiallythosenewertowebdevelopment,areunawareofthepotentialsecurityriskstheirwebapplicationscancontain.

Securityissomethingthatisoftenoverlookedwhendesigningawebproject,becausethereisn’treallyany“joy”inthinkingaboutsomeonehackingintoyourshinynewapplication.

Securityisadifficultthingtomeasure,anditisimpossibletosaywhetheranapplicationistrulysecureornot—thereareonlydegreesofsecurity.Naturally,themoreeffortyouputintomakinganapplicationsecure,themoresecureitwillbe.Thetrick,ofcourse,isfindingtherightbalanceintimeandeffort—andexpense.

Itisfairlyeasyandrelativelyinexpensivetoprovideasufficientlevelofsecurityformostapplications.However,ifyoursecurityneedsareverydemanding—becausetheinformationstoredinyourapplicationisveryvaluable(orverysensitive,likenuclearlaunchcodes)—thenyoumustensureahigherlevelofsecuritydespitetheincreasedcoststhatwillbeassociatedwithit.Remember,asecuritybreachcanalsobeveryexpensive.

BalancingSecurityandUsabilitySadly,manyofthestepstakentoincreasethesecurityofawebapplicationalsodecreaseitsusability.Passwords,sessiontime-outs,andaccesscontrollevelsandrolesallcreateobstaclesforlegitimateusers.Whilethesestepswillincreasethesecurityoftheapplication,youcan’thaveitsosecurethatnobodycanuseit.

Ididayear-pluscontractasadeveloperatanunnamedgovernmentagencythatclaimedtobeverysecurityconscious.Theyrequiredathoroughbackgroundcheckpriortoemployment,andeveryonehadtowearhigh-techbadgestomoveaboutthebuilding.Weevenhadguardsattheentrancetothebuilding.Itwas“sosecure”thatwehadtochangeourpasswordsevery30daystoapasswordwehadn’tusedbefore,andthatpasswordhadtobeatleast10characterslongandcontainnumbers,letters,mixedcase,andpunctuationmarks—anditcouldn’tbefoundinthedictionary.

Inshort,theyrequiredpasswordsthatnohumancouldactuallyremember,andthesystemwasnotveryusable.Ifyourcomputerwasidlefor15minutesormore,you’dbepromptedtotypeinthepasswordinagain.EveryoneIworkedwithonthatprojecthadtheirpasswordwrittendownonapieceofpaperrightnexttotheircomputer.Clearlythe“powersthatbe”inthesecuritydepartmenthadpickedsecurityoverusabilitytosuchanextremethattheverysecuritytheywereseekingwasutterlycompromised.

SQLInjectionOneofPHP’sgreateststrengthsistheeasewithwhichitcancommunicatewithdatabases,suchasMySQL.TheSam’sUsedCarLotexamplefromthisbookandthousandsofotherhighprofilewebsites,suchashttp://Facebook.com,relyondatabasestofunction.

Withthatstrengthalsocomesrisks.ThemostcommonsecurityhazardfacedwheninteractingwithadatabaseissomethingcalledSQLInjection-whenauserdeliberatelyusespartofyourapplicationtorununauthorizedandunintendedSQLqueriesonyourdatabase.

Let’suseacommonexample.Althoughwedidn’tcoveritinthisbook,manysystemsthataskausertologinfeaturealineofPHPcodethatlooksalotlikethisone:

Thescripttakestheusernameandpasswordthatwasenteredontheformandbuildsaqueryusingthetextenteredbytheuser.

Doesitlookfamiliar?You’llseemanyvariationsofthisasyourjourneyintotheJoyofPHPcontinues.Sowhat’stheproblem?Itdoesnotlooklikesuchcodecoulddomuchdamage.Butlet’ssayforamomentthatIenterthefollowingintothe“username”inputboxintheformandsubmitit:

‘OR1=1#

Thehashsymbol(#)tellsMySQLthateverythingfollowingitisacommentandtoignoreit.ThequerythatisgoingtobeexecutedbymySQLwillnowlooklikethis:

The#symboltellsmySQLtoignoreanytextthatfollows,leavingaWHEREstatementof‘WHEREUsername=”OR1=1’.Since1alwaysequals1,theWHEREclauseoftheSQLwillmatchforeveryrow—andhere’sthebadpart.Thequerywillreturnalloftheusernamesandpasswordsfromthedatabase.Whatmayhappennextisthatifthefirstusernameandpasswordcombinationistheadminuser,thenthepersonwhosimplyenteredafewsymbolsintoausernameboxisnowloggedinasyourwebsiteadministrator,asiftheyactuallyknewtheadmin’susernameandpassword,whichthey

probablydon’t,andshouldn’tknow.

Withalittlecreativitywhichisbeyondthescopeofthisbook,SQLInjectioncanbeusedtoaccomplishsomenastytricksyouprobablyneverthoughtofwhendesigningyourapplication.

Fortunately,itisprettyeasytoputuproadblocksthathelppreventthistypeofvulnerability.Bycheckingforapostrophesintheitemsweenterintothedatabase,andremovingorsubstitutingthem,wecanpreventanyonefromrunningtheirownSQLcodeonourdatabase.

Thefunctionbelowwoulddothetrick:

Nextwewouldneedtomodifyourquery.Insteadofdirectlyusingthe_POSTvariables,wewouldpassalluser-provideddatathroughthemake_safefunction,suchas:

Now,ifauserenteredthemaliciousdataabove,thequerywilllooklikethefollowing,whichisperfectlyharmless.Thefollowingquerywillselectfromadatabasewheretheusernameisequalto“'OR1=1#”.

Now,unlessyouhappentohaveauserwithaveryunusualusernameandablankpassword,yourattackerwillnotbeabletodoanydamage.

Itisimportanttocheckallthedatapassedtoyourdatabaselikethis,howeversecureyoumaythinkitis.

AdditionalResourcesSeealsohttp://www.addedbytes.com/articles/writing-secure-php/writing-secure-php-1/

http://phpsec.org/projects/guide/

AppendixA:InstallingPHPonaWebsiteHowtoinstallonaWindowsServerMicrosofthasconvenientlyautomatedtheentireprocessforMicrosoftservers.Allyouneedtodoisvisithttp://www.microsoft.com/web/gallery/install.aspx?appid=PHP53.

SupportedOperatingSystemsareWindows8,Windows7,WindowsVistaSP2,WindowsXPSP3+,WindowsServer2003SP2+,WindowsServer2008,WindowsServer2008R2,andWindowsServer2012.

YoumusthaveadministratorprivilegesonyourcomputertoruntheWebPlatformInstaller.

Here’sadocumentdescribinghowtoinstallPHPonWindowsServer2008http://www.howtogeek.com/50432/how-to-install-php-on-iis-7-for-windows-server-2008/

HowtoinstallonaLinuxServerAllLinuxdistributionscomewithPHP.However,itisrecommendedthatyoudownloadthelatestPHPsourcecode,compile,andinstallonLinux.ThiswillmakeiteasiertoupgradePHPonanongoingbasisimmediatelyafteranewpatchorreleaseisavailablefordownloadfromPHP.

TheGeekStuffprovidesagreatwalkthroughoftheprocess.

http://www.thegeekstuff.com/2008/07/instruction-guide-to-install-php5-from-source-on-linux/

Author’sNoteHello,andthankyouforreadingmybook.Asanewauthor,I’mespeciallyinterestedingettingyourfeedback,learningwhatyoulikedanddidn’t,andgrowingprofessionally.AsIsaidinthebeginningofthebook,[email protected].

Ifyoudidn’tlikethebook,pleaseemailmeandletmeknowhowIcouldimproveit.Ianswereveryonewhotakesthetimetohelpmeout,andthebookisalreadymuchbetterthanthefirsteditionthankstoreaderslikeyou.

Ifyoulikedthebook,IwouldsureappreciateifyouwouldtakeamomentandleavemeareviewonAmazonbyclickingthislink—>https://www.amazon.com/review/create-review?ie=UTF8&asin=B00BALXN70

Also,ifyoulikedmywritingstyleandwouldliketolearnaboutclientsidescripting,pleasecheckoutmyotherbest-seller,TheJoyofjQuery:ABeginner’sGuidetotheWorld’sMostPopularJavascriptLibrary

Thanksagain,andhappycoding!

ANotefromoneofmyKickstarterBackers….Personally,I’vebeenstrugglingwiththeprojectoflearningPHPforquitesometime.Therearemanytutorialsonline;somearebetter,whilstmostareplainterrible.I’llelaborate…

Wearebecomingincreasinglyimpatient,astheInternetismakingususedtotheconceptof‘hereandnow’.Weallmustadmitthatourattentionspanisratherlimited.Therefore,Ithinkthatweallcouldadmitthatthemostdifficultpartoflearninganewskillnowadaysisnottheunderstandingofthefield,butsittingyourselfdownandhavingthedisciplinetoseeitthrough.Learningisn’tentertaining,especiallyinthemostly-technicalfieldofprogramming.

That’swhythetitle‘TheJoyofPHPProgramming’caughtmyeyewhileshufflingthroughKickstarter.‘Joy’and‘programming’inthesamesentencewithintheconceptof‘learning’seemedsoutterlyuncommonthatIhavedecidedtotakealeapoffaithandinvestintheproject.“What’stheworstthatcouldhappen,”Iaskedmyself,“anotherblandPHPtutorial?”ButIsecretlyhopedthatsomethingspecialmightactuallyarisefromthegreatfaithinvestedbythe583othersupporters.

Thedecisionofshowcasingthebookinanearlystagehadcalmedme.Evenatthisearlystage,theentireapproachseemedverydifferentfromwhatI’veseenelsewhere.Thetextsareveryapproachableandeasytograsp-whichisperfectforpeoplelikeme.Imustsaythatittakesagreatdealofstrengthtowithholdmyselffromstartingthecourseatthecurrentstateofthebook,andwaitforthefinishedandrefinedproject.TheonlyexcuseIgivemyselfisthatIamsurethatAlanwillmanagetomakeitevenbetterthanthe“beta”.Whilewritingtheabove,IhaverealizedthatIactuallylookforwardtogettingthebookandtakingonthecourse…!

IwouldliketothankAlanfortakingonthismassiveproject,showinggoodsportsmanshipthroughouttheentireordeal,maintainingagreatlevelofcommunicationwithhistargetaudienceviathecommentsandfeedback,andtakingintoaccountmanyofthesuggestionspresentedtohim.Iamreallygladtoseeatechnicalauthorwhoprioritizeshisaudiencefirst,whilestillmanagingtodeliverhisvisionandmethod.IalsothankeachoftheothersupportersforhelpingAlanandsupportinghisidea.Iammostcertainthatweallwouldbenefitfarbeyondourmeredonation.

Enjoythereading!

-PashaKagan,soon-to-bePHPDeveloper