Tải bản đầy đủ

Premier press PHP MySQL programming for the absolute beginner

PHP/MySQLProgramming
fortheAbsoluteBeginner
ISBN:1931841322
byAndy
Harris
PremierPress©2003(414pages)
Withthisguide,youwill
acquireskillsnecessaryfor
practicalprogramming
applicationsandwilllearn
howtheseskillscanbeput
touseinrealworldscenarios
andapplythemtothenext
programminglanguageyou
tackle.
CDContent
TableofContents
PHP/MySQLProgrammingforthe
AbsoluteBeginner
Introduction
ExploringthePHP

Chapter1 Environment
Chapter2 - UsingVariablesandInput
ControllingYourCode
Chapter3 - withConditionsand
Functions
LoopsandArrays:The
Chapter4 PokerDiceGame
BetterArraysandString
Chapter5 Handling


Chapter6 - WorkingwithFiles
UsingMySQLtoCreate
Chapter7 Databases
ConnectingtoDatabases
Chapter8 WithinPHP
Chapter9 - DataNormalization
BuildingaThree-Tiered
Chapter10 DataApplication
Index
ListofFigures
ListofTables
ListofInTheRealWorld
ListofSidebars
CDContent


BackCover
IfyouarenewtoprogrammingwithPHPandMySQL
andarelookingforasolidintroduction,thisisthebook
foryou.Developedbycomputerscienceinstructors,
booksintheFortheAbsoluteBeginnerseriesteachthe
principlesofprogrammingthroughsimplegame
creation.Youwillacquiretheskillsthatyouneedfor
morepracticalprogrammingapplicationsandwilllearn
howtheseskillscanbeputtouseinreal-world
scenarios.Bestofall,bythetimeyoufinishthisbook
youwillbeabletoapplythebasicprinciplesyou’ve
learnedtothenextprogramminglanguageyoutackle.
Withtheinstructionsinthisbook,you’lllearnto:
UseMySQLtocreatedatabases
Mastervariablesandinput
ConnecttodatabaseswithinPHP
Controlyourcodewithconditionsandfunctions
Buildathree-tiereddataapplication
AbouttheAuthor
AndyHarrisbeganhisteachcareerasahighschool
specialeducationteacher.Hebeganteachingatthe
universitylevelinthelate1980sasapart-timejob.
Since1995,hehasbeenafull-timelectureratthe
ComputerScienceDepartmentofIndiana
University/PurdueUniversity—Indianapolis.He
managestheIUPUIStreamingMediaLabandteaches


classesinseveralprogramminglanguages.


PHP/MySQLProgrammingfortheAbsolute
Beginner
ANDYHARRIS

Copyright©2003byPremierPress,adivisionofCourseTechnology.
Allrightsreserved.Nopartofthisbookmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
systemwithoutwrittenpermissionfromPremierPress,exceptforthe
inclusionofbriefquotationsinareview.
ThePremierPresslogoandrelatedtradedressaretrademarksof
PremierPressandmaynotbeusedwithoutwrittenpermission.
Microsoft,Windows,InternetExplorer,Notepad,VBScript,ActiveX,and
FrontPageareeitherregisteredtrademarksortrademarksofMicrosoft
CorporationintheUnitedStatesand/orothercountries.Netscapeisa
registeredtrademarkofNetscapeCommunicationsCorporationinthe
U.S.andothercountries.
Allothertrademarksarethepropertyoftheirrespectiveowners.
Important: PremierPresscannotprovidesoftwaresupport.Please
contacttheappropriatesoftwaremanufacturer'stechnical
supportlineorWebsiteforassistance.
PremierPressandtheauthorhaveattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
InformationcontainedinthisbookhasbeenobtainedbyPremierPress
fromsourcesbelievedtobereliable.However,becauseofthepossibility


