Tải bản đầy đủ (.pdf) (677 trang)

OReilly learning PHP and MySQL jun 2006 ISBN 0596101104

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.55 MB, 677 trang )

LearningPHPandMySQL
ByMicheleDavis,JonPhillips
...............................................
Publisher:O'Reilly
PubDate:June2006
PrintISBN-10:0-596-10110-4
PrintISBN-13:978-0-59-610110-7
Pages:376

TableofContents|Index

ThePHPscriptinglanguageandMySQLopen-sourcedatabasearequite
effectiveindependently,buttogethertheymakeasimplyunbeatable
team.Whenworkinghand-in-hand,theyserveasthestandardforthe
rapiddevelopmentofdynamic,database-drivenwebsites.This
combinationissopopular,infact,thatit'sattractingmany
programmingnewbieswhocomefromaweborgraphicdesignbackground
andwhosefirstlanguageisHTML.Ifyoufallintothisever-expanding
category,thenthisbookisforyou.

LearningPHPandMySQLstartswiththeverybasics
ofthePHPlanguage,includingstringsandarrays,patternmatchingandadetailed
discussionofthevariancesindifferentPHPversions.Next,it
explainshowtoworkwithMySQL,coveringinformationonSQLdata
accessforlanguageanddatafundamentalsliketablesandstatements.
Finally,afterit'ssurethatyou'vemasteredtheseseparateconcepts,
thebookshowsyouhowtoputthemtogetherto
generatedynamiccontent.Intheprocess,you'llalsolearnabouterror
handling,security,HTTPauthenticationandmore.

Ifyou'reahobbyistwhoisintimidatedbythick,complex


computerbooks,thenthisguidedefinitelybelongsonyourshelf.
LearningPHPandMySQLexplainseverything--from
basicconceptstothenutsandboltsofperformingspecifictasks--inplain
English.


PartofO'Reilly'sbestselling"Learning"series,thebookisan
easy-to-useresourcedesignedspecificallyfornewcomers.It'salsoalaunchingpad
forfuturelearning,providingyouwithasolidfoundationformoreadvanceddevelopment.


LearningPHPandMySQL
ByMicheleDavis,JonPhillips
...............................................
Publisher:O'Reilly
PubDate:June2006
PrintISBN-10:0-596-10110-4
PrintISBN-13:978-0-59-610110-7
Pages:376

TableofContents|Index














































Copyright
Preface
Chapter1.DynamicContentandtheWeb
Section1.1.PHPandMySQL'sPlaceinWebDevelopment
Section1.2.TheComponentsofaPHPApplication
Section1.3.IntegratingManySourcesofInformation
Section1.4.RequestingDatafromaWebPage
Section1.5.Chapter1Questions
Chapter2.Installation
Section2.1.DevelopingLocally
Section2.2.WorkingRemotely
Section2.3.Chapter2Questions
Chapter3.ExploringPHP
Section3.1.PHPandHTMLText
Section3.2.CodingBuildingBlocks
Section3.3.Chapter3Questions
Chapter4.PHPDecisionMaking
Section4.1.Expressions
Section4.2.OperatorConcepts
Section4.3.Conditionals
Section4.4.Looping
Section4.5.Chapter4Questions
Chapter5.Functions
Section5.1.CallingFunctions














































































Section5.2.DefiningFunctions
Section5.3.Object-OrientedProgramming
Section5.4.Chapter5Questions
Chapter6.Arrays
Section6.1.ArrayFundamentals
Section6.2.Chapter6Questions
Chapter7.DatabaseBasics
Section7.1.DatabaseDesign
Section7.2.StructuredQueryLanguage
Section7.3.Chapter7Questions
Chapter8.UsingMySQL
Section8.1.MySQLDatabase
Section8.2.ManagingtheDatabase
Section8.3.BackingUpandRestoringData
Section8.4.AdvancedSQL
Section8.5.Chapter8Questions

