PHP外文翻译文献Word文档下载推荐.docx
《PHP外文翻译文献Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《PHP外文翻译文献Word文档下载推荐.docx(14页珍藏版)》请在冰豆网上搜索。
:
connect("
mysql:
//$db_username:
$db_password@$db_host/$db_database"
);
Thesamebasicinformationispresentinbothcommands,butthePEARfunctionalsospecifiesthetypeofdatabasestowhichtoconnect.YoucanconnecttoMySQLorothersupporteddatabases.We’lldiscussbothconnectionmethodsindetail.
Inthischapter,you’lllearnhowtoconnecttoaMySQLserverfromPHP,howtousePHPtoaccessandretrievestoreddata,andhowtocorrectlydisplayinformationtotheuser.
TheProcess
Thebasicstepsofperformingaquery,whetherusingthemysqlcommand-linetoolorPHP,arethesame:
•Connecttothedatabase.
•Selectthedatabasetouse.
•BuildaSELECTstatement.
•Performthequery.
•Displaytheresults.
We’llwalkthrougheachofthesestepsforbothplainPHPandPEARfunctions.
Resources
WhenconnectingtoaMySQLdatabase,youwillusetwonewresources.Thefirstisthelinkidentifierthatholdsalloftheinformationnecessarytoconnecttothedatabaseforanactiveconnection.Theotherresourceistheresultsresource.Itcontainsallinformationrequiredtoretrieveresultsfromanactivedatabasequery’sresultset.You’llbecreatingandassigningbothresourcesinthischapter.
QueryingtheDatabasewithPHPFunctions
Inthissection,weintroducehowtoconnecttoaMySQLdatabasewithPHP.It’squitesimple,andwe’llbeginshortlywithexamples,butweshouldtalkbrieflyaboutwhatactuallyhappens.WhenyoutryconnectingtoaMySQLdatabase,theMySQLserverauthenticatesyoubasedonyourusernameandpassword.PHPhandlesconnecting
tothedatabaseforyou,anditallowsyoutostartperformingqueriesandgatheringdataimmediately.
AsinChapter8,we’llneedthesamepiecesofinformationtoconnecttothedatabase:
•TheIPaddressofthedatabaseserver
•Thenameofthedatabase
•Theusername
•Thepassword
Beforemovingon,makesureyoucanlogintoyourdatabaseusingtheMySQLcommand-lineclient.
Figure9-1showshowthestepsofthedatabaseinteractionrelatetothetwotypesofresources.BuildingtheSELECTstatementhappensbeforethethirdfunctioncall,butitisnotshown.It’sdonewithplainPHPcode,notaMySQL-specificPHPfunction.
Figure9-1.Theinteractionbetweenfunctionsandresourceswhenusingthedatabase
IncludingDatabaseLoginDetails
You’regoingtocreateafiletoholdtheinformationforloggingintoMySQL.Storingthisinformationinafileyouincludeisrecommended.Ifyouchangethedatabasepassword,thereisonlyoneplacethatyouneedtochangeit,regardlessofhowmany
PHPfilesyouhavethataccessthedatabase.
Youdon’thavetoworryaboutanyonedirectlyviewingthefileandgettingyourdatabaselogindetails.Thefile,ifrequestedbyitself,isprocessedasaPHPfileandreturnsablankpage.
Troubleshootingconnectionerrors
Oneerroryoumaygetis:
Fatalerror:
Calltoundefinedfunctionmysql_connect()inC:
\ProgramFiles\Apache
SoftwareFoundation\Apache2.2\htdocs\db_test.phponline4
ThiserroroccursbecausePHP5.xforWindowswasdownloaded,andMySQLsupportwasnotincludedbydefault.Tofixthiserror,copythephp_mysql.dllfilefromtheext/directoryofthePHPZIPfiletoC:
\php,andthenC:
\WINDOWS\php.ini.
Makesuretherearetwolinesthatarenotcommentedoutbyasemicolon(;
)atthebeginningofthelinelikethese:
extension_dir="
c:
/PHP/ext/"
extension=php_mysql.dll
ThiswillchangetheextensiontoincludethedirectorytoC:
/phpandincludetheMySQLextension,respectively.YoucanusetheSearchfunctionofyourtexteditortocheckwhetherthelinesarealreadythereandjustneedtobeuncommented,orwhethertheyneedtobeaddedcompletely.
You’llneedtorestartApache,andthenMySQLsupportwillbeenabled.
SelectingtheDatabase
Nowthatyou’reconnected,thenextstepistoselectwhichdatabasetousewiththemysql_select_dbcommand.Ittakestwoparameters:
thedatabasenameand,optionally,thedatabaseconnection.Ifyoudon’tspecifythedatabaseconnection,thedefaultistheconnectionfromthelastmysql_connect:
//Selectthedatabase
$db_select=mysql_select_db($db_database);
if(!
$db_select)
{
die("
Couldnotselectthedatabase:
<
br/>
"
.mysql_error());
}
Again,it’sgoodpracticetocheckforanerroranddisplayiteverytimeyouaccessthedatabase.
Nowthatyou’vegotagooddatabaseconnection,you’rereadytoexecuteyourSQLquery.
BuildingtheSQLSELECTQuery
BuildingaSQLqueryisaseasyassettingavariabletothestringthatisyourSQLquery.Ofcourse,you’llneedtouseavalidSQLquery,orMySQLreturnswithanerrorwhenyouexecutethequery.Thevariablename$queryisusedsincethenamereflectsitspurpose,butyoucanchooseanythingyou’dlikeforavariablename.TheSQLqueryinthisexampleisSELECT*FROMbooks.
Youcanbuildupyourqueryinpartsusingthestringconcatenate(.)operator:
ExecutingtheQuery
Tohavethedatabaseexecutethequery,usethemysql_queryfunction.Ittakestwoparameters—thequeryand,optionally,thedatabaselink—andreturnstheresult.Savealinktotheresultsinavariablecalled,youguessedit,$result!
Thisisalsoagoodplacetocheckthereturncodefrommysql_querytomakesurethattherewerenoerrorsinthequerystringorthedatabaseconnectionbyverifyingthat$resultisnotFALSE:
Whenthedatabaseexecutesthequery,alloftheresultsformaresultset.Theseresultscorrespondtotherowsthatyousawupondoingaqueryusingthemysqlcommand-lineclient.Todisplaythem,youprocesseachrow,oneatatime.
FetchingandDisplaying
Usemysql_fetch_rowtogettherowsfromtheresultset.Itssyntaxis:
arraymysql_fetch_row(resource$result);
Ittakestheresultyoustoredin$resultfromthequeryasaparameter.Itreturnsonerowatatimefromthequeryuntiltherearenomorerows,andthenitreturnsFALSE.Therefore,youdoaloopontheresultofmysql_fetch_rowanddefinesomecodetodisplayeachrow:
Thecolumnsoftheresultrowarestoredinthearrayandcanbeaccessedoneatatime.Thevariable$result_row[2]accessesthesecondattribute(asdefinedinthequery’scolumnorderorthecolumnorderofthetableifSELECT*isused)intheresultrow.
Fetchtypes
Thisisnottheonlywaytofetchtheresults.Usingmysql_fetch_array,PHPcanplacetheresultsintoanarrayinonestep.Ittakesaresultasitsfirstparameter,andthewaytobindtheresultsasanoptionalsecondparameter.IfMYSQL_ASSOCisspecified,theresultsareindexedinanarraybasedontheircolumnnamesinthequery.IfMYSQL_NUMisspecified,thenthenumberstartingatzeroaccessestheresults.Thedefaultvalue,MYSQL_BOTH,returnsaresultarraywithbothtypes.Themysql_fetch_
associsanalternativetosupplyingtheMYSQL_ASSOCargument.
ClosingtheConnection
Asaruleofthumb,youalwayswanttocloseaconnectiontoadatabasewhenyou’redoneusingit.Closingadatabasewithmysql_closewilltellPHPandMySQLthatyounolongerwillbeusingtheconnection,andwillfreeanyresourcesandmemoryallocatedtoit:
mysql_close($connection)
Installing
PEARusesaPackageManagerthatoverseeswhichPEARfeaturesyouinstall.
WhetheryouneedtoinstallthePackageManagerdependsonwhichversionofPHPyouinstalled.Ifyou’rerunningPHP4.3.0ornewer,it’salreadyinstalled.Ifyou’rerunningPHP5.0,PEARhasbeensplitoutintoaseparatepackage.TheDBpackagethatyou’reinterestedinisoptionalbutinstalledbydefaultwiththePackageManager.SoifyouhavethePackageManager,you’reallset.
Unix
YoucaninstallthePackageManageronaUnixsystembyexecutingthefollowing
fromtheshell(command-line)prompt:
lynx-sourcehttp:
//go-pear.org/|php
Thistakestheoutputofthego-pear.orgsite(whichisactuallythesourcePHPcode)toinstallPEARandpassesitalongtothephpcommandforexecution.
Windows
ThePHP5installationincludesthePEARinstallationscriptasC:
\php\go-pear.bat.Incaseyoudidn’tinstallallthefilesinChapter2,goaheadandextractallthePHPfilestoC:
/phpfromthecommandprompt,andexecutethe.batfile.
Creatingaconnectinstance
TheDB.phpfiledefinesaclassoftypeDB.RefertoChapter5formoreinformationonworkingwithclassesandobjects.We’llprincipallybecallingthemethodsintheclass.TheDBclasshasaconnectmethod,whichwe’lluseinsteadofouroldconnectfunctio