已阅读5页,还剩11页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
0外文翻译及原文原文:GettingPHPtoTalktoMySQlNowthatyourecomfortableusingtheMySQLclienttoolstomanipulatedatainthedatabase,youcanbeginusingPHPtodisplayandmodifydatafromthedatabase.PHPhasstandardfunctionsforworkingwiththedatabase.First,weregoingtodiscussPHPsbuilt-indatabasefunctions.WellalsoshowyouhowtousetheThePHPExtensionandApplicationRepository(PEAR)databasefunctionsthatprovidetheabilitytousethesamefunctionstoaccessanysupporteddatabase.Thistypeofflexibilitycomesfromaprocesscalledabstraction.Inprogramminginterfaces,abstractionsimplifiesacomplexinteraction.Itworksbyremovinganynonessentialpartsoftheinteraction,allowingyoutoconcentrateontheimportantparts.PEARsDBclassesareonesuchdatabaseinterfaceabstraction.Theinformationyouneedtologintoadatabaseisreducedtothebareminimum.ThisstandardformatallowsyoutointeractwithMySQL,aswellasotherdatabasesusingthesamefunctions.Similarly,otherMySQL-specificfunctionsarereplacedwithgenericonesthatknowhowtotalktomanydatabases.Forexample,theMySQL-specificconnectfunctionis:mysql_connect($db_host,$db_username,$db_password);versusPEARsDBconnectfunction:$connection=DB:connect(mysql:/$db_username:$db_password$db_host/$db_database);Thesamebasicinformationispresentinbothcommands,butthePEARfunctionalsospecifiesthetypeofdatabasestowhichtoconnect.YoucanconnecttoMySQLorothersupporteddatabases.Welldiscussbothconnectionmethodsindetail.Inthischapter,youlllearnhowtoconnecttoaMySQLserverfromPHP,howtousePHPtoaccessandretrievestoreddata,andhowtocorrectlydisplayinformationtotheuser.1TheProcessThebasicstepsofperformingaquery,whetherusingthemysqlcommand-linetoolorPHP,arethesame:Connecttothedatabase.Selectthedatabasetouse.BuildaSELECTstatement.Performthequery.Displaytheresults.WellwalkthrougheachofthesestepsforbothplainPHPandPEARfunctions.ResourcesWhenconnectingtoaMySQLdatabase,youwillusetwonewresources.Thefirstisthelinkidentifierthatholdsalloftheinformationnecessarytoconnecttothedatabaseforanactiveconnection.Theotherresourceistheresultsresource.Itcontainsallinformationrequiredtoretrieveresultsfromanactivedatabasequerysresultset.Youllbecreatingandassigningbothresourcesinthischapter.QueryingtheDatabasewithPHPFunctionsInthissection,weintroducehowtoconnecttoaMySQLdatabasewithPHP.Itsquitesimple,andwellbeginshortlywithexamples,butweshouldtalkbrieflyaboutwhatactuallyhappens.WhenyoutryconnectingtoaMySQLdatabase,theMySQLserverauthenticatesyoubasedonyourusernameandpassword.PHPhandlesconnectingtothedatabaseforyou,anditallowsyoutostartperformingqueriesandgatheringdataimmediately.AsinChapter8,wellneedthesamepiecesofinformationtoconnecttothedatabase:TheIPaddressofthedatabaseserverThenameofthedatabaseTheusernameThepasswordBeforemovingon,makesureyoucanlogintoyourdatabaseusingtheMySQLcommand-lineclient.2Figure9-1showshowthestepsofthedatabaseinteractionrelatetothetwotypesofresources.BuildingtheSELECTstatementhappensbeforethethirdfunctioncall,butitisnotshown.ItsdonewithplainPHPcode,notaMySQL-specificPHPfunction.Figure9-1.TheinteractionbetweenfunctionsandresourceswhenusingthedatabaseIncludingDatabaseLoginDetailsYouregoingtocreateafiletoholdtheinformationforloggingintoMySQL.Storingthisinformationinafileyouincludeisrecommended.Ifyouchangethedatabasepassword,thereisonlyoneplacethatyouneedtochangeit,regardlessofhowmanyPHPfilesyouhavethataccessthedatabase.Youdonthavetoworryaboutanyonedirectlyviewingthefileandgettingyourdatabaselogindetails.Thefile,ifrequestedbyitself,isprocessedasaPHPfileandreturnsablankpage.TroubleshootingconnectionerrorsOneerroryoumaygetis:Fatalerror:Calltoundefinedfunctionmysql_connect()inC:ProgramFilesApacheSoftwareFoundationApache2.2htdocsdb_test.phponline4ThiserroroccursbecausePHP5.xforWindowswasdownloaded,andMySQLsupportwasnotincludedbydefault.Tofixthiserror,copythephp_mysql.dllfilefromtheext/directoryofthePHPZIPfiletoC:php,andthenC:WINDOWSphp.ini.Makesuretherearetwolinesthatarenotcommentedoutbyasemicolon(;)atthebeginningofthelinelikethese:extension_dir=c:/PHP/ext/extension=php_mysql.dllThiswillchangetheextensiontoincludethedirectorytoC:/phpandincludetheMySQLextension,respectively.YoucanusetheSearchfunctionofyourtexteditortocheckwhether3thelinesarealreadythereandjustneedtobeuncommented,orwhethertheyneedtobeaddedcompletely.YoullneedtorestartApache,andthenMySQLsupportwillbeenabled.SelectingtheDatabaseNowthatyoureconnected,thenextstepistoselectwhichdatabasetousewiththemysql_select_dbcommand.Ittakestwoparameters:thedatabasenameand,optionally,thedatabaseconnection.Ifyoudontspecifythedatabaseconnection,thedefaultistheconnectionfromthelastmysql_connect:/Selectthedatabase$db_select=mysql_select_db($db_database);if(!$db_select)die(Couldnotselectthedatabase:.mysql_error();Again,itsgoodpracticetocheckforanerroranddisplayiteverytimeyouaccessthedatabase.Nowthatyouvegotagooddatabaseconnection,yourereadytoexecuteyourSQLquery.BuildingtheSQLSELECTQueryBuildingaSQLqueryisaseasyassettingavariabletothestringthatisyourSQLquery.Ofcourse,youllneedtouseavalidSQLquery,orMySQLreturnswithanerrorwhenyouexecutethequery.Thevariablename$queryisusedsincethenamereflectsitspurpose,butyoucanchooseanythingyoudlikeforavariablename.TheSQLqueryinthisexampleisSELECT*FROMbooks.Youcanbuildupyourqueryinpartsusingthestringconcatenate(.)operator:4ExecutingtheQueryTohavethedatabaseexecutethequery,usethemysql_queryfunction.Ittakestwoparametersthequeryand,optionally,thedatabaselinkandreturnstheresult.Savealinktotheresultsinavariablecalled,youguessedit,$result!Thisisalsoagoodplacetocheckthereturncodefrommysql_querytomakesurethattherewerenoerrorsinthequerystringorthedatabaseconnectionbyverifyingthat$resultisnotFALSE:Whenthedatabaseexecutesthequery,alloftheresultsformaresultset.Theseresultscorrespondtotherowsthatyousawupondoingaqueryusingthemysqlcommand-lineclient.Todisplaythem,youprocesseachrow,oneatatime.FetchingandDisplayingUsemysql_fetch_rowtogettherowsfromtheresultset.Itssyntaxis:arraymysql_fetch_row(resource$result);Ittakestheresultyoustoredin$resultfromthequeryasaparameter.Itreturnsonerowatatimefromthequeryuntiltherearenomorerows,andthenitreturnsFALSE.Therefore,youdoaloopontheresultofmysql_fetch_rowanddefinesomecodetodisplayeachrow:Thecolumnsoftheresultrowarestoredinthearrayandcanbeaccessedoneatatime.Thevariable$result_row2accessesthesecondattribute(asdefinedinthequeryscolumnorderorthecolumnorderofthetableifSELECT*isused)intheresultrow.FetchtypesThisisnottheonlywaytofetchtheresults.Usingmysql_fetch_array,PHPcanplacetheresultsintoanarrayinonestep.Ittakesaresultasitsfirstparameter,andthewaytobindtheresultsasanoptionalsecondparameter.IfMYSQL_ASSOCisspecified,theresultsareindexedinanarraybasedontheircolumnnamesinthequery.IfMYSQL_NUMisspecified,thenthenumberstartingatzeroaccessestheresults.Thedefaultvalue,MYSQL_BOTH,returnsaresultarraywithbothtypes.Themysql_fetch_associsanalternativetosupplyingtheMYSQL_ASSOCargument.ClosingtheConnection5Asaruleofthumb,youalwayswanttocloseaconnectiontoadatabasewhenyouredoneusingit.Closingadatabasewithmysql_closewilltellPHPandMySQLthatyounolongerwillbeusingtheconnection,andwillfreeanyresourcesandmemoryallocatedtoit:mysql_close($connection)InstallingPEARusesaPackageManagerthatoverseeswhichPEARfeaturesyouinstall.WhetheryouneedtoinstallthePackageManagerdependsonwhichversionofPHPyouinstalled.IfyourerunningPHP4.3.0ornewer,itsalreadyinstalled.IfyourerunningPHP5.0,PEARhasbeensplitoutintoaseparatepackage.TheDBpackagethatyoureinterestedinisoptionalbutinstalledbydefaultwiththePackageManager.SoifyouhavethePackageManager,youreallset.UnixYoucaninstallthePackageManageronaUnixsystembyexecutingthefollowingfromtheshell(command-line)prompt:lynx-source/|phpTsite(whichisactuallythesourcePHPcode)toinstallPEARandpassesitalongtothephpcommandforexecution.WindowsThePHP5installationincludesthePEARinstallationscriptasC:phpgo-pear.bat.IncaseyoudidntinstallallthefilesinChapter2,goaheadandextractallthePHPfilestoC:/phpfromthecommandprompt,andexecutethe.batfile.CreatingaconnectinstanceTheDB.phpfiledefinesaclassoftypeDB.RefertoChapter5formoreinformationonworkingwithclassesandobjects.Wellprincipallybecallingthemethodsintheclass.TheDBclasshasaconnectmethod,whichwelluseinsteadofouroldconnectfunction,mysql_connect.Thedoublecolons(:)indicatethatwerecallingthatfunctionfromtheclassinline4:6$connection=DB:connect(mysql:/$db_username:$db_password$db_host/$db_database);Whenyoucalltheconnectfunction,itcreatesanewdatabaseconnectionthatisstoredinthevariable$connection.Theconnectfunctionattemptstoconnecttothedatabasebasedontheconnectstringyoupassedtoit.ConnectstringTheconnectstringusesthisnewformattorepresentthelogininformationthatyoualreadysuppliedinseparatefields:dbtype:/username:passwordhost/databaseThisformatmaylookfamiliartoyou,asitsverysimilartotheconnectstringforaWindowsfileshare.ThefirstpartofthestringiswhatreallysetsthePEARfunctionsapartfromtheplainPHP.Thephptypefieldspecifiesthetypeofdatabasetoconnect.Supporteddatabasesincludeibase,msql,mssql,mysql,oci8,odbc,pgsql,andsybase.AllthatsrequiredforyourPHPpagetoworkwithadifferenttypeofdatabaseischangingthephptype!Theusername,password,host,anddatabaseshouldbefamiliarfromthebasicPHPconnect.Onlythetypeofconnectionisrequired.However,youllusuallywanttospecifyallfields.Afterthevaluesfromdb_login.phpareincluded,theconnectstringlookslikethefollowing:mysql:/test:testlocalhost/testIftheconnectmethodonline6wassuccessful,aDBobjectiscreated.Itcontainsthemethodstoaccessthedatabaseaswellasalloftheinformationaboutthestateofthatdatabaseconnection.QueryingOneofthemethodsitcontainsiscalledquery.ThequerymethodworksjustlikePHPsqueryfunctioninthatittakesaSQLstatement.Thedifferenceisthatthearrowsyntax(-)isusedtocallitfromtheobject.Italsoreturnstheresultsasanotherobjectinsteadofaresultset:$query=SELECT*FROMbooks$result=$connection-query($query);7BasedontheSQLquery,thiscodecallsthequeryfunctionfromtheconnectionobjectandreturnsaresultobjectnamed$result.FetchingLine22usestheresultobjecttocallthefetchRowmethod.Itreturnstherowsoneatatime,similartomysql_fetch_row:while($result_row=$result-fetchRow()echoTitle:.$result_row1.;echoAuthor:.$result_row4.;echoPages:.$result_row2.;UseanotherwhilelooptogothrougheachrowfromfetchRowuntilitreturnsFALSE.Thecodeintheloophasntchangedfromthenon-PEARexample.ClosingYourefinishedwiththedatabaseconnection,socloseitusingtheobjectmethoddisconnect:$connection-disconnect();PEARerrorreportingThefunctionDB:isErrorwillchecktoseewhethertheresultthatsbeenreturnedtoyouisanerror.Ifitisanerror,youcanuseDB:errorMessagetoreturnatextdescriptionoftheerrorthatwasgenerated.YouneedtopassDB:errorMessage,thereturnvaluefromyourfunction,asanargument.HereyourewritethePEARcodetouseerrorchecking:query($sql)echoDB:errorMessage($demoResult);else8while($demoRow=$demoResult-fetchRow()echo$demoRow2.;?TheresalsoanewversionofthePEARdatabaseinterfacecalledPEAR:MDB2.Thesameresultsdisplay,buttherearemorefunctionsavailableinthisversionofthePEARdatabaseabstractionlayer.NowthatyouhaveagoodhandleonconnectingtothedatabaseandthevariousfunctionsofPEAR。译文:9通过PHP访问MySQL现在你已经可以熟练地使用MySQL客户端软件来操作数据库里的数据,我们也可以开始学习如何使用PHP来显示和修改数据库里的数据了。PHP有标准的函数用来操作数据库。我们首先学习PHP内建的数据库函数,然后会学习PHP扩展和应用程序库(PEAR,PHPExtensionandApplicationRepository)中的数据库函数,我们可以使用这些函数操作所有支持的数据库。这种灵活性源自于抽象。对于编程接口而言,抽象简化了复杂的交互过程。它将交互过程中无关紧要的部分屏蔽起来,让你关注于重要的部分。PEAR的DB类就是这样一种数据库接口的抽象。你登录一个数据库所需要提供的信息被减少到最少。这种标准的格式可以通过同一个函数来访问MySQL以及其他的数据库。同样,一些MySQL特定的函数被更一般的、可以用在很多数据库上的函数所替代。比如,MySQL特定的连接函数是:mysql_connect($db_host,$db_username,$db_password);而PEAR的DB提供的连接函数是:$connection=DB:connect(mysql:/$db_username:$db_password$db_host/$db_database);两个命令都提供了同样的基本信息,但是PEAR的函数中还指定了要连接的数据库的类型。你可以连接到MySQL或者其他支持的数据库。我们会详细讨论这两种连接方式。本章中,我们会学习如何从PHP连接到MySQL的服务器,如何使用PHP访问数据库中存储的数据,以及如何正确的向用户显示信息。步骤无论是通过MySQL命令行工具,还是通过PHP,执行一个查询的基本步骤都是一样的:连接到数据库选择要使用的数据库创建SELECT语句执行查询显示结果我们将逐一介绍如何用PHP和PEAR的函数完成上面的每一步。10资源当连接到MySQL数据库的时候,你会使用到两个新的资源。第一个是连接的标识符,它记录了一个活动连接用来连接到数据库所必需的所有信息。另外一个资源是结果资源,它包含了用来从一个有效的数据库查询结果中取出结果所需要的所有信息。本章中我们会创建并使用这两种资源。使用PHP函数查询数据库本节我们会介绍如何使用PHP连接MySQL数据库。这非常简单,我们会用一些例子说明。但是之前我们应该稍微了解一下幕后发生的事情。当你试图连接一个MySQL数据库的时候,MySQL服务器会根据你的用户名和密码进行身份认证。PHP为你建立数据库的连接,你可以立即开始查询并得到结果。我们需要同样的信息来连接数据库:数据库服务器的IP地址数据库的名字用户名密码在开始之前,首先使用MySQL的命令行客户端确认你登录到数据库。图9-1显示了数据库交互过程的各个步骤和两种类型资源之间的关系。创建SELECT语句发生在第三个函数调用之前,但是在图中没有显示出来。它是通过普通的PHP代码,而不是MySQL特定的PHP函数完成的。图9-1:使用数据库时函数和资源之间的交互包含数据库登录细节我们先创建一个文件,用来保存登录MySQL所用到的信息。我们建议你把这些信息放在单独的文件里然后通过include来使用这个文件。这样一来如果你修改了数据库的密码。无论有多少个PHP文件访问数据库,你只需要修改这一个文件。连接到数据库我们需要做的头一件事情是连接数据库,并且检查连接是否确实建立起来。通过include包含连接信息的文件,我们可以在调用mysql_connect函数的时候使用这些变量而不是将这些值写死在代码中。我们使用一个叫做db_test.php的文件,往其中增加这些代码段。诊断连接错误你可能遇到的一个错误是:Fatalerror:Calltoundefinedfunctionmysql_connect()inC:ProgramFilesApacheSoftwareFoundationApache2.2htdocsdb_test.phponline411这个错误发生的原因是下载安装的PHP5.x默认没有包括对MySQL的支持。解决这个问题需要将php_mysql.dll文件从PHP压缩包例的ext/目录复制到C:/php,并修改C:WINDOWSphp.ini文件,确保下面两行没有被注释掉(注释的方法在行首使用分号)。extension_dir=c:/PHP/ext/extension=php_mysql.dll这样PHP扩展的目录就被设为C:PHP,MySQL的扩展也会被使用。在编辑php.ini文件的时候,你可以使用编辑器的搜索功能来检查这两行是否已经存在,只是需要去掉注释,并且需要重新输入。重新启动Apache,这样MySQL的支持就会被打开了。选择数据库建立连接之后,下一步就是使用mysql_select_db来选择我们要用的数据库。它的参数有两个:数据库名和可选的数据库连接。如果不指定数据库连接,默认使用上一条mysql_connect所建立的连接。/Selectthedatabase$db_select=mysql_select_db($db_database);if(!$db_select)die(Couldnotselectthedatabase:.mysql_error();同样的,每次访问数据库的时候最好能检查可能的错误并且进行显示。现在我们做好了一切准备工作,可以开始执行SQL查询了。构建SQLSELECT查询构建SQL查询非常容易就是将一个字符串赋值给变量。这个字符串就是我们的SQL查询,当然我们要给出有效的SQL查询,否则执行这个查询的时候MySQL会返回错误。我们使用$query作为变量名,这个名字对应其目的,你也可以选择任何你喜欢的变量名。这个例子中的SQL查询是”SELECT*FROMbooks”。你可以使用字符串连接操作符(.)来构建查询:执行查询使用mysql_query函数来告诉数据库执行查询。它有两个参数:查询和可选的数据库连接,返回值是查询结果。我们将查询结果保存在一个变量里,也许你已经猜到我们要用变量名就是$result。这里同样有必要检查mysql_query的返回值不是FALSE来确保查询字符串和数据库连接都没有问题。12当数据库查询的时候,所有的结果构成一个结果集。这些结果跟使用mysql命令行客户端执行同样查询所得到的行一致。要显示这些结果,你需要依次处理这些行。取结果并显示使用mysql_fetch_row从结果集中取出一行,它的用法如下:arraymysql_fetch_row(resource$result);它的参数是SQL查询返回的结果,我们将结果保存在$result中。每次调用它返回一行数据,直到没有数据为止,这时候它返回FALSE。这样,我们可以使用一个循环,在循环内调用mysql_fetch_row并使用一些代码来显示每一行。结果行的所有列都保存在一个数组里,可以方便地进行访问。变量$result_row2访问结果行的第二个属性(数组的顺序是查询是定义的列的顺序,如果使用SELECE*,那么数组顺序就是表的列的顺序)。取结果的方式去结果的方式不止一种。使用mysql_fetch_arrry可以一次性将所有结果放在一个数组里。它的参数是查询结果和一个可选的结果绑定方式。如果绑定方式指定为MYSQL_ASSOC,数组中的结果则使用查询中列的名字进行访问。如果指定了MYSQL_NUM,那么就使用从0开始的数字来访问结果。默认使用的方式是MYSQL_BOTH,这样返回的数组支持两种类型的访问。Mysql_fetch_assoc是使用MYSQL_ASSOC取结果的另外一种方式。关闭连接绝大部分情况下,我们在使用完一个数据库之后要关闭到它的连接。使用mysql_close来关闭一个数据库,它会告诉PHP和MySQL这个数据库连接已经不再使用,所使用的所有资源和内存都可以释放。mysql_close($connection)安装PEAR使用包管理器来管理安装PEAR模块。是否需要安装包管理取决于你所使用的PHP版本。如果你使用的版本是PHP4.4.0或者更新的版本,那么就已经安装了包管理器。如果你使用的是PHP5.0,则PEAR是一个单独的包。我们要用到的DB包是可选的,但是它会被包管理器默认安装。所以,如果你有包管理器,那么就全搞定了。UNIX在UNIX系统下,可以通过在shell(命令行)下执行下面的命令来安装包管理器:lynx-source/|php这个命令使用的输出(实际就是PHP源代码)来安装PEAR,的输出被传给php命令执行。13Windows安装完PHP5后,会有一个PEAR安装脚本C:phpgo-pear.b
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年厦门市思明区街道办人员招聘考试试题及答案详解
- 2025年抚顺市顺城区中小学教师招聘笔试试题及答案详解
- 2026年云浮市云城区街道办人员招聘考试模拟试题及答案详解
- 2026年北京市宣武区法检系统书记员招聘考试模拟试题及答案详解
- 2026年大连市普兰店区消防救援局面向社会公开招聘政府专职消防员6人考试备考题库及答案详解
- 2026年郴州市苏仙区法检系统书记员招聘考试参考试题及答案详解
- 2026年伊春市金山屯区中小学教师招聘考试模拟试题及答案详解
- 2026年白城市洮北区中小学教师招聘笔试参考试题及答案详解
- 2025年毕节地区中小学教师招聘考试试题及答案详解
- 2026年黄石市下陆区中小学教师招聘考试备考题库及答案详解
- 化疗药物配伍及输注操作标准
- 物业项目成本控制及预算管理方案
- 2024年注册安全工程师考试化工(初级)安全生产实务试题及答案
- 单位食堂食材供应及配送服务(肉类)服务方案投标文件(技术方案)
- 农村企业经营管理课件
- 铝锭联营合同与合作协议
- T/CADBM 3-2018竹木纤维集成墙面
- 《气体中毒急诊救治》课件
- 水利工程土石方施工方案设计
- GB/Z 44071-2024液压传动连接软管总成操作规程
- 烧烤视频拍摄脚本
评论
0/150
提交评论