Chapter9.GettingPHPtoTalktoMySQL
Section9.1.TheProcess
Section9.2.QueryingtheDatabasewithPHPFunctions
Section9.3.UsingPEAR
Section9.4.Chapter9Questions
Chapter10.WorkingwithForms
Section10.1.BuildingaForm
Section10.2.Templates
Section10.3.Chapter10Questions
Chapter11.PracticalPHP
Section11.1.StringFunctions
Section11.2.DateandTimeFunctions
Section11.3.FileManipulation
Section11.4.CallingSystemCalls
Section11.5.Chapter11Questions
Chapter12.ModifyingMySQLObjectsandPHPData
Section12.1.ChangingDatabaseObjectsfromPHP
Section12.2.ManipulatingTableData
Section12.3.DisplayingResultswithEmbeddedLinks
Section12.4.PresentingaFormtoAddandProcessinOneFile
Section12.5.UpdatingData
Section12.6.DeletingData
Section12.7.PerformingaSubquery















































































Section12.8.Chapter12Questions
Chapter13.Cookies,Sessions,andAccessControl
Section13.1.Cookies
Section13.2.PHPandHTTPAuthentication
Section13.3.Sessions
Section13.4.UsingAuth_HTTPtoAuthenticate
Section13.5.Chapter13Questions
Chapter14.Security
Section14.1.
Section14.2.SessionSecurity
Section14.3.Chapter14Questions
Chapter15.ValidationandErrorHandling
Section15.1.ValidatingUserInputwithJavaScript
Section15.2.PatternMatching
Section15.3.RedisplayingaFormAfterPHPValidationFails
Section15.4.Chapter15Questions
Chapter16.SampleApplications
Section16.1.BuildingaBlog
Section16.2.Chapter16Questions
Chapter17.FinishingYourJourney
Section17.1.FindingHelpontheWeb

Section17.2.WebSites
Section17.3.Zend
Section17.4.Lampshade
Section17.5.Chapter17Questions
AnswerstoChapterQuestions
SectionA.1.Chapter1
SectionA.2.Chapter2
SectionA.3.Chapter3
SectionA.4.Chapter4
SectionA.5.Chapter5
SectionA.6.Chapter6
SectionA.7.Chapter7
SectionA.8.Chapter8
SectionA.9.Chapter9
SectionA.10.Chapter10
SectionA.11.Chapter11
SectionA.12.Chapter12
SectionA.13.Chapter13
















SectionA.14.Chapter14
SectionA.15.Chapter15
SectionA.16.Chapter16
SectionA.17.Chapter17
Colophon
AbouttheAuthors
Index


LearningPHPandMySQL
byMicheleE.DavisandJonA.Phillips
Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contactour
corporate/institutionalsalesdepartment:(800)998-9938or

Editor:

SimonSt.Laurent

ProductionEditor:

MaryBrady


Copyeditor:

LinleyDolby

Proofreader:

MaryBrady

Indexer:

JohnnaVanHooseDinse

CoverDesigner:

KarenMontgomery

InteriorDesigner:

DavidFutato

Illustrators:

RobertRomanoandJessamynRead

PrintingHistory:


June2006:


FirstEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
LearningPHPandMySQL,theimageofKookaburrabirds,and
relatedtradedressaretrademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-10110-4
[M]


Preface
PHPandMySQLareapowerfulcombinationthattogethermake
iteasytocreatewebapplications.Ifyou'vebeencreatingweb
pagesbutwanttobuildmoresophisticatedsitesthatcangrow
andinteractwithusers,PHPandMySQLletyoubuildyour
foundationsquickly,andsubsequentlybuildonthemtomeet
yourneeds.
OurgoalistohelpyoulearntheinsandoutsofPHPandMySQL
andsaveyousomeofthe"Whydoesn'tthatwork?"moments
thatwe'vealreadybeenthrough.We'llshowyouwhattowatch
forandhowtofixtheseissueswithoutpullingoutyourhair.


Audience
Thisbookisforpeoplewhowanttoknowhowtocreate
dynamicwebsites.Thatcouldincludegraphicdesignerswho
arealreadyworkinginanITfirmoradvertisingfirmcreating
staticwebsites,whomayneedtomoveforwardwithcoding
database-drivenwebsites.Itmightalsoincludepeoplewho
alreadyknow,say,FlashdevelopmentandHTMLmarkup,but
needtoexpandtheirrepertoireofskillstodatabaseandopen
sourceprogrammingenvironments.