ofhumanormechanicalerrorbyoursources,PremierPress,orothers,
thePublisherdoesnotguaranteetheaccuracy,adequacy,or
completenessofanyinformationandisnotresponsibleforanyerrorsor
omissionsortheresultsobtainedfromuseofsuchinformation.Readers
shouldbeparticularlyawareofthefactthattheInternetisaneverchangingentity.Somefactsmayhavechangedsincethisbookwentto
press.
ISBN:1-931841-32-2
LibraryofCongressCatalogCardNumber:2003104019
PrintedintheUnitedStatesofAmerica
0304050607BH10987654321
PremierPress,adivisionofCourseTechnology
25ThomsonPlace
Boston,MA02210
Publisher:
StacyL.Hiquet
SeniorMarketingManager:
MartineEdwards
MarketingManager:
HeatherHurley
ManagerofEditorialServices:
HeatherTalbot
AssociateMarketingManager:
KristinEisenzopf
AcquisitionsEditor:


ToddJensen
ProjectEditor:
SandyDoell
TechnicalReviewer:
JasonWynia
RetailMarketCoordinator:
SarahDubois
InteriorLayout:
DanielleFoster
CoverDesigner:
MikeTanamachi
CD-ROMProducer:
KeithDavenport
Indexer:
KellyTalbot
Proofreader:
MargaretBauer
ToHeather,Elizabeth,Matthew,andJacob
Acknowledgments
FirstIthankHimfromwhomallflows.
Heather,youalwaysworkharderonthesebooksthanIdo.Thankyoufor
yourloveandyoursupport.ThankyouElizabeth,Matthew,andJacobfor


