Tải bản đầy đủ - 0 (trang)
Chapter 25.  Running Web Applications with MySQL and PHP

Chapter 25.  Running Web Applications with MySQL and PHP

Tải bản đầy đủ - 0trang

ToobtainaworkingLAMPinstallation,youwillneedtohave

Apachesetupasdescribedin"ConfiguringYourOwnWeb

Server"inChapter22,aswellastoinstallMySQLandPHP.We

willcoverhowtogetthelattertwoapplicationsrunninginthis

chapter.

Beforewegetintothetechnicaldetails,however,weshould

reviewwhyyoumightwanttobothersettingupandlearning

howtouseaLAMPsystem.

LAMPmakesiteasytoprovidealargeamountofcontentand

allowusersofyourwebsitetonavigatethroughiteasily.

Let'ssayyouhaveasitewithlotsofJPEGsofphotographs

you'vetakenonnumerousoccasions.Visitorsmaywanttoview

photographsusinganumberofdifferentcriteria.Thatis,some

visitorswanttoseephotographsofhistoricbuildings,whenever

youtookthem.Othersmightwanttoseephotographstakenon

yourlatesttrip,wheneverthatwas.

Tomakenavigationandretrievaleasy,youstartbyinserting

theinformationaboutyourJPEGsintoaMySQLdatabase.(The

JPEGfileswillremainonthefilesystemwhereApachecanget

tothemquickly.)Youorganizethemanywayyouwant(by

subjectmatter,bytrip,andsoon)andstoreallthisinformation

intableswithinthedatabase.Inotherwords,dataisstoredin

tables,andanumberofrelatedtablesmakeupadatabase.

Nowyouprovideaformonyourwebsitethatvisitorscanfill

outtoindicatethedimensionalongwhichtheywanttoview

photographs.Theformcouldbeassimpleasthatshownin

Figure25-1.



Figure25-1.Asimpleinputform



Yournextpageisadynamicone,alongthelinesofthatwhich

wedescribeinthischapter.AbitofPHPcoderetrievesthe

visitor'srequestanddetermineswhatisdisplayedinthepage.

ThiscouldlooklikeFigure25-2.

WhereistheMySQLinallthis?It'snotimmediatelyvisible,but

itplaysacrucialrolebehindthescenesbecauseitisqueriedby

thePHPcode.ThecombinationofinlinePHPcodeandafast

databasemakesthewholeexperiencefairlypleasantforthe

visitor.



Figure25-2.Adynamicwebpagegeneratedby

PHP







25.1.MySQL

MySQLisanopensourcedatabasethatisveryfastand

comparativelyeasytoadminister.Ifyouneedthemost

advanceddatabasefeatures,suchasreplicationordistributed

databases,orifyouplantostoregigabytesofdata,thebig-iron

databasessuchasOraclemightbeabetterchoice,butformost

intentsandpurposes,MySQLisanexcellentdatabasechoice

(anditisinfactcatchingupevenwhenitcomestothosevery

advancedfeatures).Itisdual-licensed.IfyouareusingtheGPL

version,yourapplicationmustbelicensedundertheGPLas

well;otherwise,youneedtobuythecommercialversion.



25.1.1.MySQLInstallationandInitial

Configuration

Itisverylikelythatyourdistributioncontainsaninstallable

MySQLsystem,butifyou'dratherhavethelatestandgreatest,

youcangotohttp://www.mysql.com/downloadsanddownload

thepackageyourself.Atthetimeofthiswriting,thelatest



OntheChoiceofDatabases

WeshouldprobablypointoutthatMySQLisnottheonlychoiceyouhavewhen

selectingadatabaseasthebackendfordynamicwebsites.Forexample,

Postgres,whichisinstalledbydefaultonRedHatsystems,isaverygoodopen

sourcedatabaseaswell.So,ifyouwanttodeploya"LAPP"systemanduse

Postgresinstead,youcanverywelldothat.Mostoftheinformationinthis

chapterwillstillapply.However,MySQLcanbeconsideredthestandarddatabase

fordynamicwebsitesonLinuxsystems.Thisisduetoitseaseofuse,speed,

andversatility.Also,ifyouarelookingforadditionaldocumentationondeploying

dynamicwebsitesonLinux(whichwestronglyrecommendyoudo),youare

morelikelytofindthisinformation(e.g.,intheformofdedicatedbooksonthis

topic)forMySQLthanforPostgres.



stableversionwas4.1.13.Version5.0wasstabilizingquickly.If

youplantouseMySQLforreal-lifeapplications,makesureyour

Linuxkernelisat2.4orbetter.

AproblemthatcanoccurwithMySQLversionscompiledwith

gcc2.96israndomcrashes.Thisgccversionisnotanofficial

stableversion,butatleastonedistributor(RedHat)