AssumptionsThisBookMakes
Thisbookassumesyouunderstandhowwebbrowsersworkand
haveabasicunderstandingofHTML.Someunderstandingof
JavaScriptmaybeuseful(forChapter15)butisn'tgenerally
required.
Youmightalsobeover-qualified.Ifyoualreadyknowhowto
createpagesusingMySQLandPHP,thenyou'dprobablybe


betteroffwithabookthatismoreareferencethanaLearning
book,suchasonefromtheNutshellseries.

OrganizationofThisBook
Thisbookstartsoutwithanoverviewofhowallofthepieces
you'llbeworkingwithfittogether.Becausetherearemultiple
languagesandtechnologiesthatinteracttoformthedynamic
webpages,it'sbesttostartwithasolidfoundationofhowthe
piecesworktogether.ThePHPthatyou'lllearnworksasasort
ofatotalintegrationpackagefordynamicwebsites.

Next,we'llwalkthroughinstallingthecoresoftwarepackages
onyourlocalcomputer.ThisbookfocusesonPHPandMySQL,
butmakingthisworkalsousuallyrequirestheApacheweb
server.ThePHPinterpreterworkswiththewebserverwhen
processingdynamiccontent.Finally,you'llinstalltheMySQL
database.InstallationiscoveredonthePC,Mac,andLinux
systems.YoucanalsouseahostedISPaccounttodevelopyour
pages,ifyoudon'twanttoinstalleverythinglocally.
SincePHPplaysanimportantroleinpullingeverything
together,wetakethetimetoexplainthebasicsofworkingwith
thePHPlanguage.Thisincludeslanguageessentialssuchas
datatypes,programflowlogic,andvariables.Functions,arrays,
andformseachgettheirownchaptertofullyexplorethem.
Sinceyoumaybenewtodatabasesingeneral,weeaseinto
MySQLbyfirstexplainingconceptsthatapplytodesigningand
usinganyrelationaldatabase.Thenwegivespecificexamples
ofusingMySQLtointeractwithyourdata.Onceyoucanget
datainandoutofthedatabase,you'llneedtoworkwithPHPto
integratethatdataintoyourdynamiccontent.
Securityandaccesscontroltoyourwebpageseachgettheir
ownchapter.Whilesecuritymaysoundlikeadullsubject,it's
stillahugeissueifyoustoreanyinformationthat'sprivateon


yourwebpage.Thereareseveralcommonsecuritypitfallsthat
we'llguideyouaround.
Finally,weclosewithsampleapplicationsthatdemonstratehow
thetechnologiesworktogethertorapidlybuildworkable,fast
websites.You'llalsolearnwheretolookforadditional
informationonthetopicscoveredinthebook.