understandingwhyDaddywastypingallthetime.
ThankstotheOpenSourcecommunityforcreatinggreatfreesoftware
likePHPandMySQL.
Thankyou,StacyHiquet,foryourcontinuedsupportandencouragement
onthisandotherprojects.
Thanks,ToddJensen,forholdingthisthingtogether.
SpecialthankstoSandyDoellforturningmydrivelintosomething
readable.
ThankstoJWynia(www.phpgeek.com)fortechnicalediting.Thanksalso
toJasonforuseofPHPTriadontheCD-ROM.
Thankyoutothewebyogdevelopmentteam
(http://www.webyog.com/sqlyog/)foruseoftheSQLyogtool.
AbigthankstoKeithDavenportforputtingtogethertheCD-ROM.It'sa
bigjob,andyoudiditwell.
ThankyoutothemanymembersofthePremier/Courseteamwho
workedonthisbook.
AhugethankstomyCSCIN399ServerSideWebDevelopmentclassin
Spring2003.Thankyouforbeingpatientwithmymanuscript,forhelping
mespotmanyerrors,andforprovidinginvaluableadvice.Ilearnedas
muchfromyouasyoudidfromme.
AbouttheAuthor
AndyHarrisbeganhisteachingcareerasahighschoolspecial
educationteacher.Duringthattime,hetaughthimselfenoughcomputing
todopart-timecomputerconsultinganddatabasework.Hebegan
teachingcomputingattheuniversitylevelinthelate1980sasapart-time
job.Since1995hehasbeenafull-timelecturerintheComputerScience
DepartmentofIndianaUniversity/PurdueUniversity—Indianapolis,where
hemanagestheStreamingMediaLabandteachesclassesinseveral
programminglanguages.HisprimaryinterestsareJava,Microsoft


languages,Perl,JavaScript,PHP,WebData,virtualreality,portable
devices,andstreamingmedia.


Introduction
Ifyou'vebeenwatchingtheWebforawhileyou'veprobablynoticeditis
changing.WhentheWebfirstenteredintothepublicconsciousness,it
wasawaytodistributedocuments.Thesedocumentswereprettyeasyto
make.AnybodywithaweekendandatexteditorcouldgetaWebpage
upandrunning.BuildingaWebsiteintheearlydayswasaboutmaking
documents.
TodaytheInternetismuchmorethanthat.InterestingWebsitesarenot
simplydocuments;theyareapplications.Theyhavemuchmore
complexityandpower.YoumightthinktheWebisnolongeraplacefor
individualsorbeginningprogrammers.Manyofthesoftwaredevelopment
toolsavailableareexpensiveandcomplicated.
Tome,themostexcitingthingabouttheInternetisitssocialimplications.
Thereisalargecommunitythatbelievesinpowerful,easy-to-use,free
software.Thatcommunityhasproducedanumberofexceptional
programs,includingPHPandMySQL.
PHPisapowerfulprogramminglanguagethatletsyoubuilddynamic
Websites.Itworkswellonavarietyofplatforms,andit'sreasonably
easytounderstand.MySQLisanimpressiverelationaldatamanagement
systemusedtobuildcommercialqualitydatabases.PHPandMySQLare
suchpowerfulandeasy-to-useplatformsthattheymakeWeb
programmingaccessibleevenforbeginners.
Inthisbook,Iwillteachyouaboutprogramming.Specifically,youwill
learnhowtowriteprogramsonWebservers.You'lllearnallthemain
conceptsofprogramminglanguages.You'llalsolearnabouthowdata
worksinthemodernenvironment.You'lllearncommandsandsyntax,but
you'llalsolearntheprocessofprogramming.
Ifyou'veneverwrittenacomputerprogrambefore,thisbookwillbea
goodintroduction.Ifyou'reanexperiencedprogrammerwantingtolearn
PHPandMySQL,you'llfindthisbooktobeagentleintroduction.
Programmingishardwork,butit'salsoalotoffun.Ihadagreattime


writingthisbook,andIhopeyouenjoylearningfromit.I'mlooking
forwardtohearingaboutwhatyoucandoafteryoulearnfromthisbook.
—Andy


Chapter1:ExploringthePHPEnvironment


Overview
Webpagesareinteresting,butontheirowntheyaresimply
documents.YoucanusePHPtoaddcodetoyourWebpagesso
theycandomore.AscriptinglanguagelikePHPcanconvertyour
Websitefromstaticdocumentstoaninteractiveapplication.Inthis
chapter,you'lllearnhowtoaddbasicPHPfunctionalitytoyourWeb
pages.Specifically,you'll:
ReviewHTMLcommands.
UseCascadingStyleSheetstoenhanceyourWebpages.
BuildHTMLforms.
EnsurePHPisonyoursystem.
RunabasicdiagnosticofyourPHPinstallation.
AddPHPcodetoaWebpage.


Introducingthe"TipoftheDay"Program
Yourfirstprogramprobablywon'twinanyWebawards,butitwilltake
youbeyondwhatyoucandowithregularHTML.Figure1.1illustratesthe
"Tipoftheday"page,whichoffersfriendly,helpfuladvice.


Figure1.1:Thetipofthedaymightlooksimple,butitisa
technologicalmarvel,becauseitfeatureshtml,cascadingstylesheets,
andPHPcode.
Ofcourse,youcouldwritethiskindofpagewithoutusingatechnology
likePHP,buttheprogramisalittlemoresophisticatedthanitmightlook
onthesurface.Thetipisn'tactuallyembeddedintheWebpageatall,but
itisstoredinacompletelyseparatefile.Theprogramintegratesthis
separatefileintotheHTMLpage.Thepageownercanchangethetipof
thedayveryeasilybyeditingthetextfilethatcontainsthetips.
You'llstartbyreviewingyourHTMLskills.Soonenough,you'regoingto
bewritingprogramsthatwriteWebpages,soyouneedtobeverysecure
withyourHTMLcoding.IfyouusuallywriteallyourWebpageswitha
plain-texteditor,youshouldbefine.Ifyoutendtorelyonhigherendtools
likeMicrosoftFrontPageorMacromediaDreamweaver,youshouldput
thosetoolsasideforawhileandmakesureyoucanwritesolidHTMLby
hand.
INTHEREALWORLD


TheTipofthedaypageillustratesoneofthehottestconceptsin
Webprogrammingtoday—thecontentmanagementsystem.This
kindofstructureallowsprogrammerstodesignthegenerallayout
ofaWebsite,butisolatesthecontentsfromthepagedesign.The
pageowners(whomightormightnotknowhowtomodifyaWeb
pagedirectly)caneasilychangeatextfilewithoutriskofexposing
thecodethatholdsthesitetogether.Asyouprogressthroughthis
book,you'lllearnhowtodeveloppowerfulcontentmanagement
systems,aswellasalotofothercoolthings.


ProgrammingontheWebServer
TheInternetisallaboutvariouscomputerscommunicatingwitheach
other.TheprevailingmodeloftheInternetisthenotionofclientsand
servers.Youcanunderstandthisbetterbyimaginingadrive-through
restaurant.Asyoudrivetothelittlespeaker,abarelyintelligiblevoice
asksforyourorder.Youaskforyour"cholesto-burgersupreme,"andthe
boredteenagerpackagesyourfood.Youdriveup,exchangemoneyfor
thecombomeal,anddriveaway.Meanwhile,theteenagerwaitsfor
anothercustomertoappear.TheInternetworksmuchlikethismodel.
LargepermanentcomputerscalledWebserverspermanentlyhostWeb
pagesandotherinformation.Theyaremuchlikethedrive-through
restaurant.Users"driveup"totheWebserverusingaWebbrowser.The
dataisexchanged,andtheusercanreadtheinformationontheWeb
browser.
What'sinterestingaboutthismodelistheinteractiondoesn'thavetostop
there.Sincetheclient(user's)machineisacomputer,itcanbegiven
instructions.Commonly,theJavaScriptlanguageisusedtostorespecial
instructionsinaWebpage.Theseinstructions(liketheHTMLcodeitself)
don'tmeananythingontheserver.Oncethepagegetstotheclient
machine,thebrowserinterpretstheHTMLcodeandanyotherJavaScript
instructions.Whilemuchoftheworkispassedtotheclient,thereare
somedisadvantagestothisclient-sideapproach.Programsdesignedto
workinsideaWebbrowserareusuallygreatlyrestrictedinthekindsof
thingstheycando.Aclient-sideWebprogramusuallycannotaccessthe
user'sprinterordiskdrives.Thislimitationalonepreventssuchprograms
fromdoingmuchofthemostusefulworkoftheInternet,suchas
databaseconnectivityandusertracking.
Theserverisalsoacomputer,andit'spossibletowriteprograms
designedtooperateontheserverratherthantheclient.Therearea
numberofadvantagestothisarrangement:
Server-sideprogramsrunonpowerfulWebservercomputers.
Theservercanfreelyworkwithfilesanddatabases.


ThecodereturnedtotheuserisplainHTML,whichcanbe
displayedonanyWebbrowser.


BuildingBasicHTMLPages
ThebasicunitofwebdevelopmentistheHTMLpage.Thisissimplya
textdocumentcontainingspecialtagstodescribethedatainthepage.
AlthoughyoumightalreadybefamiliarwithHTML,itmakessenseto
reviewtheseskillsbecausePHPprogrammingiscloselytiedtoHTML.
TRAP Asyouarebeginning,Istronglyurgeyoutouseaplaintext
editor.YoucanuseNotepadoroneofthemanyfreeeditors
available.Therearesomeexceptionalfreeeditorsavailable
ontheCD-ROMthataccompaniesthisbook.Word
processorsusuallydonotsavefilesinplaintextformat(which
PHPandHTMLrequire)andmanyofthefancyWebeditors
(suchasFrontPageorDreamweaver)tendtowriteclunky
codethatwillreallygetinyourwayonceyoustarttoadd
programmingfunctionalitytoit.

CreatingtheHTML"Hello"Page
HTMLismainlytext.TheWebauthoraddsspecialmarkupstoatext
documenttoindicatethemeaningofvariouselements.Whenauser
requestsaWebpage,thetextdocumentispulledfromtheWebserver,
andthebrowserinterpretsthevarioustagstodeterminehowthe
documentisdisplayedonthescreen.Figure1.2illustratesaverysimple
Webpage.




Figure1.2:AverybasicWebpage.
Ifyoulookatthecodeforthispage,youwillseethatit'sprettyeasyto
understand,evenifyouaren'tterriblyfamiliarwithHTMLcode.


Hello,World



Hello,World!


ThisismyfirstHTMLpage



Asyoucansee,manywordsareencasedinanglebraces(<>).These
wordsarecalledtags,andtheyaremeanttobeinterpretedas
instructionsfortheWebbrowser.Mosttagscomeinpairs.Forexample,
theentiredocumentbeginswithandendswithThe
slash(/)indicatesanendingtag.
EachHTMLdocumentcontainsaheadareasurroundedwitha
pair.Theheaderareacontainsinformationaboutthedocument
ingeneral.Italmostalwayscontainsatitle,whichisoftendisplayedin
thetitlebaroftheWebbrowser.However,therearenoguarantees.
HTMLtagsdescribethemeaningofanelement,notnecessarilyhowitis
tobedisplayed.It'suptoeachbrowsertodeterminehowsomethingwill
bedisplayed.
ThebulkofanHTMLdocumentiscontainedinthebody,indicatedwith
thetags.
WithinthebodyoftheHTMLdocument,youcanusetagstodefine
variouscharacteristicsofthepage.Usuallyyoucanguessatthe
meaningsofmostofthetags.Forexample,the



paircausesallthetextbetweenthetagstobecentered(ifthebrowser
cansupportthisfeature).
TRAP It'svitaltounderstandthatHTMLtagsarenotcommandsto
thebrowserasmuchassuggestions.Thisisbecausethere
aresomanydifferenttypesofcomputersandWebbrowsers
available.It'spossiblethatsomebodymightlookatyourWeb
pageonapalm-sizedcomputeroracellphone.These
deviceswillnotbeabletodisplayinformationinthesameway
asfull-sizecomputers.TheWebbrowserwilltrytofollowyour
instructions,butultimately,thewaythepagelookstotheend
userisnotunderyourdirectcontrol.
The

tagsareusedtodesignatethatthetextcontained
betweenthetagsisalevel-one(highestpriority)heading.HTMLsupports
sixlevelsofheading,from

to

.Youcan'tbeexactlysurehow
theseheadingswillappearinauser'sbrowser,butanytextinan


pairwillbestronglyemphasized,andeachdescendingheadlevelcauses
thetextdesignatedbythatcodetohavelessandlessemphasis.

BasicTags
ThereareanumberoftagsassociatedwithHTML.Mostofthesetags
areusedtodeterminethemeaningofaparticularchunkoftext.Table1.1
illustratessomeofthesetags.
Table1.1:BASICHTMLTAGS
Tag

Meaning Discussion



Bold

Won'tworkonallbrowsers.



Italic

Won'tworkonallbrowsers.



Level1
header

Strongestheadlineemphasis.



Level6
header

Weakestheadlinelevel(levels2–5
alsosupported).






UnMustcontainlistitems(
  • ).
    numbered Usedforbulletedlists.
    list
    Addasmanylistitemsasyouwish.




    1. Mustcontainlistitems(
    2. ).
      Ordered
      list



    Usedfornumberedlist.
    Addasmanylistitemsasyouwish.

    Placesalinkonthepage.
    Textbetweenandwillbe
    "anotherPage.html"> Anchor
    gotoanother
    (hyperlink) visibleonpageasalink.Whenuser
    clicksonlink,browserwillgotothe
    page
    specifiedaddress.
    "imgName.gif">
    size=5>
    thistextisred


    image

    Addsthespecifiedimagetothe
    page.ImagesshouldbeinGIF,JPG,
    orPNGformats.
    Willnotworkinallbrowsers.

    Modify
    font

    It'spossibletomodifyfontcolor,size,
    andface(typeface),although
    typefacewilloftennottransferto
    clientmachine.
    Causesacarriagereturninthe
    output.Doesnothaveanendingtag.




    Break




    Horizontal Addahorizontallinetothepage.
    rule
    Doesnothaveanendingtag.

    Ofcourse,therearemanyotherHTMLtags,butthosefeaturedinTable
    1.1arethemostcommonlyused.Figure1.3illustratesseveralofthetags
    featuredinTable1.1.



    Figure1.3:AnHTMLpagecontainingthemostcommonHTML
    tags.
    Thesourcecodeforthebasic.htmldocumentillustrateshowthepage
    wasdesigned.


    BasicHTMLTags


    BasicHTMLTags


    Thisisanh1header


    Thisisanh2header


    Thisisanh3header


    Thisisanh4header


    Thisisanh5header

    Thisisanh6header


    Thistextiscentered

    Thisisbold


    Thisisitalic






    TheH1throughH6headerscreateheadlinesofvaryingsizeand
    emphasis.Thetagcausestexttobebold,andformatstextin
    italics.Finally,the
    tagisusedtodrawahorizontallineonthepage.

    MoreHTMLTags
    TherestofthetagsshowninTable1.1arefeaturedinFigure1.4.


    Figure1.4:ExamplesofseveralotherbasicHTML
    tags.
    Thetagsinmore.htmlareusedtoaddlists,links,andimagestoaWeb
    page.Thecodeusedtoproducethispagelookslikethis:


    MoreHTMLTags


    MoreHTMLTags


    OrderedList





    1. alpha

    2. beta

    3. charlie


    UnorderedList



    • alpha

    • beta

    • charlie


    Hyperlink



    Andy'sHomepage

    Image


    height=100
    width=100>


    HTMLsupportstwotypesoflists.The
      setcreatesordered
      (ornumbered)lists.Eachelementinthelistset(specifiedbyan

    1. pair)isautomaticallynumbered.The
        tagsareused
        toproduceunnumberedlists.Each
      • elementisautomatically
        givenabullet.
        Hyperlinksaretheelementsthatallowyourusertomovearoundonthe
        Webbyclickingonspeciallydesignatedtext.Thetagisusedto
        designateahyperlink.Thetagalmostalwaysincludesanhref
        attribute,whichindicatesanaddress.Theuserwillberedirectedto
        whicheveraddressisindicatedinthisaddresswhenheorsheclickson
        thelink.Thetext(orotherhtml)betweenthe
        andtagswillbe


        designatedasthehyperlink.Thattextwillappearonthepageasalink
        (usuallyblueandunderlined).Inthemore.htmlexample,Icreateda
        linktooneofmyhomepages(http://www.cs.iupui.edu).Whentheuser
        clicksonthe"Andy'sHomePage"linkinthebrowser,heorshewillbe
        transportedtothatpage.
        Theotherfeatureillustratedinmore.htmlisthetag.Thistagis
        usedtoincludeimagesintoaWebpage.Mostbrowsersreadilysupport
        .gifand.jpgfiles,andmanynowcansupportthenewer.pngformat.
        TRICK Ifyouhaveanimageinsomeotherformat,oranimagethat
        needstobemodifiedinsomewaybeforeusingitinyourWeb
        page,youcanusefreesoftwaresuchasirfanVieworthe
        Gimp(bothincludedontheCD-ROMthataccompaniesthis
        book).

        Tables
        Therearemanytimesyoumightbeworkingwithlargeamountsof
        informationthatcouldbenefitfromtable-styleorganization.HTML
        supportsasetoftagsthatcanbeusedtobuildtables.Thesetagsare
        illustratedinFigure1.5.


        Figure1.5:Tablescanbebasic,orcellscanoccupymultiplerowsand
        columns.


        ×