PHP &
MySQL
™Vikram Vaswani
McGraw-Hill/Osborne
NewYork Chicago SanFrancisco Lisbon London Madrid MexicoCity Milan NewDelhi SanJuan Seoul Singapore Sydney Toronto
Copyright © 2005 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United States of America. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher.
0-07-146654-1
The material in this eBook also appears in the print version of this title: 0-07-225795-4.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. For more information, please contact George Hoare, Special Sales, at [email protected] or (212) 904-4069.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
Dedication
Forthebaby: ane’er-fixedmark
thatlooksontempestsandisne’ershaken
AbouttheAuthor
VikramVaswaniisthefounderandCEOof
Melonfire(http://www.melonfire.com/),acompany specializinginsoftwareconsultancyandcontent creation/syndicationservices.Heisapassionate advocateoftheopen-sourcesoftwaremovementand frequentlycontributesarticlesandtutorialsonopen-sourcetechnologies,includingPerl,Python,PHP, MySQL,andLinuxtothecommunityatlargethrough hisweeklycolumnathttp://www.melonfire
.com/community/columns/trog/.Hislastbookwas
MySQL:TheCompleteReference(http://www.mysql-tcr.com/).
VikramhasovereightyearsofexperienceintheITworld,andhasspent sixofthoseyearsworkingwithPHPandMySQLasuser,administrator,and applicationdeveloper.HeistheauthorofZendTechnologies’PHP101seriesfor PHPbeginners(http://www.zend.com/php5/abs/),andhasextensiveexperience deployingPHPandMySQLinavarietyofdifferentenvironments(including corporateintranets,high-trafficInternetwebsites,andmission-criticalthinclient applications).
Acknowledgments .................................... xi Introduction ......................................... xiii
PART I LearningtheBasics
CHAPTER 1 IntroducingPHPandMySQL ........................ 3
Server-SideApplications ............................ 4 …AndtheDatabasesThatLoveThem .................. 5 ThePHPStory .................................... 7 History .................................... 8 Features ................................... 9 TheMySQLStory ................................. 11 History .................................... 11 Features ................................... 12 PHPandMySQL:TheWell-MatchedCouple ............. 16 Architecture ................................ 17 SampleApplications .......................... 19 Summary ....................................... 20
CHAPTER 2 SettingUpaPHP-MySQLDevelopmentEnvironment ...... 23
ObtainingtheSoftware ............................. 24 InstallingandConfiguringtheSoftware ................. 26 InstallingonUNIX ........................... 26 InstallingonWindows ......................... 35 TestingtheSoftware ............................... 50 TestingMySQL .............................. 50 TestingApache .............................. 51 TestingApacheandPHP ....................... 51 PerformingPostinstallationSteps ...................... 53 SettingtheMySQLSuper-UserPassword ........... 53 ConfiguringMySQLandApache
toStartAutomatically ....................... 54 Summary ....................................... 55
v
Contents
vi
HowtoDoEverythingwithPHP&MySQL
PART II LearningPHP
CHAPTER 3 UsingVariables,Statements,andOperators ............. 59
EmbeddingPHPinHTML .............................. 60 WritingStatementsandComments ....................... 63 StoringValuesinVariables .............................. 63 AssigningandUsingVariableValues ................ 65 SavingFormInputinVariables ..................... 65 UnderstandingSimpleDataTypes ........................ 66 DetectingtheDataTypeofaVariable ................ 67 UsingOperatorstoManipulateandCompareVariables ....... 70 UsingArithmeticOperators ........................ 70 UsingStringOperators ........................... 72 UsingComparisonOperators ...................... 72 UsingLogicalOperators .......................... 74 UsingtheAuto-Increment
andAuto-DecrementOperators .................. 75 UnderstandingOperatorPrecedence ................. 75 Summary ........................................... 76
CHAPTER 4 UsingConditionalStatementsandLoops ............... 79
AddingDecision-MakingCapabilities
withConditionalStatements .......................... 80 Usingtheif()Statement ........................ 81 Usingtheswitch()Statement ................... 84 NestingConditionalStatements .................... 86 MergingFormsandTheirResultPages
withConditionalStatements .......................... 86 RepeatingActionswithLoops ........................... 88 Usingthewhile()Loop ........................ 88 Usingthedo()Loop ............................ 89 Usingthefor()Loop ........................... 90 ControllingLoopIterationwithbreakandcontinue ..... 92 Summary ........................................... 93
CHAPTER 5 UsingArraysandCustomFunctions ................... 95
Contents
vii
CreatingUser-DefinedFunctions ......................... 106 DefiningandInvokingFunctions ................... 107 UsingArgumentsandReturnValues ................. 108 DefiningGlobalandLocalVariables ................ 110 ImportingFunctionDefinitions ..................... 112 Summary ........................................... 113
CHAPTER 6 UsingFiles,Sessions,Cookies,andExternalPrograms .... 115
ReadingandWritingFiles .............................. 116 ReadingDatafromaFile ......................... 116 WritingDatatoaFile ............................ 119 TestingFileAttributes ............................ 120 ObtainingDirectoryListings ....................... 122 ManagingSessionsandUsingSessionVariables ............. 123 CreatingaSessionandRegisteringSessionVariables ... 124 DestroyingaSession ............................. 125 StoringDatainCookies ................................ 126 SettingCookies ................................. 127 RetrievingCookieData ........................... 128 DeletingCookies ................................ 128 DealingwithDatesandTimes ...................... 129 ExecutingExternalPrograms ............................ 130 Summary ........................................... 131
CHAPTER 7 SampleApplication:Session-BasedShoppingCart ........ 133
UnderstandingRequirements ............................ 134 RetrievingCatalogData ................................ 134 CreatingtheShoppingCart ............................. 136 CalculatingCosts ..................................... 137 HandlingCartUpdates ................................. 138 PuttingItAllTogether ................................. 139 Summary ........................................... 144
PART III LearningMySQL
CHAPTER 8 UnderstandinganRDBMS .......................... 149
UnderstandingaRelationalDatabase ..................... 150 UnderstandingTables,Records,andFields ............ 151 UnderstandingPrimaryandForeignKeys ............ 151 UnderstandingSQLandSQLQueries ..................... 154 UnderstandingDatabaseNormalization .................... 156 UsingtheMySQLCommand-LineClient .................. 156 InteractingwithMySQLThroughaGraphicalClient ......... 159 Summary ........................................... 160
viii
HowtoDoEverythingwithPHP&MySQL
CHAPTER 9 WorkingwithDatabasesandTables ................... 161
CreatingDatabases .................................... 163 CreatingTables ....................................... 163 SpecifyingFieldDataTypes ....................... 164 SelectingtheMostAppropriateDataType ............ 168 AddingFieldModifiersandKeys ................... 168 SelectingaTableType ............................ 170 AlteringTables ....................................... 173 AlteringTableandFieldNames .................... 173 AlteringFieldProperties .......................... 173 AddingandRemovingFieldsandKeys .............. 174 AlteringTableTypes ............................. 175 BackingUpandRestoringDatabasesandTables ............ 175 BackingUpDatabasesandTables ................... 175 RestoringDatabasesandTablesfromBackup ......... 176 DroppingDatabasesandTables .......................... 177 ViewingDatabase,Table,andFieldInformation ............. 178 Summary ........................................... 180
CHAPTER 10 EditingRecordsandPerformingQueries ............... 181
InsertingRecords ..................................... 182 EditingandDeletingRecords ........................... 184 PerformingQueries ................................... 186 RetrievingSpecificColumns ....................... 187 FilteringRecordswithaWHEREClause ............. 187 UsingOperators ................................. 188 SortingRecordsandEliminatingDuplicates .......... 191 LimitingResults ................................ 192 UsingBuilt-InFunctions .......................... 193 GroupingRecords ............................... 194 JoiningTables .................................. 196 UsingSubqueries ................................ 201 UsingTableandColumnAliases .................... 203 Summary ........................................... 204
CHAPTER 11 UsingtheMySQLSecuritySystem ..................... 207
Contents
ix
CHAPTER 12 SampleApplication:OrderTrackingSystem ............. 219
UnderstandingRequirements ............................ 220 CreatinganOptimizedDatabaseDesign ................... 221 DesigningtheCustomerTables ..................... 221 DesigningtheProductTables ...................... 222 DesigningtheOrderTable ......................... 224 CreatingandPopulatingtheTables ....................... 225 QueryingtheDatabase ................................. 228 Summary ........................................... 236
PART IV UsingPHPwithMySQL
CHAPTER 13 QueryingaMySQLDatabasewithPHP ................. 239
UsingMySQLandPHPTogether ........................ 240 ManagingDatabaseConnections ......................... 244 PerformingQueries ................................... 247 ProcessingResultSets ................................. 248 QueriesWhichReturnData ........................ 248 QueriesThatAlterData ........................... 252 HandlingErrors ...................................... 254 UsingAncillaryFunctions .............................. 254 Summary ........................................... 257
CHAPTER 14 ValidatingUserInput .............................. 259
SettingInputConstraintsattheDatabaseLayer ............. 260 UsingtheNULLModifier ......................... 260 UsingtheUNIQUEModifier ...................... 262 UsingFieldDataTypes ........................... 263 ValidatingInputattheApplicationLayer .................. 264 CheckingforRequiredValues ...................... 264 RestrictingtheSizeofInputData ................... 266 CheckingtheTypeofInputData .................... 268 CheckingforIllegalInputValues ................... 274 ValidatingDates ................................. 277 ValidatingMultiple-ChoiceInput ................... 279 MatchingPatterns ............................... 281 Summary ........................................... 286
CHAPTER 15 FormattingQueryOutput ........................... 287
FormattingCharacterData .............................. 288 ConcatenatingStringValues ....................... 289 PaddingStringValues ............................ 293 AlteringStringCase ............................. 297 DealingwithSpecialCharacters .................... 300
x
HowtoDoEverythingwithPHP&MySQL
FormattingNumericData ............................... 306 UsingDecimalandCommaSeparators ............... 306 FormattingCurrencyValues ....................... 312 FormattingDatesandTimes ............................ 316 PaginatingLargeResultSets ............................ 325 Summary ........................................... 328
CHAPTER 16 SampleApplication:NewsPublishingSystem ............ 331
UnderstandingRequirements ............................ 332 DesigningtheDatabase ................................ 333 ListingandDisplayingNewsItems ....................... 334 ListingNewsItems .............................. 335 DisplayingStoryContent ......................... 339 ManipulatingNewsItems .............................. 342 ListingNewsItems .............................. 342 AddingNewsItems .............................. 344 DeletingNewsItems ............................. 349 EditingNewsItems .............................. 351 ProtectingtheAdministrationModule ..................... 358 Summary ........................................... 361
Iwrotethisbookoveraperiodofeightmonths,infitsandstarts,andwithnumerous breaksfortravel,research,examinations,collegeapplications,andotherequally stimulatingactivities.Needlesstosay,thisisn’tthebestwaytowork,andI’msure Istressedoutabunchofpeoplealongtheway.Thissectionistheirreward.
Firstandforemost,I’dliketothankmyfamily,forprovidingmewithaquiet placetowork,andfortheirforbearancewithmyoddworkhours(andevenodder behavior)whilethisbookwasbeingwritten.
TheeditorialandmarketingteamatMcGraw-Hill/Osbornehasbeenfabulous toworkwith,asusual.Thisismysecondbookwiththem,andtheyseemtoget betterandbetterwitheachone.AcquisitionseditorNancyMaragioglio,acquisitions coordinatorsAthenaHonoreandAlexanderMcDonald,technicaleditorSara Golemon,projecteditorMarkKarmendy,copyeditorMarciaBaker,andeditorial directorWendyRinaldiallguidedthisbookthroughthedevelopmentprocess.I’d liketothankthemfortheirexpertise,dedication,andeffortsonmybehalf.
PHPandMySQLhavegrownupoverthelastcoupleofyears,tothepoint wherethey’rebarelyrecognizablefromthetoddlerstheyoncewere.Theonly thingthathasn’tchangedishowmuchfunIhaveplayingwiththem.Special mention,then,ofZendTechnologiesandMySQLAB,bothofwhomhavebuilt twoincrediblycoolpiecesofsoftware.Keeprockin’,guys!
Finally,formakingtheentirebook-writingprocesslesstediousthanitusually is,thanksto:LawrenceBlock,BryanAdams,theStones,MADmagazine,Scott Adams,GaryLarson,MTV,Jamelia,KylieMinogue,Buffy,FarahMalegam, StephenKing,JohnleCarre,Subway,HarishKamath,BarryWhite,Steph Fox,Apple,RobertCrais,RobertB.Parker,BazLuhrmann,JonathanStroud, FHM,Canon,AnnaKournikova,Swatch,ZakGreant,Ling’sPavilion,Tonka, HBO,MarkTwain,thecastofTheWomanInBlack,TimBurton,PabloPicasso, RandyCosby,thecastofFriends,JohnSandford,theLondonTube,Jeroo Dayal,Pixar,Dido,Google.com,NicoleKidman,TheMatrix,AlfredHitchcock, BrunoD’Costa,WoodyAllen,PalmOne,SusannaClarke,SaïdBusinessSchool,
xi
Acknowledgments
xii
HowtoDoEverythingwithPHP&MySQL
xiii
Introduction
Ifyou’rereadingthisbook,youprobablyalreadyknowwhatPHPis—oneofthe world’smostpopularprogramminglanguagesforwebdevelopment.Flexible, scalable,easytoprogramin,andsupportedbyaninternationalcommunityof developersandusers,PHPistodayinuseonoverfifteenmillionwebsites,an impressiveachievement,especiallyconsideringthatthelanguagewasoriginally developedbyvolunteerswhomadeitssourcecodefreelyavailabletoanyonewho caredtoaskforit!
OneofthemostimportantfactorsdrivingPHP’spopularityoverthelastcouple ofyearshasbeenitssupportforavarietyofdatabases,includingMySQL,mSQL, Oracle,andMicrosoftAccess.Bysimplifyingandstreamliningdatabaseaccess,PHP enablesdeveloperstobuildcomplexdata-drivenwebapplications,whileenjoying shortdevelopmentcyclesbecauseofthesimplicityandflexibilityofthelanguage.
OneofthemostpowerfulcombinationsintheopensourcearenatodayisthePHP/ MySQLcombination.LikePHP,MySQLhasopen-sourceroots:itisafastand reliabledatabasemanagementsystemthatisrapidlyacquiringaworldwideuser base.ByusingPHPandMySQLtogether,userscanbenefitfromthecostsavings thataccompanycommunity-drivensoftware,andalsoleverageofftheimmense numberoffreelyavailablePHP/MySQLapplicationstoreducedevelopmentand deploymenttime.
That’swhereHowtoDoEverythingwithPHP&MySQLcomesin.Ifyou’re abusinessprofessionallookingtoreduceyoursoftwarecostsbyusingopen-source tools,adeveloperinterestedincreatingdatabase-backedapplicationsfortheWeb, orsimplyahobbyistcuriousaboutwhattheLinux,Apache,PHP,andMySQL (LAMP)combinationcando,thebookyou’reholdinginyourhandsisallyou’ll needtogetstartedonyourjourneyintotheworldofPHPandMySQL.
Overview
HowtoDoEverythingwithPHP&MySQLhasbeendesignedasacomprehensive tutorialthatwillteachdeveloperseverythingtheyneedtoknowtobegincreating database-backedwebapplications.ItcontainsinformationonboththePHP programmingtoolkitandtheMySQLRDBMS(includingcoverageofrelevant featuresinbothPHP5.xandMySQL4.1.x),andprovidesone-stopcoverageof softwareinstallation,languagesyntaxanddatastructures,flowcontrolroutines, built-infunctions,andbestpractices.
xiv
HowtoDoEverythingwithPHP&MySQL
EverychapterinHowtoDoEverythingwithPHP&MySQLcontainscode snippetsandexamplesthatyoucantryoutyourself.Theconceptstaughtineach ofthemainsectionsarefurtherillustratedwithasampleapplicationattheend ofeachsection;thissampleapplicationisapracticaltool,suchasaweb-based shoppingcartoranewspublishingsystem,whichyoucanimmediatelyuseand modifyforyourwebsite.
Audience
HowtoDoEverythingwithPHP&MySQListargetedatnovicewebdevelopers interestedinserver-sidescriptinganddatabaseusage.Suchdevelopersaretypically alreadyfamiliarwithHTML,CSS,andclient-sidescripting,andtheyarekeentoadd server-sideprogrammingskillstotheirrepertoire.ThePHP-MySQLcombination isoneofthemostpopularforserver-sideapplicationdevelopment,andthisbook providesaneasyintroductiontousingit.
Anumberofotherreadersegmentswillalsofindthisbookuseful:students lookingforafreeRDBMSonwhichtopracticetheirSQL,developersexperienced withotherprogramminglanguageswhonowwanttotranslatetheirskillstothePHP platform,individualsinterestedininexpensivelyaddingbellsandwhistles(online polls,discussionforums,andcontentmanagementtools)totheirpersonalwebsites, andadministratorsconcernedwithmigratingtheirdatatoanopen-sourceplatform. Thisbookcontainsthetheoryandpracticalexamplesneededtogetalltheseusers upandrunningwiththepowerfulPHP-MySQLcombination.
Unlikemanyotherbooks,HowtoDoEverythingwithPHP&MySQLdoesn’t assumepriorknowledgeofprogrammingordatabasefundamentals.Rather,it teachesbyexample,usingtutorialsandreal-worldexamplestoexplainbasic conceptsand,thus,increaseyourfamiliaritywithbothPHPprogrammingand MySQLusage.Throughoutthechaptersthatfollow,you’reencouragedtotryout thevariousexamplesonyourownLAMPinstallation.Youwon’tbreakanything, andyou’resuretogainagreatdealfromthehands-onexperience.
Organization
HowtoDoEverythingwithPHP&MySQLisstructuredprimarilyasatutorial,so it’sprobablybestifyoureadthechapterssequentially(thisisespeciallytruefor usersnewtobothtechnologies).Thatsaid,ifyou’realreadyfamiliarwitheither oneofthetwotechnologies,feelfreetoskipaheadtothebitsthatarenewtoyou.
HowtoDoEverythingwithPHP&MySQLisbroadlydividedintofoursections. Here’swhateachsectioncontains:
thehistoryandevolutionofPHPandMySQL,looksattheirindividualfeaturesets, andexplainswhythecombinationofthetwoissuchacompellingvalueproposition. Chapter2,SettingUpaPHP-MySQLDevelopmentEnvironmentdiscusseshow toobtain,install,configure,andtestaPHP-MySQLdevelopmentenvironment, forbothWindowsandUNIXusers.
PartIIfocusesonthebasicsofPHPprogramming,introducingyoutoPHP syntaxandlanguagestructuresanddemonstratingpracticalPHPapplicationsin thewebcontext.Chapter3,UsingVariables,Statements,andOperatorsgets youstartedwithPHP,byshowingyouhowtoembedPHPcodeinsideHTML documentsandusestatements,comments,variablesandoperators.Chapter4, UsingConditionalStatementsandLoopsteachesyoutousePHP’scomparison andlogicalinconditionalstatementsandloopstomakeyourPHPscriptsrespond intelligentlytodifferentevents.Chapter5,UsingArraysandCustomFunctions showsyouhowtogrouprelateddataintoPHParraysanddefineyourownfunctions forgreaterreusabilityofyourPHPcode.Chapter6,UsingFiles,Sessions, Cookies,andExternalProgramscontainsagrab-bagofcommontechniquesand toolsyouwillfindyourselfusingfrequentlyinyourPHPdevelopment.Chapter7, Session-BasedShoppingCartbuildsoneverythingtaughtthusfartocreate asession-basedshoppingcartyoucanplugintoyourwebsite.
PartIIIintroducestheMySQLRDBMS,teachingyouthebasiccommands andconceptsyouneedtouseitefficiently.Chapter8,Understandingan RDBMSgivesyouacrashcourseinbasicRDBMSconceptsandintroducesyou totheMySQLcommand-lineclient.Chapter9,WorkingwithDatabasesand TableslooksatthedatabaseandtablestructuresusedbyMySQLtostoreitsdata, andexplainstheSQLcommandstocreate,alter,anddeletedatabases,tables, andindexes.Chapter10,EditingRecordsandPerformingQueriescontinues wherethepreviouschapterleftoff,explaininghowtoinsertrecordsintoa MySQLdatabaseandusetheSELECTstatementtocreatefilteredsubsetsofthe recordsinadatabase;sort,group,andcountrecords;usesessionvariables;and importandexportdatainavarietyofdifferentformats.Chapter11,Usingthe MySQLSecuritySystemdiscussestheMySQLsecurityandprivilegesystem, andthemanagementofuseraccountsandpasswords(includingwhattodoifyou forgettheMySQLsuperuserpassword).Chapter12,OrderTrackingSystem takesyouthroughtheprocessofdesigningalarger,morechallengingdatabase forasmallbusiness’sordertrackingsystem,andalsoteachespracticaldatabase normalization.
PartIVbringsPHPandMySQLtogether,teachingyouthetoolsandtechniques youwillneedtoretrieveandusetheresultsofMySQLqueriesinadynamicweb application.Chapter13,QueryingaMySQLDatabasewithPHPexamines thebuilt-inMySQLsupportinPHP,andexplainshowitcanbeusedtoperform andprocessMySQLqueries.Chapter14,ValidatingUserInputteachesyouto
Introduction
xv
userinputbeforeitissavedtothesystem.Amongtheitemscovered:ensuring requiredfieldsareneverleftempty,validatingthelengthanddatatypeofuserinput, andusingregularexpressionstovalidatee-mailaddresses.Chapter15,Formatting QueryOutputdiscussescommontechniquesusedbyPHPdeveloperstomakethe resultsofMySQLqueriesmorereadableanduseful.BothPHPandMySQLcome withnumerousfunctionsforoutputmanipulationanddisplay,andthischapter explainshowtousethemonstrings,numbers,andtimestamps.Chapter16,Sample Application:NewsPublishingSystemconcludesthetutorial,usingeverything you’velearnedtobuildareal-worldapplicationthatretrievesdatafromaMySQL databasewithPHPtocreateanewspublishingsystemforapublicwebsite.
ConventionsUsedinThisBook
Thisbookusesdifferenttypesofformattingtohighlightspecialadvice.Here’salist:
■ Note Additionalinsightorinformationonthetopic.
■ Tip Atechniqueortricktohelpyoudothingsbetter.
■ Caution Somethingtowatchoutfor.
■ Howto… Instructionsoradviceforperformingaspecifictask.
■ Didyouknow? Informationthatistangentialtothetopicathand,but thatyoushouldknowabout.
Inthecodelistingsinthisbook,texthighlightedinboldisacommandtobe enteredattheprompt.Forexample,inthefollowinglisting:
mysql>INSERTINTOmovies(mtitle,myear)VALUES('RearWindow',1954);
QueryOK,1rowaffected(0.06sec)
thelineinboldisaquerythatyouwouldtypeinatthecommandprompt.Youcan usethisasaguidetotryoutthecommandsinthebook.
CompanionWebSite
Part IV
Learning
theBasics
Part I
Chapter 1
IntroducingPHP
andMySQL
4
HowtoDoEverythingwith
PHP&MySQLI
fyouthinkbackalittle,you’llrememberhowtheWebfirstbegan,withstatic HTMLpagesonwhichimagemapsandanimatedGIFswereconsideredcutting-edge.Andyou’llrememberhowwebusersclamoredformoreinteractivityonthose staticpages,interactivitythatbecamesimpleroncedynamicHTMLandJavaScript becamestandardaccessoriesforyourInternetbrowser.Well,itisn’tyourgrandmother’sWebanymore....
ThecurrentgenerationofwebdesignersthinksnothingofanimatedGIFs andpop-upboxes,preferringinsteadtousebrightlycoloredFlashanimationand livevideofeeds.Andthat’sjustwhatthey’redoinginyourbrowser.Asimilar revolutionhasbeentakingplaceinthebackroom,withthecurrentcropofserver-sidelanguagesgivingwebdevelopersabrandnewsandboxtoplayin.
That’swherethisintroductorychaptercomesin.Thenextfewpagesgiveyou aquickoverviewofhowserver-sidescriptingcanbecombinedwithadatabase systemtocreatesomeusefulandpowerfulapplications.Thischapteralsointroduces youtothestarsofthisbook—PHPandMySQL—explainingwhattheyare,how theycameintobeing,andwhytheymakesuchagoodcouple.
Server-SideApplications…
Server-sidescriptingisnotnew.It’sbeenaroundforquiteawhile,andalmost everymajorwebsiteusessomeamountofserver-sidescripting.Amazon.com usesittofindthebookyou’relookingfor,Yahoo!usesittostoreyourpersonal preferences,andeBayusesittoprocessyourcreditcardnumberforthatgigantic eight-headedstoneeagleyoujustbought.Whathaschanged,however,isthatit’s nolongerthedomainofthebigguns—asprogramminglanguageshavematuredand thebarrierstoentryhavelowered,independentwebpublishersareincreasingly usingserver-sidetechnologiestodeliverabetterexperiencetotheirusers.
CHAPTER1: Introducing
PHPandMySQL
5
Server-sidescriptsrunonthewebserver,usuallyapowerfulUNIXorMicrosoft WindowssystemwithoodlesofRAMandCPUcycles;theycan,therefore,beused toaccessserverresources,suchasdatabasesorexternalfiles,andperformmore sophisticatedtasksthanregularclient-sidescripting.Forexample,aserver-side scriptcouldstoreauser’sshoppingcartinadatabase,andretrieveitontheuser’s nextvisittosavehimsometimereselectingitemsforpurchase;thistranslates intoanimprovedcustomerexperience(anditdoesn’tmatterwhichcomputerthe userlogsinfrom,becausethesettingsareallontheserverand,thus,arealways available).
…AndtheDatabasesThatLoveThem
Thelargemajorityofserver-sidescriptsarerelatedtoeithergettinginformation fromtheuserandsavingitsomewhere,orretrievinginformationfromsomewhere andpresentingit.This“somewhere”isusuallyananimalcalledadatabase,andif you’reatallseriousaboutbuildingusefulwebapplications,you’regoingtoneed tomakefriendswithit.
Adatabase,fundamentally,isacollectionofdataorganizedandclassified accordingtosomecriteria.Thetraditionalanalogyisthatofafilingcabinet containingmanydrawers,witheachdrawerholdingfilesrelatedtoaparticular subject.Thisorganizationofinformationintodrawersandfilesmakesiteasyto retrievespecificbitsofinformationquickly—tolayyourhandsonaparticular pieceofinformation,youpullopentheappropriatedrawerandselectthefile(s) youneed.
AFineBalance
Justbecauseyoucandoalotmorewithserver-sidescriptsdoesn’tmeanthat yougettobinyourcopyoftheJavaScriptmanual.Often,client-sidescripting isthemostefficientwaytoperformtaskslocalizedtotheuserinterface.It’s hardtoimagine,forexample,howaserver-sidescriptcouldhelpwithan imagerolloverorapagetransitioneffect.Similarly,whendealingwithuser inputinwebforms,client-sidechecksareanecessaryfirststeptoverifyingthe validityofentereddata;performingbasicchecksontheclientalertstheuser toerrorsfasterandreducesthenumberofround-tripstotheserver.Ajudicious mixofthetwoisthusessentialtocreatingwebapplicationsthatarefastand easytouse,yetrobustanderror-free.
1
6
HowtoDoEverythingwith
PHP&MySQLAnelectronicdatabasemanagementsystem(DBMS)helpsyouorganize informationandprovidesaframeworktoaccessitquicklyandefficiently.The drawersthatcontainthefilesarereferredtoindatabaseparlanceastables,while thefilesthemselvesarecalledrecords.Theactofpullingoutinformationis referredtoasaquery,andit’susuallyexpressedusingStructuredQueryLanguage (SQL).Theresultingdataisreferredtoasaresultset.Thesetermsmightseem foreigntoyouatthemoment,butbytheendofthisbook,you’llbetossingthem aroundlikeapro.
Arelationaldatabasemanagementsystem(RDBMS)takesthingsonestep furtherbycreatingrelationshipsamongthetablesthatmakeupadatabase.These relationshipscanthenbeusedtocombinedatafrommultipletables,allowing differentperspectivesandmoreusefulreports.Bycreatinglinksamongrelated piecesofinformation,anRDBMSnotonlymakesitpossibletostoreinformation moreefficiently(byremovingredundanciesandrepetition),butitalsomakes visiblepreviouslyundiscoveredrelationshipsamongdisparatesegmentsofdata andpermitsefficientexploitationofthoserelationships.
Thus,server-sidescriptinglanguagesandrelationaldatabasemanagement systemspossessuniquecapabilitiesandadvantagesintheirownright.Putthem together,however,andtheworldreallyisyouroyster:thecombinationofthe twomakesitpossibletocreateinnovativeproductsandservicesthatenhance thecustomerexperience,simplifyandspeedbusinessprocesses,andenablenew Internetapplications.
Theseareamongthethingsyoucandowithserver-sidescriptsandanRDBMS:
■ Buildasearchenginethatrespondstouserqueries
■ Recorduserinputprovidedthroughwebformsandsaveitforfuture reference
■ Createwebsitesthatdynamicallyupdatethemselveswithnewcontent
■ Manageablog(ormorethanone)
■ Processelectronicpaymentsandtrackcustomerorders
■ Buildcustomizedbargraphs,piecharts,andotherstatisticalreportsfrom rawnumericdata
CHAPTER1: Introducing
PHPandMySQL
7
Inrecentyears,oneofthemostpopularcombinationsinthiscontexthasbeen thePHPscriptinglanguageandtheMySQLRDBMS.Thefollowingsection discussesthesetwoproductsindetail,highlightingthecapabilitiesandfeatures ofeach,andillustratingjustwhytheyworksowelltogether.
ThePHPStory
Accordingtoitsofficialwebsiteathttp://www.php.net/,PHPis“...awidely usedgeneral-purposescriptinglanguagethatisespeciallysuitedforweb developmentandcanbeembeddedintoHTML...themaingoalofthelanguage istoallowwebdeveloperstowritedynamicallygeneratedwebpagesquickly.” InEnglish,whatthismeansisthatPHPisaprogramminglanguagethatmakes itpossibletoincorporatesophisticatedbusinesslogicintootherwisestaticweb sites.Thelanguageisrapidlybecomingthepopularchoicefordata-drivenweb applicationsbecauseofitswidesupportfordifferentdatabasesystems.
Typically,PHPcodeis“embedded”insidearegularHTMLdocument,and isrecognizedandexecutedbythewebserverwhenthedocumentisrequested throughabrowser.BecausePHPisafull-featuredprogramminglanguage,you cancodeallmannerofcomplexthingummiesintoyourwebpagesusingthis technique;theserverwillexecuteyourcodeandreturntheoutputtothebrowser intheformatyouspecify.BecausePHPcodeisexecutedontheserverandnoton theclient,developersdon’thavetoworryaboutbrowser-specificquirksthatcould causethecodetobreak(ascommonlyhappenswithJavaScript);PHPcodeworks independentlyoftheuser’swebbrowser.
Now,whilethisisfineanddandy,youmightbewonderingexactlywhat makesPHPsopopular.Afterall,webdevelopershavebeencreatingPerl/CGI scriptstodynamicallygenerateHTMLpagesforalongtime,andthegradual adoptionofW3CstandardsbymodernbrowservendorshasmadeJavaScriptfar lesssusceptibletothevagariesofproprietaryextensions.SowhatmakesPHPthe preferredwebscriptinglanguagefordevelopersaroundtheworld?
I’vealwaysthoughtthereasonforPHP’spopularitytobefairlysimple:ithas theuniquedistinctionofbeingtheonlyopen-sourceserver-sidescriptinglanguage that’sbotheasytolearnandextremelypowerfultouse.Unlikemostmodern server-sidelanguages,PHPusesclear,simplesyntaxanddelightsinnonobfuscated code;thismakesiteasytoreadandunderstand,andencouragesrapidapplication development.Andthen,ofcourse,there’scostandavailability—PHPisavailable freeofchargeontheInternet,foravarietyofplatformsandarchitectures,including UNIX,MicrosoftWindows,andMacOS,aswellasformostwebservers.
1
8
HowtoDoEverythingwith
PHP&MySQLGeekswillbehappytohearPHPisaninterpretedlanguage.Whyisthis good?Well,oneadvantageofaninterpretedlanguageisthatitenablesyouto performincremental,iterativedevelopmentandtestingwithoutgoingthrough acompile-test-debugcycleeachtimeyouchangeyourcode.Thiscanspeedthe developmentcycledrastically.Avarietyofdatatypes,apowerfulobject-oriented engine,anextensivelibraryofbuilt-infunctions,andsupportformostcurrentweb technologiesandprotocolscompletethepicture.
Abonus,especiallyfordevelopersbuildingwebapplicationsthatmust interfacewithadatabase,isPHP’ssupportfortheMySQLRDBMS,aswellas othercommercialdatabasesystems;thissupportistheprimarydrawforweb developersdealingwithdata-heavywebapplications,likecontentportalsor electronic-commerceapplications.Theclose-knitrelationshipbetweenPHPand MySQL,bothopen-sourceprojects,makespossiblesomepowerfulsynergies. Seethesection“SampleApplications”attheendofthischapterforexamples.
Thesky’sthelimit...foralistofwhatyoucandowithPHP,seethe PHPmanualathttp://www.php.net/manual/en/intro-whatcando.php.
History
ThefirstversionofPHP,PHP/FI,wasdevelopedbyRasmusLerdorfasameansof monitoringpageviewsforhisonlineresum´eandslowlystartedmakingamarkin mid1995.ThisversionofPHPhadsupportforsomebasicfunctions,primarilythe capabilitytohandleformdataandsupportforthemSQLdatabase.PHP/FI1.0was followedbyPHP/FI2.0and,inturn,quicklysupplantedin1997byPHP3.0.
PHP3.0,developedbyAndiGutmansandZeevSuraski,waswherethings startedtogetinteresting.PHP3.0wasacompleterewriteoftheoriginalPHP/FI implementationanditincludedsupportforawiderrangeofdatabases,including MySQLandOracle.PHP3.0’sextensiblearchitectureencouragedindependent developerstobegincreatingtheirownlanguageextensions,whichservedto increasethelanguage’spopularityinthedevelopercommunity.Beforelong, PHP3.0wasinstalledonhundredsofthousandsofwebservers,andmoreand morepeoplewereusingittobuilddatabase-backedwebapplications.
CHAPTER1: Introducing
PHPandMySQL
9
versionofPHP,PHP5.0,offersacompletelyrevampedobjectmodelthatuses objecthandlesformoreconsistentbehaviorwhenpassingobjectsaround,aswell asabstractclasses,destructors,multipleinterfaces,andclasstypehints.
PHP5.0alsoincludesbetterexceptionhandling,amoreconsistentXML toolkit,improvedMySQLsupport,andabettermemorymanager.Sofar,allthese changeshaveconspiredtomakePHP5.0thebestPHPreleaseinthelanguage’s ten-yearhistory...afactamplyillustratedbytheApril2004Netcraftsurvey, whichshowsPHPinuseonoverfifteenmillionwebsites.
Features
AsaprogramminglanguagefortheWeb,PHPishardtoignore.Cleansyntax, object-orientedfundamentals,anextensiblearchitecturethatencouragesinnovation, supportforbothcurrentandupcomingtechnologiesandprotocols,andexcellent databaseintegrationarejustsomeofthereasonsforthepopularityitcurrently enjoysinthedevelopercommunity.
Simplicity
BecausePHPusesaconsistentandlogicalsyntax,andbecauseitcomeswith aclearlywrittenmanual,evennovicesfinditeasytolearn.Infact,thequickest waytolearnPHPistostepthroughthemanual’sintroductorytutorial,andthen startlookingatcodesamplesofftheWeb.Withinafewhours,you’llhavelearned thebasicsandwillbeconfidentenoughtobeginwritingyourownscripts.This adherencetotheKISS(KeepItSimple,Stupid)principlehasmadePHPpopular asaprototypingandrapidapplicationdevelopmenttoolforwebapplications.PHP canevenaccessClibrariesandtakeadvantageofprogramcodewrittenforthis language,andthelanguageisrenownedforthetremendousflexibilityitallows programmersinaccomplishingspecifictasks.
Portability
Withprogramminglanguages,portability—theeasewithwhichaprogramcan bemadetoworkondifferentplatforms—isanimportantfactor.PHPusershave littletofearhere,becausecross-platformdevelopmenthasbeenanimportant designgoalofPHPsincePHP3.0.Today,PHPisavailableforawidevarietyof platforms,includingUNIX,MicrosoftWindows,MacOS,andOS/2.Additionally, becausePHPcodeisinterpretedandnotcompiled,PHPscriptswrittenonone platformusuallyworkasisonanyotherplatformforwhichaninterpreterexists. ThismeansthatdeveloperscancodeonWindowsanddeployonUNIXwithout anymajordifficulties.
1
10
HowtoDoEverythingwith
PHP&MySQLSpeed
Outofthebox,PHPscriptsrunfasterthanmostotherscriptinglanguages,with numerousindependentbenchmarksputtingthelanguageaheadofcompeting alternativeslikeJSP,ASP.NET,andPerl.WhenPHP4.0wasfirstreleased,it raisedtheperformancebarwithitscompletelynewparsingengine.PHP5.0 improvesperformanceevenfurtherthroughtheuseofanoptimizedmemory manager,andtheuseofobjecthandlesthatreducememoryconsumptionand helpapplicationsrunfaster.
OpenSource
PossiblythebestthingaboutPHPisthatit’sfree—itssourcecodeisfreely availableontheWeb,anddeveloperscaninstallanduseitwithoutpayinglicensing feesorinvestinginexpensivehardwareorsoftware.UsingPHPcanthussignificantly reducethedevelopmentcostsofasoftwareapplication,withoutcompromisingon eitherreliabilityorperformance.Theopen-sourceapproachalsoensuresfasterbug fixesandquickerintegrationofnewtechnologiesintothecorelanguage,simply duetothemuchlargerbaseofinvolveddevelopers.
Extensible
Keepingfuturegrowthinmind,PHP’screatorsbuiltanextensiblearchitecture thatenablesdeveloperstoeasilyaddsupportfornewtechnologiestothelanguage throughmodularextensions.ThisextensibilitykeepsPHPfreshandalwaysat thecuttingedgeofnewtechnology.Toillustratethis,considerwhatPHPletsyou dothroughitsadd-onmodules:dynamicallycreateimage,PDF,andSWFfiles; connecttoIMAPandPOP3servers;interfacewithMySQL,Oracle,PostgreSQL, andSQLitedatabases;handleelectronicpayments;parseXMLdocuments;and executePerl,Java,andCOMcodethroughaPHPscript.Andasifallthatwasn’t enough,there’salsoanonlinerepositoryoffreePHPclassescalledPEAR,the PHPExtensionandApplicationRepository,whichprovidesasourceofreusable, bug-freePHPcomponents.
XMLandDatabaseSupport
CHAPTER1: Introducing
PHPandMySQL
11
Sybase,andSQLite.Alternatively,ifit’sXMLyou’reafter,PHP5.0offers acompletelyredesignedXMLAPIbuiltaroundthelibxml2toolkit;thisAPI supportsSAX,DOM,andXSLT,aswellasthenewSimpleXMLandSOAP extensions.
TheSimpleXMLextensionisparticularlynote-worthy—ittakesallthe painoutofparsingXMLbyrepresentinganXMLfileasaPHPobject. ThisobjectcanthenbeprocessedusingstandardPHPconstructslike loopsandindexes.
Andspeakingofdatabases....
TheMySQLStory
Ifyou’vehadeventheslightestbitofexperiencewithrelationaldatabases,you’ve probablyheardofMySQL:It’sahigh-performance,multiuserrelationaldatabase managementsystemthatistodaythedefactostandardfordatabase-drivensoftware applications,bothonandofftheWeb.
Designedaroundthreefundamentalprinciples—speed,stability,andeaseof use—andfreelyavailableundertheGNUGeneralPublicLicense,MySQLhasbeen dubbed“theworld’smostpopularopen-sourcedatabase”byitsparentcompany, MySQLAB.Andwithgoodreason.Officialstatisticsrevealoverfivemillionsites arecreating,using,anddeployingMySQL-basedapplications,withmorecoming intothefoldonadailybasis.YoumayevenhaveheardofsomeofMySQL’s customers:dothenamesYahoo!,Google,Cisco,NASA,andHPsoundfamiliar?
History
TheMySQLstoryhasn’talwaysbeenaboutrocketinggrowthratesandhigh usersatisfactionratings,however.MySQLhasaninterestinghistory,withroots goingbackto1979,whenMichael“Monty”Wideniuscreatedadatabasesystem namedUNIREGfortheSwedishcompanyTcX.UNIREGdidn’tworkforTcXon accountofperformanceissues,andsoTcXbeganasearchforalternatives.They triedmSQL,acompetingDBMScreatedbyDavidHughes,butwhenthatattempt alsofailed,anewapproachwascalledfor.Thus,Wideniusdecidedtocreateanew databaseservercustomizedtohisspecificrequirements,butbasedonthemSQL API(tosimplifyportingapplicationsbetweenthetwo).Thatsystem,completed andreleasedtoasmallgroupinMay1996,becameMySQL1.0.