SupportingBooks
Evenifyoufeelyouarereadyforthisbook,youmaywantto
exploresomeoftheXMLtechnologiesingreaterdepththanis
possiblehere.Thefollowinglistofferssomegoodplacesto
start:
RunYourOwnWebServerUsingLinux&Apache,byTony
Steidler-Dennison(SitePoint,2005).
PHPinaNutshell,FirstEdition,byPaulHudson(O'Reilly,
2005).
MySQLinaNutshell,FirstEdition,byRussellDyer(O'Reilly,
2005).
CSSCookbook,FirstEdition,byChristopherSchmitt
(O'Reilly,2004).
Therearealsoseveralgoodonlineresourcesfordynamicweb
development,includingonlamp.com,partoftheO'Reilly
Network.LAMPstandsforLinux,Apache,MySQL,PHP.LAMPis
thedefactostandardforservingdynamicwebpages.

ConventionsUsedinThisBook


Thefollowingfontconventionsareusedinthisbook:

Italic
Indicatespathnames,filenames,andprogramnames;
Internetaddresses,suchasdomainnamesandURLs;and
newitemswheretheyaredefined

Constantwidth

Indicatescommandlinesandoptionsthatshouldbetyped
verbatim;namesandkeywordsinprograms,including
methodnames,variablenames,andclassnames;and
HTMLelementtags

Constantwidthbold
Indicatesemphasisinprogramcodelines

Constantwidthitalic

Indicatestextthatshouldbereplacedwithuser-supplied
values

Thisiconsignifiesatip,suggestion,orgeneralnote.


Thisiconindicatesawarningorcaution.

UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire

permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"LearningPHPandMySQLbyMicheleE.Davisand
JonA.Phillips.Copyright2006O'ReillyMedia,Inc.,0-59610110-4."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat


Safari®Enabled

WhenyouseeaSafari®Enabledicononthecover


ofyourfavoritetechnologybook,thatmeansthebookis
availableonlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.

HowtoContactUs
Wehavetestedandverifiedtheinformationinthisbooktothe
bestofourability,butyoumayfindthatfeatureshavechanged
(oreventhatwehavemadeafewmistakes!)Pleaseletus
knowaboutanyerrorsyoufind,aswellasyoursuggestionsfor
futureeditions,bywritingto:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth

Sebastopol,CA95472
800-998-9938(intheU.S.orCanada)
707-829-0515(international/local)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:



Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:


Acknowledgments
First,we'dliketothankourwonderfulagent,MattWagnerof
FreshBooks,forbringingsuchafabulousopportunitytothe
tableforus.TheopportunitytowriteforO'ReillyMediawasa
greathonor.Astechnologists,ourbookcaseisalreadywell
populatedwithanimalsfromtheNutshellseries.
ThankstoourO'Reillydevelopmentaleditors,BrettMcLaughlin
andSimonSt.Laurent.Thisbookwouldn'tbewhatitiswithout
bothoftheirhelpworkingwithus.Second,profusethanksto
ourtechnicaleditors,especiallyJeremeAllenandChristopher
Finke,whomwemetthroughourlocalMinneapolis/St.PaulPHP
community:.Technicaleditthanksalso
gotoourlasttechnicaleditor,PatrickKrekelberg.



Chapter1.DynamicContentandtheWeb
Therearetwotypesofwebpages:staticanddynamic.Astatic
siteprovideshyperlinkedtextandperhapsaloginscreen,but
beyondthat,itdoesn'trequireadditionalparticipationfromthe
user.isanexampleofastaticsite,
exceptthatyoudohavetoregistertoviewarticles.
isanexampleofadynamicwebsite,
becauseyourorderingdataislogged,andAmazonoffers
recommendationsbasedonyourpurchasinghistorywhenyou
accesstheirpage.Inotherwords,dynamicmeansthattheuser
interactsmorewiththewebsite,beyondjustreadingpages,
andthewebsiterespondsaccordingly.
Creatingdynamicwebpagesevenafewyearsagomeantwriting
alotofcodeintheCorPerllanguages,andthencallingand
executingthoseprogramsthroughaprocesscalledaCommon
GatewayInterface(CGI).Havingtocreateexecutablefiles
doesn'tsoundlikemuchfun,andneitherdoeslearningawhole
newcomplicatedlanguage.Well,thankfully,PHPandMySQL
makecreatingdynamicwebsitessimpler,easier,andfaster.




1.1.PHPandMySQL'sPlaceinWeb
Development
PHPisaprogramminglanguagedesignedtogenerateweb
pagesinteractivelyonthecomputerservingthem,calledaweb
server.UnlikeHTML,wherethewebbrowserusestagsand
markuptogenerateapage,PHPcoderunsbetweenthe

requestedpageandthewebserver,addingtoandchangingthe
basicHTMLoutput.Forexample,PHPcodecouldbeusedto
displayacounterofvisitorstoasite.
PHP,inlessthan20linesofcode,canstoretheIPaddressfrom
whichapagerequestcomesinaseparatefile,andthendisplay
thenumberofuniqueIPaddressesthatvisitedaparticularsite.
Thepersonrequestingthewebpagedoesn'tknowthatPHP
generatedthepage,becausethecountertextispartofthe
standardHTMLmarkuplanguagethatthePHPcodegenerated.
PHPmakeswebdevelopmenteasy,becauseallthecodeyou
neediscontainedwithinthePHPframework.Thismeansthat
there'snoreasonforyoutoreinventthewheeleachtimeyou
sitdowntodevelopaPHPprogram;thatwouldbesomething
you'dhavetodoifyouwereusingacompiledlanguagelikeC.
WhilePHPisgreatfordevelopingwebfunctionality,itisnota
database.ThedatabaseofchoiceforPHPdevelopersisMySQL,
whichactslikeafilingclerkforPHP-processeduserinformation.
MySQLautomatesthemostcommontasksrelatedtostoring
andretrievingspecificuserinformationbasedonyoursupplied
criteria.

TakeourAmazonexample;therecommendationsAmazonoffersyou
canbestoredinaMySQLdatabase,alongwithyourpriororder
information.


MySQLiseasilyaccessedfromPHP,andthey'recommonlyused
togetherastheyworkwellhandinhand.Anaddedbenefitis
thatPHPandMySQLrunonvariouscomputertypesand
operatingsystems,includingMacOSX,Windows-basedPCs,

andLinux.

1.1.1.AdvantagesofUsingPHPwithMySQL
ThereareseveralfactorsthatmakeusingPHPandMySQL
togetheranaturalchoice:

PHPandMySQLworkwelltogether
PHPandMySQLhavebeendevelopedwitheachotherin
mind,sotheyareeasytousetogether.Theprogramming
interfacesbetweenthemarelogicallypairedup.Working
togetherwasn'tanafterthoughtwhenthedevelopers
createdthePHPandMySQLinterfaces.

PHPandMySQLhaveopensourcepower
Astheyarebothopensourceprojects,PHPandMySQLcan
bothbeusedforfree.MySQLclientlibrariesarenolonger
bundledwithPHP.Advancedusershavetheabilitytomake
changestothesourcecode,andtherefore,changetheway
thelanguageandprogramswork.

PHPandMySQLhavecommunitysupport


ThereareactivecommunitiesontheWebinwhichyoucan
participateandthey'llansweryourquestions.Youcanalso
purchaseprofessionalsupportforMySQLifyouneedit.

PHPandMySQLarefast
Theirsimplicityandefficientdesignenablesfaster
processing.


PHPandMySQLdon'tbogyoudownwithunnecessarydetails.
Youdon'tneedtoknowallofthelow-leveldetailsofhow
thePHPlanguageinterfaceswiththeMySQLdatabase,as
thereisastandardinterfaceforcallingMySQLprocedures
fromPHP.OnlineAPIsatofferan
unlimitedresource.

1.1.2.TheValueofOpenSource
Aswementionedabove,bothPHPandMySQLareopensource
projects,sothere'snoneedtoworryaboutuserlicensesfor
everycomputerinyourofficeorhome.Inopensourceprojects
andtechnologies,programmershaveaccesstothesourcecode;
thisenablesindividualorgroupanalysistoidentifypotentially
problematiccode,test,debug,andofferchangesaswellas
additionstothatcode.Forexample,Unixtheforerunnerinthe
opensourcesoftwarecommunitywasfreelysharedwith
universitysoftwareresearchers.Linux,thefreealternativeto
Unix,isadirectresultoftheireffortsandtheopensource
licensingparadigm.
AsTimO'Reillyputsit,"Opensourcelicensingbeganasan
attempttopreserveacultureofsharing,andonlylaterledto


anexpandedawarenessofthevalueofthatsharing."Today,
opensourceprogrammerssharetheircodechangesontheWeb
viaphp.net,listservs,andwebsites.Ifyou'recaughtina
codingnightmareandcan'twakeup,theresourcesmentioned
abovecanandwillhelpyou.


We'llarmyouwithopensourceuserforumslaterinthisbooksoyou
cancheckthemoutyourself.We'llincludelistservsandwebsitesso
thatyouhavenumerousresourcesifyourunintoasnafu.


1.2.TheComponentsofaPHPApplication
Inordertoprocessanddevelopdynamicwebpages,you'llneed
touseandunderstandseveraltechnologies.Therearethree
maincomponentstocreatingdynamicwebpages:awebserver,
aserver-sideprogramminglanguage,andadatabase.It'sa
goodideatohaveanunderstandingofthethreebasic
componentsforwebdevelopmentusingPHP.Startwithsome
rudimentaryunderstandingofthehistoryandpurposeof
Apache(yourwebserver),PHP(yourserver-sideprogramming
language),andMySQL(yourdatabase).Thiscanhelpyou
understandhowtheyfitintothewebdevelopmentpicture.
Rememberthatdynamicwebpagespullinformationfrom
severalsourcessimultaneously,includingApache,PHP,MySQL,
andCascadingStyleSheets(CSS),whichwe'lltalkaboutlater.

1.2.1.BirthofPHP
PHPgrewoutofaneedforpeopletodevelopandmaintainweb
sitescontainingdynamicclient-serverfunctionality.In1994,
RasmusLerdorfcreatedacollectionofopensourcePerlscripts
forhispersonaluse,andtheseeventuallywererewritteninC
andturnedintowhatPHPistoday.By1998,PHPwasreleased
initsthirdversion,turningitintoawebdevelopmenttoolthat
couldcompetewithsimilarproductssuchasMicrosoft'sActive
ServerPages(ASP)orSun'sJavaServerPages(JSP).
TherealbeautyofPHPisitssimplicitycoupledwithitspower,

aswellasitbeinganinterpretedlanguage,ratherthana
compiledone.

Compiledlanguagescreateabinary.exefile,whileinterpreted
languagesworkdirectlywiththesourcecodewhenexecutingas


opposedtocreatingastandalonefile.

PHPisubiquitousandcompatiblewithallmajoroperating
systems.Itisalsoeasytolearn,makingitanidealtoolfor
web-programmingbeginners.Additionally,yougettotake
advantageofacommunity'sefforttomakewebdevelopment
easierforeveryone.ThecreatorsofPHPdevelopedan
infrastructurethatallowsexperiencedCprogrammerstoextend
PHP'sabilities.Asaresult,PHPnowintegrateswithadvanced
technologieslikeXML,XSL,andMicrosoft'sCOM.Atthis
juncture,PHP5.0isbeingused.

1.2.2.BirthofApache
Apacheisawebserverthatturnsbrowserrequestsinto
resultingwebpagesandknowshowtoprocessPHPcode.PHP
isonlyaprogramminglanguage,sowithoutthepowerofaweb
serverlikeApachebehindit,therewouldbenowayforweb
userstoreachyourpagesthatcontainthePHPlanguagecode.
Apacheisnottheonlywebserveravailable.Anotherpopular
webserverisMicrosoft'sInternetInformationServices(IIS),
whichissuppliedwithWindows2000andalllaterversions.For
themostpart,thedifferencesbetweenApacheandIIScome
downtopersonalpreference,althoughApachehasthedecided

advantagesofbeingfree,providingfullsourcecode,andusing
anunrestrictedlicense.Apache2.0isthecurrentversionyou'll
beusing.IISiseasiertointegratewithActiveDirectory,
Microsoft'slatestauthenticationsystem,butthisappliesmostly
tointernalcompanywebsites.


AccordingtotheNetcraftwebserversurvey,Apachehasbeenthemost
popularwebserverontheInternetsinceApril1996.

BecausewebserverslikeApacheandIISaremadetoserveup
pagesfromHTMLfiles,theyneedawaytoknowhowtoprocess
PHPlanguagecode.Apacheusesasystemcalledmodulesto
loadextensionsintoitsfunctionality.IISusesasimilarconcept
calledISAPI.ThesebothallowforfasterprocessingofthePHP
codethantheoldschoolprocessofcallingPHPasaseparate
executableeachtimethewebserverhadarequestforapage
containingPHP.We'lldiscusshowtheApachemoduleissetup
inChapter2.

1.2.3.ApacheVersions
Apachehasonlytwomajorversionsinusetoday.Theyare1.3
and2.Apache2isamajorrewriteandsupportsthreading.
Threadsareawayforasingleprocesstomanagemorethan
onethingatatime.Thebenefitisanincreaseinspeedanda
reductionintheresourcesneeded.Unfortunately,PHPisn't
totallycompatiblewiththreadingyet.Apache2hasbeenout
longenoughtobeconsideredstablefordevelopmentand
productionuse.Apache2alsosupportsmorepowerfulmodules.
Someadditionalmodulescanbefoundat

However,
sharedmoduleDLLsthatdon'tcomewiththeofficialApache
sourcefiles,suchasmod_php4,mod_ssl,mod_auth_mysql,
andmod_auth_ntsec,canbefoundontheWeb.

1.2.4.BirthofMySQL


MySQLwasdevelopedinthe1990stofilltheever-growing
needforcomputerstomanageinformationintelligently.The
originalcoreMySQLdevelopersweretryingtosolvetheirneeds
foradatabasebyusingmSQL,asmallandsimpledatabase.It
becomeclearthatmSQLcouldn'tsolvealltheproblemsthey
wanteditto,sotheycreatedamorerobustdatabasethat
turnedintoMySQL
MySQLsupportsseveraldifferentdatabaseengines.The
databaseenginedetermineshowMySQLhandlestheactual
storageandqueryingofthedata.Becauseofthat,eachstorage
enginehasitsownsetofabilitiesandstrengths.Overtime,the
databaseenginesavailablearebecomingmoreadvancedand
faster.Table1-1listswhenvariousfeatureshavebeenaddedto
MySQL.
Table1-1.MajorMySQLreleases
Version Features
TheMyISAMdatabaseengineisaddedandisthedefaultengine.Ithandleslarge
amountsofdataefficiently.
3.23

TheInnoDBdatabaseenginedebutsfortransactionsafedatabaseprocessingand
supportforforeignkeys.Foreignkeysallowtherelationshipsbetweentablestobe

explicitlydesignatedinthedatabase.

4.0

Queriessupportunions.Unionsallowmergingtheresultsoftwoqueriesintoone
result.Configurationchangescanbemadewithoutrestartingthedatabase.

4.01

Ahelpcommandisincludedforthedatabaseclient.Thereissupportforunnamed
views,alsoknownassubqueries.Unnamedviewsallowyoutotreataquerylikea
separatetablewithinaquery.

5.0

Databasetriggers,storedprocedures,andcursorsareadded.Atriggerallows
codetoruninthedatabasewhenatriggeringeventoccurs,suchasinsertingdata
intoatable.Storedproceduresallowprogramstobedefinedandexecutedwithin
thedatabase.Cursorsallowcodeinthedatabasetoberunforeachrowthat
matchesaquery.

5.1

Constraintsandpartitioningareadded.Constraintsareusedtodefinerulesfor
whenrowscanbeaddedormodifiedinthedatabase.Partitioningisusedtosplit
upthephysicalstorageoflargetablesbasedonadefinedrule.Itiscommonly


usedtoincreasetheperformanceoflargetablessuchashistoricaldata.


ThecurrentproductionreleaseofMySQListhelatestavailable
5.0xversion.MySQL5.0providesperformancethatis
comparabletoanyofthemuchmoreexpensiveenterprise
databasessuchasOracle,Informix,DB2(IBM),andSQLServer
(Microsoft).Thedevelopershaveachievedthislevelof
performancebyleveragingthetalentsofmanyopensource
developers,alongwithcommunitytesting.Forgeneralwebdrivendatabasetasks,thedefaultMyISAMdatabaseengineworks
perfectlyfine.

ThenewestadvancedfeaturesofMySQL5.1arenotasstableas
featuresintroducedinpriorreleases.MySQL5.0isthecurrentstable
generalrelease.Downloadthelatestminorrelease(thelargestofthe
thirdportionoftheversionnumber)forwhichevermajorversionyou
choose.Ithasthemostbugfixesforthatversionincluded.

Apachealsohastheadvantageofbeingabletorunon
operatingsystemsotherthanWindows,whichnowbringsusto
thesubjectofcompatibility.

1.2.5.Compatibility
WebbrowserslikeFirefox,Netscape,andInternetExplorerare
madetoprocessHTML,soitdoesn'tmatterwhatoperating
systemawebserverrunson.Apache,PHP,andMySQLsupport
awiderangeofoperatingsystems,soyouaren'trestrictedtoa
specificOSoneithertheserverortheclient.Whileyoudon't
havetoworrymuchaboutsoftwarecompatibility,thesheer


×