unfortunatelyshippeditasthedefaultcompilerinoneversion.

Soifyouexperiencestrangecrashesinthedatabaseserverand

areusinggcc2.96,tryusingoneoftheprecompiledbinariesor

installamorestable(andmorerecent)compilerversion,such

as3.3.5.

IfyouwanttobuildMySQLonyourown,youneedtodownload

thesourcepackage,unpackit,andinstallwiththefollowing

commands:

owl$./configure--prefix=/usr/local/mysql

owl$make

owl#makeinstall



Notethatdependingonyoursystem,youmightselecta

differentinstallationpath.Youwillalsoprobablyneedtoberoot

forthethirdstep.Youneedtoremembertheinstallationpath

becauseyouwillneeditforthePHPconfigurationlateron.

Forthenextstep,werecommendthatyoucreateauseranda

groupcalledmysqlasdescribedin"CreatingAccounts"in

Chapter11.Changetothisuserwithsu-mysqlandexecute:

owl$scripts/mysql_install_db



Forsecurityreasons,itmightbeagoodideatodisablelogins

bythemysqluser.Youcansimplydothisasrootbyputtinga

starinthesecond(password)columnin/etc/passwordor

/etc/shadow,orboth.

Afterthisstep,youneedtoperformjustonemorecommand

beforereturningfromroottoyournormaluseraccount.The

followingcommandstartstheMySQLserver:

owl#/usr/local/mysql/bin/mysqld_safe&



Youmightalsowanttoaddeithertheoption--logortheoption

--log-long-formatinordertogetalogfileaboutwhatisgoing

oninthedatabaseserver.

Tocheckwhetheryourserverwasstartedcorrectly,youcantry

(asanormaluseragain)thefollowingcommand(youneedto

changethepath,ofcourse,ifyouhaveinstalledMySQLina

differentlocation):

owl$/usr/local/mysql/bin/mysqladminversion



mysqladminVer8.41Distrib4.1.13,forsuse-linuxoni686

Copyright(C)2000MySQLAB&MySQLFinlandAB&TCXDataKonsul

ThissoftwarecomeswithABSOLUTELYNOWARRANTY.Thisisfrees

andyouarewelcometomodifyandredistributeitundertheGPL

Serverversion4.1.13

Protocolversion10

ConnectionLocalhostviaUNIXsocket

UNIXsocket/var/lib/mysql/mysql.sock

Uptime:43days11hours39min17sec



Threads:1Questions:142Slowqueries:0Opens:160Flush

tables:13Queriespersecondavg:0.000



Thisshouldworkwithoutenteringapassword.Wewouldliketo

pointout,though,thatitisnotagoodideatohaveadatabase

withoutapasswordbecausethatincreasestheoddsthata

possibleintruderwillgetatyourpotentiallyvaluabledatainthe

database.Youmightperhapswanttoleavethedatabase

withoutapasswordfortesting,butyoushouldmakesurethat

youdonotforgettosetapasswordafteryouaredonewith

yourtests.Retesttoseewhethereverythingworkswiththe

passwordinplace.Ifyouhavecreatedapasswordfortheroot

databaseuser(orifyourdistributionhasdonesoforyoucheck

yourdocumentationincaseofanyproblems),youmustspecify

the-poption,whichmakesmysqladminaskyouforyour

password.

Weshouldaddherethatmostdistributionsincludeastartup

scriptfortheMySQLserverthatyoucanuseinsteadofstarting

theservermanually(especiallyifyouhaveinstalledMySQL

fromyourinstallationmedia).Often,thisscriptisin

/etc/init.d/mysql.

Withthedatabaseserverstartedandworking,wecanstartto



definedatabaseusersandcreatenewdatabases.Wewouldlike

topointoutthatausabletutorialisincludedwiththeMySQL

sources.Youcanalsofindlotsofdocumentationon

http://www.mysql.com,sowejustcovertheverybasicshereto

getyoustarted.



25.1.2.InitialTasks:SettingUpUsersandSQL

TherearethreewaysofcommunicatingwiththeMySQLengine:

youcanuseaconsole-baseddatabaseclient,youcanwritesocalledSQLscriptsandfeedthemtothedatabaseinorderto

executemanySQLcommandsatonce,andyoucanuseoneof

themanybindingstoprogramminglanguagestoaccessthe

MySQLdatabaseintheprogramminglanguageofyourchoice

(dependingontheaccesslibrarythatyouuse,thismayeven

meanthatyoudonothavetoenterSQLstatementsatall).SQL

standsforStructuredQueryLanguageandisthedatabase

languageusedwithrelationaldatabases;wecoveritsuselater

inthischapter.AllthreewaysofexecutingSQLcommands

assumethatyouhavethecorrectusername/password

combination.

AnimportantthingyouneedtoknowaboutMySQListhatLinux

