McGraw Hill.Osborne.How.to.Do.Everything.with.PHP.and.MySQL.eBook.Feb.2005.eBook LinG
TEAM LinG
PHP &
MySQL
™
Vikram Vaswani
McGraw-Hill/Osborne
NewYork Chicago SanFrancisco Lisbon
London Madrid MexicoCity Milan NewDelhi
SanJuan Seoul Singapore Sydney Toronto
TEAM LinG
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 McGrawHill’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.
DOI: 10.1036/0071466541
TEAM LinG
Dedication
Forthebaby:
ane’er-fixedmark
thatlooksontempestsandisne’ershaken
TEAM LinG
AbouttheAuthor
VikramVaswaniisthefounderandCEOof
Melonfire(http://www.melonfire.com/),acompany
specializinginsoftwareconsultancyandcontent
creation/syndicationservices.Heisapassionate
advocateoftheopen-sourcesoftwaremovementand
frequentlycontributesarticlesandtutorialsonopensourcetechnologies,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).
Whenhe’snotplottingtoruletheworldfromaheavilyguardedconference
roomatMelonfireHQ,Vikramamuseshimselfbyreadingcrimefiction,watching
oldmovies,playingsquash,fiddlingwithhisever-growingcollectionofelectronic
gadgets,andkeepinganeyeoutforunfriendlyagents.Readmoreabouthim,
downloadsamplecode,andconnectwithotheropen-sourceenthusiastsonline
athttp://www.everythingphpmysql.com/.
TEAM LinG
For more information about this title, click here
Contents
Acknowledgments ....................................
Introduction .........................................
PART I
CHAPTER 1
CHAPTER 2
LearningtheBasics
IntroducingPHPandMySQL ........................
3
Server-SideApplications ............................
…AndtheDatabasesThatLoveThem ..................
ThePHPStory ....................................
History ....................................
Features ...................................
TheMySQLStory .................................
History ....................................
Features ...................................
PHPandMySQL:TheWell-MatchedCouple .............
Architecture ................................
SampleApplications ..........................
Summary .......................................
4
5
7
8
9
11
11
12
16
17
19
20
SettingUpaPHP-MySQLDevelopmentEnvironment ......
ObtainingtheSoftware .............................
InstallingandConfiguringtheSoftware .................
InstallingonUNIX ...........................
InstallingonWindows .........................
TestingtheSoftware ...............................
TestingMySQL ..............................
TestingApache ..............................
TestingApacheandPHP .......................
PerformingPostinstallationSteps ......................
SettingtheMySQLSuper-UserPassword ...........
23
ConfiguringMySQLandApache
toStartAutomatically .......................
Summary .......................................
xi
xiii
24
26
26
35
50
50
51
51
53
53
54
55
v
TEAM LinG
vi
HowtoDoEverythingwithPHP&MySQL
PART II
LearningPHP
CHAPTER 3
UsingVariables,Statements,andOperators .............
59
EmbeddingPHPinHTML ..............................
WritingStatementsandComments .......................
StoringValuesinVariables ..............................
AssigningandUsingVariableValues ................
SavingFormInputinVariables .....................
UnderstandingSimpleDataTypes ........................
DetectingtheDataTypeofaVariable ................
UsingOperatorstoManipulateandCompareVariables .......
UsingArithmeticOperators ........................
UsingStringOperators ...........................
UsingComparisonOperators ......................
UsingLogicalOperators ..........................
UsingtheAuto-Increment
andAuto-DecrementOperators ..................
UnderstandingOperatorPrecedence .................
Summary ...........................................
60
63
63
65
65
66
67
70
70
72
72
74
UsingConditionalStatementsandLoops ...............
79
CHAPTER 4
AddingDecision-MakingCapabilities
withConditionalStatements ..........................
Usingtheif()Statement ........................
Usingtheswitch()Statement ...................
NestingConditionalStatements ....................
MergingFormsandTheirResultPages
withConditionalStatements ..........................
RepeatingActionswithLoops ...........................
Usingthewhile()Loop ........................
Usingthedo()Loop ............................
Usingthefor()Loop ...........................
ControllingLoopIterationwithbreakandcontinue .....
Summary ...........................................
CHAPTER 5
75
75
76
80
81
84
86
86
88
88
89
90
92
93
UsingArraysandCustomFunctions ...................
95
UsingArraystoGroupRelatedValues .....................
CreatinganArray ...............................
ModifyingArrayElements ........................
ProcessingArrayswithLoops ......................
GroupingFormSelectionswithArrays ...............
UsingArrayFunctions ............................
96
98
99
100
102
104
TEAM LinG
Contents
CreatingUser-DefinedFunctions .........................
DefiningandInvokingFunctions ...................
UsingArgumentsandReturnValues .................
DefiningGlobalandLocalVariables ................
ImportingFunctionDefinitions .....................
Summary ...........................................
CHAPTER 6
106
107
108
110
112
113
UsingFiles,Sessions,Cookies,andExternalPrograms .... 115
ReadingandWritingFiles ..............................
ReadingDatafromaFile .........................
WritingDatatoaFile ............................
TestingFileAttributes ............................
ObtainingDirectoryListings .......................
ManagingSessionsandUsingSessionVariables .............
CreatingaSessionandRegisteringSessionVariables ...
DestroyingaSession .............................
StoringDatainCookies ................................
SettingCookies .................................
RetrievingCookieData ...........................
DeletingCookies ................................
DealingwithDatesandTimes ......................
ExecutingExternalPrograms ............................
Summary ...........................................
CHAPTER 7
vii
116
116
119
120
122
123
124
125
126
127
128
128
129
130
131
SampleApplication:Session-BasedShoppingCart ........ 133
UnderstandingRequirements ............................
RetrievingCatalogData ................................
CreatingtheShoppingCart .............................
CalculatingCosts .....................................
HandlingCartUpdates .................................
PuttingItAllTogether .................................
Summary ...........................................
134
134
136
137
138
139
144
PART III
LearningMySQL
CHAPTER 8
UnderstandinganRDBMS .......................... 149
UnderstandingaRelationalDatabase .....................
UnderstandingTables,Records,andFields ............
UnderstandingPrimaryandForeignKeys ............
UnderstandingSQLandSQLQueries .....................
UnderstandingDatabaseNormalization ....................
UsingtheMySQLCommand-LineClient ..................
InteractingwithMySQLThroughaGraphicalClient .........
Summary ...........................................
150
151
151
154
156
156
159
160
TEAM LinG
viii
HowtoDoEverythingwithPHP&MySQL
CHAPTER 9
WorkingwithDatabasesandTables ................... 161
CreatingDatabases ....................................
CreatingTables .......................................
SpecifyingFieldDataTypes .......................
SelectingtheMostAppropriateDataType ............
AddingFieldModifiersandKeys ...................
SelectingaTableType ............................
AlteringTables .......................................
AlteringTableandFieldNames ....................
AlteringFieldProperties ..........................
AddingandRemovingFieldsandKeys ..............
AlteringTableTypes .............................
BackingUpandRestoringDatabasesandTables ............
BackingUpDatabasesandTables ...................
RestoringDatabasesandTablesfromBackup .........
DroppingDatabasesandTables ..........................
ViewingDatabase,Table,andFieldInformation .............
Summary ...........................................
CHAPTER 10
EditingRecordsandPerformingQueries ............... 181
InsertingRecords .....................................
EditingandDeletingRecords ...........................
PerformingQueries ...................................
RetrievingSpecificColumns .......................
FilteringRecordswithaWHEREClause .............
UsingOperators .................................
SortingRecordsandEliminatingDuplicates ..........
LimitingResults ................................
UsingBuilt-InFunctions ..........................
GroupingRecords ...............................
JoiningTables ..................................
UsingSubqueries ................................
UsingTableandColumnAliases ....................
Summary ...........................................
CHAPTER 11
163
163
164
168
168
170
173
173
173
174
175
175
175
176
177
178
180
182
184
186
187
187
188
191
192
193
194
196
201
203
204
UsingtheMySQLSecuritySystem ..................... 207
UnderstandingtheNeedforAccessControl ................
UnderstandingHowMySQLAccessControlWorks ..........
Assigning,Revoking,andViewingUserPrivileges ..........
WorkingwithUserAccountsandPassword ................
CreatingandRemovingUserAccounts ..............
AlteringUserPasswords ..........................
Summary ...........................................
208
209
210
213
214
215
217
TEAM LinG
Contents
CHAPTER 12
SampleApplication:OrderTrackingSystem ............. 219
UnderstandingRequirements ............................
CreatinganOptimizedDatabaseDesign ...................
DesigningtheCustomerTables .....................
DesigningtheProductTables ......................
DesigningtheOrderTable .........................
CreatingandPopulatingtheTables .......................
QueryingtheDatabase .................................
Summary ...........................................
PART IV
CHAPTER 13
QueryingaMySQLDatabasewithPHP ................. 239
240
244
247
248
248
252
254
254
257
ValidatingUserInput .............................. 259
SettingInputConstraintsattheDatabaseLayer .............
UsingtheNULLModifier .........................
UsingtheUNIQUEModifier ......................
UsingFieldDataTypes ...........................
ValidatingInputattheApplicationLayer ..................
CheckingforRequiredValues ......................
RestrictingtheSizeofInputData ...................
CheckingtheTypeofInputData ....................
CheckingforIllegalInputValues ...................
ValidatingDates .................................
ValidatingMultiple-ChoiceInput ...................
MatchingPatterns ...............................
Summary ...........................................
CHAPTER 15
220
221
221
222
224
225
228
236
UsingPHPwithMySQL
UsingMySQLandPHPTogether ........................
ManagingDatabaseConnections .........................
PerformingQueries ...................................
ProcessingResultSets .................................
QueriesWhichReturnData ........................
QueriesThatAlterData ...........................
HandlingErrors ......................................
UsingAncillaryFunctions ..............................
Summary ...........................................
CHAPTER 14
ix
260
260
262
263
264
264
266
268
274
277
279
281
286
FormattingQueryOutput ........................... 287
FormattingCharacterData ..............................
ConcatenatingStringValues .......................
PaddingStringValues ............................
AlteringStringCase .............................
DealingwithSpecialCharacters ....................
288
289
293
297
300
TEAM LinG
x
HowtoDoEverythingwithPHP&MySQL
FormattingNumericData ...............................
UsingDecimalandCommaSeparators ...............
FormattingCurrencyValues .......................
FormattingDatesandTimes ............................
PaginatingLargeResultSets ............................
Summary ...........................................
CHAPTER 16
306
306
312
316
325
328
SampleApplication:NewsPublishingSystem ............ 331
UnderstandingRequirements ............................
DesigningtheDatabase ................................
ListingandDisplayingNewsItems .......................
ListingNewsItems ..............................
DisplayingStoryContent .........................
ManipulatingNewsItems ..............................
ListingNewsItems ..............................
AddingNewsItems ..............................
DeletingNewsItems .............................
EditingNewsItems ..............................
ProtectingtheAdministrationModule .....................
Summary ...........................................
332
333
334
335
339
342
342
344
349
351
358
361
Index .......................................... 363
TEAM LinG
Acknowledgments
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
TEAM LinG
Copyright © 2005 by The McGraw-Hill Companies. Click here for terms of use.
xii
HowtoDoEverythingwithPHP&MySQL
LondonBusinessSchool,AnahitaMarker,MichaelSchumacher,MarkHaddon,
Mambo’sandTito’s,KalindiMehta,JohnKerry,HumphreyBogart,theLibrary
Bar,BombayTravels,Amazon.com,U2,TheThreeStooges,OscarWilde,Punch,
HarryPotter,ScottTurow,SlackwareLinux,CalvinandHobbes,Vincentvan
Gogh,FionaD’Silva,KelleyArmstrong,BlizzardEntertainment,DharaDusija,
StanfordUniversity,PopeyeandOlive,DennisLehane,Trattoria,XerxesAntia,
DireStraits,BruceSpringsteen,DavidMitchell,andallmyfriends,athomeand
elsewhere.
TEAM LinG
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.
xiii
TEAM LinG
Copyright © 2005 by The McGraw-Hill Companies. Click here for terms of use.
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:
PartIprovidesanintroductiontoPHPandMySQL,andguidesyouthrough
theprocessofinstallingandconfiguringaPHP-MySQLdevelopmentenvironment
onbothUNIXandWindows.Chapter1,IntroducingPHPandMySQLdiscusses
TEAM LinG
Introduction
xv
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.
PartIVbringsPHPandMySQLtoge
PHP &
MySQL
™
Vikram Vaswani
McGraw-Hill/Osborne
NewYork Chicago SanFrancisco Lisbon
London Madrid MexicoCity Milan NewDelhi
SanJuan Seoul Singapore Sydney Toronto
TEAM LinG
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 McGrawHill’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.
DOI: 10.1036/0071466541
TEAM LinG
Dedication
Forthebaby:
ane’er-fixedmark
thatlooksontempestsandisne’ershaken
TEAM LinG
AbouttheAuthor
VikramVaswaniisthefounderandCEOof
Melonfire(http://www.melonfire.com/),acompany
specializinginsoftwareconsultancyandcontent
creation/syndicationservices.Heisapassionate
advocateoftheopen-sourcesoftwaremovementand
frequentlycontributesarticlesandtutorialsonopensourcetechnologies,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).
Whenhe’snotplottingtoruletheworldfromaheavilyguardedconference
roomatMelonfireHQ,Vikramamuseshimselfbyreadingcrimefiction,watching
oldmovies,playingsquash,fiddlingwithhisever-growingcollectionofelectronic
gadgets,andkeepinganeyeoutforunfriendlyagents.Readmoreabouthim,
downloadsamplecode,andconnectwithotheropen-sourceenthusiastsonline
athttp://www.everythingphpmysql.com/.
TEAM LinG
For more information about this title, click here
Contents
Acknowledgments ....................................
Introduction .........................................
PART I
CHAPTER 1
CHAPTER 2
LearningtheBasics
IntroducingPHPandMySQL ........................
3
Server-SideApplications ............................
…AndtheDatabasesThatLoveThem ..................
ThePHPStory ....................................
History ....................................
Features ...................................
TheMySQLStory .................................
History ....................................
Features ...................................
PHPandMySQL:TheWell-MatchedCouple .............
Architecture ................................
SampleApplications ..........................
Summary .......................................
4
5
7
8
9
11
11
12
16
17
19
20
SettingUpaPHP-MySQLDevelopmentEnvironment ......
ObtainingtheSoftware .............................
InstallingandConfiguringtheSoftware .................
InstallingonUNIX ...........................
InstallingonWindows .........................
TestingtheSoftware ...............................
TestingMySQL ..............................
TestingApache ..............................
TestingApacheandPHP .......................
PerformingPostinstallationSteps ......................
SettingtheMySQLSuper-UserPassword ...........
23
ConfiguringMySQLandApache
toStartAutomatically .......................
Summary .......................................
xi
xiii
24
26
26
35
50
50
51
51
53
53
54
55
v
TEAM LinG
vi
HowtoDoEverythingwithPHP&MySQL
PART II
LearningPHP
CHAPTER 3
UsingVariables,Statements,andOperators .............
59
EmbeddingPHPinHTML ..............................
WritingStatementsandComments .......................
StoringValuesinVariables ..............................
AssigningandUsingVariableValues ................
SavingFormInputinVariables .....................
UnderstandingSimpleDataTypes ........................
DetectingtheDataTypeofaVariable ................
UsingOperatorstoManipulateandCompareVariables .......
UsingArithmeticOperators ........................
UsingStringOperators ...........................
UsingComparisonOperators ......................
UsingLogicalOperators ..........................
UsingtheAuto-Increment
andAuto-DecrementOperators ..................
UnderstandingOperatorPrecedence .................
Summary ...........................................
60
63
63
65
65
66
67
70
70
72
72
74
UsingConditionalStatementsandLoops ...............
79
CHAPTER 4
AddingDecision-MakingCapabilities
withConditionalStatements ..........................
Usingtheif()Statement ........................
Usingtheswitch()Statement ...................
NestingConditionalStatements ....................
MergingFormsandTheirResultPages
withConditionalStatements ..........................
RepeatingActionswithLoops ...........................
Usingthewhile()Loop ........................
Usingthedo()Loop ............................
Usingthefor()Loop ...........................
ControllingLoopIterationwithbreakandcontinue .....
Summary ...........................................
CHAPTER 5
75
75
76
80
81
84
86
86
88
88
89
90
92
93
UsingArraysandCustomFunctions ...................
95
UsingArraystoGroupRelatedValues .....................
CreatinganArray ...............................
ModifyingArrayElements ........................
ProcessingArrayswithLoops ......................
GroupingFormSelectionswithArrays ...............
UsingArrayFunctions ............................
96
98
99
100
102
104
TEAM LinG
Contents
CreatingUser-DefinedFunctions .........................
DefiningandInvokingFunctions ...................
UsingArgumentsandReturnValues .................
DefiningGlobalandLocalVariables ................
ImportingFunctionDefinitions .....................
Summary ...........................................
CHAPTER 6
106
107
108
110
112
113
UsingFiles,Sessions,Cookies,andExternalPrograms .... 115
ReadingandWritingFiles ..............................
ReadingDatafromaFile .........................
WritingDatatoaFile ............................
TestingFileAttributes ............................
ObtainingDirectoryListings .......................
ManagingSessionsandUsingSessionVariables .............
CreatingaSessionandRegisteringSessionVariables ...
DestroyingaSession .............................
StoringDatainCookies ................................
SettingCookies .................................
RetrievingCookieData ...........................
DeletingCookies ................................
DealingwithDatesandTimes ......................
ExecutingExternalPrograms ............................
Summary ...........................................
CHAPTER 7
vii
116
116
119
120
122
123
124
125
126
127
128
128
129
130
131
SampleApplication:Session-BasedShoppingCart ........ 133
UnderstandingRequirements ............................
RetrievingCatalogData ................................
CreatingtheShoppingCart .............................
CalculatingCosts .....................................
HandlingCartUpdates .................................
PuttingItAllTogether .................................
Summary ...........................................
134
134
136
137
138
139
144
PART III
LearningMySQL
CHAPTER 8
UnderstandinganRDBMS .......................... 149
UnderstandingaRelationalDatabase .....................
UnderstandingTables,Records,andFields ............
UnderstandingPrimaryandForeignKeys ............
UnderstandingSQLandSQLQueries .....................
UnderstandingDatabaseNormalization ....................
UsingtheMySQLCommand-LineClient ..................
InteractingwithMySQLThroughaGraphicalClient .........
Summary ...........................................
150
151
151
154
156
156
159
160
TEAM LinG
viii
HowtoDoEverythingwithPHP&MySQL
CHAPTER 9
WorkingwithDatabasesandTables ................... 161
CreatingDatabases ....................................
CreatingTables .......................................
SpecifyingFieldDataTypes .......................
SelectingtheMostAppropriateDataType ............
AddingFieldModifiersandKeys ...................
SelectingaTableType ............................
AlteringTables .......................................
AlteringTableandFieldNames ....................
AlteringFieldProperties ..........................
AddingandRemovingFieldsandKeys ..............
AlteringTableTypes .............................
BackingUpandRestoringDatabasesandTables ............
BackingUpDatabasesandTables ...................
RestoringDatabasesandTablesfromBackup .........
DroppingDatabasesandTables ..........................
ViewingDatabase,Table,andFieldInformation .............
Summary ...........................................
CHAPTER 10
EditingRecordsandPerformingQueries ............... 181
InsertingRecords .....................................
EditingandDeletingRecords ...........................
PerformingQueries ...................................
RetrievingSpecificColumns .......................
FilteringRecordswithaWHEREClause .............
UsingOperators .................................
SortingRecordsandEliminatingDuplicates ..........
LimitingResults ................................
UsingBuilt-InFunctions ..........................
GroupingRecords ...............................
JoiningTables ..................................
UsingSubqueries ................................
UsingTableandColumnAliases ....................
Summary ...........................................
CHAPTER 11
163
163
164
168
168
170
173
173
173
174
175
175
175
176
177
178
180
182
184
186
187
187
188
191
192
193
194
196
201
203
204
UsingtheMySQLSecuritySystem ..................... 207
UnderstandingtheNeedforAccessControl ................
UnderstandingHowMySQLAccessControlWorks ..........
Assigning,Revoking,andViewingUserPrivileges ..........
WorkingwithUserAccountsandPassword ................
CreatingandRemovingUserAccounts ..............
AlteringUserPasswords ..........................
Summary ...........................................
208
209
210
213
214
215
217
TEAM LinG
Contents
CHAPTER 12
SampleApplication:OrderTrackingSystem ............. 219
UnderstandingRequirements ............................
CreatinganOptimizedDatabaseDesign ...................
DesigningtheCustomerTables .....................
DesigningtheProductTables ......................
DesigningtheOrderTable .........................
CreatingandPopulatingtheTables .......................
QueryingtheDatabase .................................
Summary ...........................................
PART IV
CHAPTER 13
QueryingaMySQLDatabasewithPHP ................. 239
240
244
247
248
248
252
254
254
257
ValidatingUserInput .............................. 259
SettingInputConstraintsattheDatabaseLayer .............
UsingtheNULLModifier .........................
UsingtheUNIQUEModifier ......................
UsingFieldDataTypes ...........................
ValidatingInputattheApplicationLayer ..................
CheckingforRequiredValues ......................
RestrictingtheSizeofInputData ...................
CheckingtheTypeofInputData ....................
CheckingforIllegalInputValues ...................
ValidatingDates .................................
ValidatingMultiple-ChoiceInput ...................
MatchingPatterns ...............................
Summary ...........................................
CHAPTER 15
220
221
221
222
224
225
228
236
UsingPHPwithMySQL
UsingMySQLandPHPTogether ........................
ManagingDatabaseConnections .........................
PerformingQueries ...................................
ProcessingResultSets .................................
QueriesWhichReturnData ........................
QueriesThatAlterData ...........................
HandlingErrors ......................................
UsingAncillaryFunctions ..............................
Summary ...........................................
CHAPTER 14
ix
260
260
262
263
264
264
266
268
274
277
279
281
286
FormattingQueryOutput ........................... 287
FormattingCharacterData ..............................
ConcatenatingStringValues .......................
PaddingStringValues ............................
AlteringStringCase .............................
DealingwithSpecialCharacters ....................
288
289
293
297
300
TEAM LinG
x
HowtoDoEverythingwithPHP&MySQL
FormattingNumericData ...............................
UsingDecimalandCommaSeparators ...............
FormattingCurrencyValues .......................
FormattingDatesandTimes ............................
PaginatingLargeResultSets ............................
Summary ...........................................
CHAPTER 16
306
306
312
316
325
328
SampleApplication:NewsPublishingSystem ............ 331
UnderstandingRequirements ............................
DesigningtheDatabase ................................
ListingandDisplayingNewsItems .......................
ListingNewsItems ..............................
DisplayingStoryContent .........................
ManipulatingNewsItems ..............................
ListingNewsItems ..............................
AddingNewsItems ..............................
DeletingNewsItems .............................
EditingNewsItems ..............................
ProtectingtheAdministrationModule .....................
Summary ...........................................
332
333
334
335
339
342
342
344
349
351
358
361
Index .......................................... 363
TEAM LinG
Acknowledgments
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
TEAM LinG
Copyright © 2005 by The McGraw-Hill Companies. Click here for terms of use.
xii
HowtoDoEverythingwithPHP&MySQL
LondonBusinessSchool,AnahitaMarker,MichaelSchumacher,MarkHaddon,
Mambo’sandTito’s,KalindiMehta,JohnKerry,HumphreyBogart,theLibrary
Bar,BombayTravels,Amazon.com,U2,TheThreeStooges,OscarWilde,Punch,
HarryPotter,ScottTurow,SlackwareLinux,CalvinandHobbes,Vincentvan
Gogh,FionaD’Silva,KelleyArmstrong,BlizzardEntertainment,DharaDusija,
StanfordUniversity,PopeyeandOlive,DennisLehane,Trattoria,XerxesAntia,
DireStraits,BruceSpringsteen,DavidMitchell,andallmyfriends,athomeand
elsewhere.
TEAM LinG
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.
xiii
TEAM LinG
Copyright © 2005 by The McGraw-Hill Companies. Click here for terms of use.
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:
PartIprovidesanintroductiontoPHPandMySQL,andguidesyouthrough
theprocessofinstallingandconfiguringaPHP-MySQLdevelopmentenvironment
onbothUNIXandWindows.Chapter1,IntroducingPHPandMySQLdiscusses
TEAM LinG
Introduction
xv
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.
PartIVbringsPHPandMySQLtoge