useraccountsaredifferentfromMySQLuseraccounts.Inother

words,MySQLhasitsownaccountmanagement.Mostpeople

givetheirMySQLuseraccountsthesamenamesastheirLinux

useraccountsinordertoavoidconfusion,though.

Bydefault,thereisoneMySQLaccountcalledroot,whichhas

nopassword(talkabout"securitybydefault").Thismeansthat

youcanaccessthedatabaseserverwiththeinteractive

command-linetoolmysqlasfollows:

owl$mysql-uroot

WelcometotheMySQLmonitor.Commandsendwith;or\g.



YourMySQLconnectionidis13toserverversion:4.1.13.

Type'help;'or'\h'forhelp.Type'\c'toclearthebuffer.

mysql>



The-uoptionspecifiesthedatabaseusertouse.Ifthisdoes

notwork,maybeyourMySQLinstallationhasapasswordsetfor

therootuser.Trytofindthispasswordinthedocumentation

andstartthemysqlprogramwith:

owl$mysql-uroot-p



whichwillpromptyouforthepassword.

Assumingthatyouhavebeenabletologintothedatabase

server,let'strytoissueacommand:[*]

[*]ThisisnotarealSQLcommand,butratheraMySQLadministrationcommand.



mysql>showdatabases;

+-------------+

|Database|

+-------------+

|mysql|

|test|

+-------------+

2rowsinset(0.11sec)



Thistellsyouthattwodatabasesaremanagedbythisdatabase

server.OneiscalledmysqlandcontainsMySQL'sinternal



configurationinformation,includingtheusernames,andthe

otheroneiscalledtestandcanbeusedbyyouforyour

experiments.It'salsonoproblematalltocreateadditional

databases;we'llshowyouhowinaminute.Asyoucansee,all

SQLcommandsneedtobeterminatedwitha

semicolonprobablyinordertomaketheCprogrammershappy.

Nowyoushouldgivetherootaccountapassword(incaseit

doesnothaveonealready).ThisisdonewithtwoSQL

commands:

mysql>SETPASSWORDFORroot=PASSWORD('new_topsecret_passwd');

mysql>FLUSHPRIVILEGES

;



Noticeagainthesemicolonattheendofthesecommands;if

youforgettotypethembeforepressingtheEnterkey,MySQL

willjuststareatyou,waitingforyoutoentermore.

Bytheway,SQLcommandsarecase-insensitive;wehave

writtentheminuppercaseherebecausethatmakesitabit

easiertoseewherethecommandkeywordsandthevariable

parametersareinaSQLscript.

AlsonotetheuseoftheFLUSHPRIVILEGEScommand.Thisis

importantbecauseonlyafterthiscommandhasbeenexecuted

willMySQLupdateitsuserdatabase.

Nowwewanttocreateanewusercalledolof,whichhasthe

sameaccessrightsasroot,exceptthatitcannotcreatenew

users.Apartfromthat,olofmayuseandmanipulateallMySQL

databasesonthisdatabaseserver:



mysql>GRANTALLPRIVILEGESON*.*TOolof@localhostIDENTIFIED

mysql>FLUSHPRIVILEGES;



Theuserolofcanlogintothedatabaseonlyfromthelocal

machine.Thisisagoodideasinceitleavesonelesssecurity

issuetothinkabout.Werecommendthatyouonlyallowaccess

fromthelocalmachineunlessyouhaveaverygoodreasonnot

todoitthisway.EvenintheLAMPcombo,localaccessis

enough,becausethewebserverprocessisrunningonthelocal

machine,andthisistheprocessthatconnectstothedatabase,

nottheuser'swebbrowserprocess.

Butifyoureallyrequireaccesstothedatabaseoverthe

network,youcouldusethesecommandsinstead:



mysql>GRANTALLPRIVILEGESON*.*TOusername@"%"IDENTIFIED

mysql>FLUSHPRIVILEGES;



Ifyouthinkthathavingallaccessrightsexceptcreatingnew

usersisabittoomuch,let'screateanotheruserthatmay

executetheSELECT,INSERT,UPDATE,DELETE,andDROPoperations,but

onlyonthedatabasecalledtest(andonlywhenconnectedfrom

thelocalmachine):



mysql>GRANTSELECT,INSERT,UPDATE,DELETE,DROPONtest.*TO

IDENTIFIEDBY'gonzo_passwd';

mysql>FLUSHPRIVILEGES;



Ifyouhaven'tworkedwithSQLdatabasesbefore,these

operationswillprobablynotmakemuchsensetoyou.Since

youaregoingtoneedtousethemanywaywhensettingup

yourLAMPsystem,wemightaswellshortlydescribethem

here:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 25.  Running Web Applications with MySQL and PHP

Tải bản đầy đủ ngay(0 tr)

×