Date post: | 10-Apr-2015 |
Category: |
Documents |
Author: | sitegroundcom-inc |
View: | 5,101 times |
Download: | 0 times |
SiteGroundTutorials PHP/MySQLTutorial:HowtoUsePHPandMySQL?PHPisthemostpopularscriptinglanguageforwebdevelopment.Itisfree,opensourceandserverside (thecodeisexecutedontheserver).MySQLisaRelationalDatabaseManagementSystem(RDBMS)that usesStructuredQueryLanguage(SQL).Itisalsofreeandopensource.ThecombinationofPHPand MySQLgivesunmetoptionstocreatejustaboutanykindofwebsitefromsmallcontactformtolarge corporateportal. ThisPHP/MySQLtutorialispartoftherichcollectionofwebhostingtutorialswhichSiteGroundexperts havepreparedforyou.Findouthowtostartyourwebsite,howtopromoteit,howtodealwithcPanel, webmailandFTP.
PHP/MySQLTutorialincludes:AshortintroductiononwhatisPHP WhatisMySQLandwhatareitsbenefits CreatingMySQLdatabaseanduserusefulinformationforinstallingaPHP/MySQLscriptonyour website RemovingMySQLdatabaseanduser LearnhowtomanageMySQLdatabaseswithphpMyAdminMySQLBackup/Restorefunctionality andhowtouseMySQLAccessHost Creatingadatabasetable Connectingtothedatabase Queryingthedatabase DisplayingtabledatainHTML Selectingindividualrecords HowtousetheMySQLGUItoolstobackup,restoreandexecutequeriesonyourdatabase InformationaboutZendOptimizer LearnhowtoinstallPearmodules.
PHPTutorial WhatisPHP?PHPwasatfirstcreatedasasimplescriptingplatformcalled"PersonalHomePage".NowadaysPHP(the shortforHypertextPreprocessor)isanalternativeofMicrosoft'sActiveServerPages(ASP)technology. PHPisanopensourceserversidelanguagewhichisusedforcreatingdynamicwebpages.Itcanbe embeddedintoHTML.PHPisusuallyusedinconjunctionwitha MySQLdatabaseonLinux/UNIXweb servers.Itisprobablythemostpopularscriptinglanguage. PHPisawidely usedgeneralpurposescriptinglanguageandinterpreterthatisfreelyavailable.Afull explanationofallthePHPtags,completeusermanualandlotsoftutorialscanbefoundonthe PHP's officialpage. OneofthemostimportantthingsaboutusingPHPistohaveaPHPspecializedhost.Herearesome ofthethingsweatSiteGroundareproudof: WehavelongexperienceinprovidingtechnicalsupportforPHPbasedwebsites.Thanksto itourserversareperfectlyoptimizedtoofferthebestoverallperformanceformostPHP applications. WeofferalotofFREEPHPtoolsincludingCMSsystems,forums,galleries,blogs,shopping cartsandmore. WeprovideseveralversionsofPHP(PHP5.0,PHP5.1,PHP5.2)onaperfolderbasis. OurPHPhostingpackageisthebestofferonthemarketithasthelowestpriceforthequalityand featuresitincludes.SignupnowforourProfessionalPHPHosting!
MySQLTutorial WhatisMySQL?MySQLisafreelyavailableopensourceRelationalDatabaseManagementSystem(RDBMS)thatuses StructuredQueryLanguage(SQL). SQListhemostpopularlanguageforadding,accessingandmanagingcontentinadatabase.Itismost notedforitsquickprocessing,provenreliability,easeandflexibilityofuse.MySQLisanessentialpartof almosteveryopensourcePHPapplication.GoodexamplesforPHP/MySQLbasedscriptsare phpBB, osCommerce,andJoomla.
OneofthemostimportantthingsaboutusingMySQListohaveaMySQLspecializedhost.Hereare someofthethingsSiteGroundisproudof: WehavelongexperienceinprovidingtechnicalsupportforMySQL basedwebsites.Thanks toitourserversareperfectlyoptimizedtoofferthebestoverallperformanceformost MySQLapplications. WeofferalotofFREEMySQLtoolsincludingCMSsystems,forums,galleries,blogs, shoppingcartsandmore. WesupportbothMySQL4andMySQL5.WeprovideunlimitedMySQLdatabases. OurMySQLhostingpackageisthebestofferonthemarketithasthelowestpriceforthequality andfeaturesitincludes.SignupnowforourProfessionalMySQLHosting!
MySQLTutorial:CreatingMySQLDatabaseandUserCheckouttheCreatingandModifyingMySQLDatabasesvideotutorial: CreatingandModifyingMySQLDatabasesVideoTutorial
CreatingaMySQLDatabaseDetailedTutorialCreatingaMySQLdatabasewithcPanel,whichisincludedinallofSiteGround'shostingplans,canbe easilyaccomplished.InordertocreateaMySQLdatabaseonyourhostingaccount,youneedtologin thecPanel.Thiscanbedonebyeitherusingthe GobuttonintheCustomerArea>MyAccount Accountsection:
orbyenteringthefollowingURLinyourwebbrowser: http://yourdomainname.com/cpanel http://cpanel.servername.comYoushouldreplace"yourdomainname.com"withyouractualdomainnameor"servername.com"withthehostname oftheSiteGroundserveronwhichyouraccountishosted.
OnceyouhaveloggedinthecPanel,youcanaccesstheMySQLmanagementscreenbyclickingonthe MySQLDatabasesbuttonasshownbelow.
InordertocreateanewdatabaseyouneedtoenterthedesirednameforthedatabaseintheNew
DatabasefieldandclickontheCreateDatabasebuttonasshownbelow:
Aconfirmationscreenwillbedisplayed,informingthatthedatabasehasbeensuccessfullycreated:
YoucanclickontheGoBackbuttontoreturntothedatabasemanagementscreen.TheMySQLdatabaseiscreatedwithyourusernameasprefix username_databasename andthisisthename youhavetouseforyourapplication.
CreatingaMySQLUsernameDetailedTutorialYoucancontinuewiththecreationofauserwhoshouldbeabletoconnecttothenewlycreated database.Tocreateauseryoujustneedtofillinthedesiredusernameandpasswordasshowninthe imagebelow:
ClickSubmittosaveyourMySQLusername.YoushouldalwaysbearinmindthatyourcPanelusernamewillbeaddedasaprefixtoalldatabasesand usernamesyoucreate.
AddingausertoaMySQLDatabaseDetailedTutorialOncethedatabaseandtheusernamearecreated,youcanaddcertainprivilegesfortheusertothe
database.Inordertodosoyoushouldselectthembothfromthecorrespondingdropdownmenus underAddUserToDatabaselabelandclickontheSubmitbutton:
Youwillberedirectedtoascreenwhereyouwillbepromptedtochoosethedesiredprivileges.Itis advisabletoselectAllPrivilegesandclickontheMakeChangesbutton:
UsingtheMySQLDatabaseWizardAllofthestepsabovecanbeaccomplishedusingtheMySQLDatabaseWizard.Clickonitandyouwill beguidedtroughallstepsthatyoushouldperforminordertosuccessfullycreateanewMySQL databaseandaddausertoit.
CheckouttheUsingMySQLDatabasesWizardvideotutorial: UsingMySQLDatabasesWizardVideoTutorial
MySQLTutorial:RemovingMySQLDatabaseandUser RemovingPrivilegedUserfromadatabase
Ifyouwouldliketoremoveaprivilegeduserfromadatabaseyoucaneasilydosobyclickingonthe correspondingbuttonnexttothedatabaseuserasshownbelow:
Aconfirmationmessagefortheremovalwillbedisplayed.Thismeansthattheusernamenolongerhas anyprivilegestothedatabase.
RemovingaMySQLdatabaseIfyouwouldlikeaMySQLdatabaseremovedthiscanbeeasilyaccomplishedbyclickingontheDelete DatabasebuttonundertheActionsarea:
Youwillgetaconfirmationscreenwhenthedatabaseisremoved.Notethatthisprocessisirreversibleandallthedatafromthisdatabasewillbelost.
RemovingaMySQLUserIfaMySQLusernameisnolongerneededyoucanremoveitbyclickingonthecorrespondingDelete buttonundertheCurrentUsersarea:
Againaconfirmationscreenwillbeshownuponsuccessfulremoval.
MySQLTutorial HowtoAccessandManageyourMySQLDatabasephpMyAdminTherearetwowaystoaccessandmanageyournewlycreateddatabase.Thefirstoneislocallythrough theWebbasedmanagerphpMyAdmin,whichisaccessedfromthecPanelDatabasessection.
Anewpage/tabofyourbrowserwillopenandthephpMyAdminwillloadasshownbelow:
CheckouthowtomanageMySQLdatabasethroughphpMyAdminvideotutorial: HowtoManageMySQLDatabaseThroughphpMyAdminVideoTutorial WithphpMyAdminyoucancreateaMySQLbackupandrestoreit. TheseconddatabasemanagementsolutionistoaddaMySQLaccesshostandallowaremoteMySQL connection.
MySQLTutorial MySQLExport:HowtobackupyourMySQLdatabase?Youcaneasilycreateadumpfile(export/backup)ofadatabaseusedbyyouraccount.Inordertodoso youshouldaccessthephpMyAdmintoolavailableinyourcPanel:
ThephpMyAdmintoolwillbeloadedshortly. YoucanselectthedatabasethatyouwouldliketobackupfromthedropdownmenucalledDatabase (locatedintheupperleftcornerofthepage).
AnewpagewillbeloadedinphpMyAdminshowingtheselecteddatabase.Inordertoproceedwiththe backupclickontheExporttab:
TheoptionsthatyoushouldselectapartfromthedefaultonesareSaveasfile(whichwillsavethefile locallytoyourcomputerinan.sqlformat)and AddDROPTABLE(whichwilladdthedroptable functionalityifthetablealreadyexistsinthedatabasebackup)asshownbelow:
ClickontheGobuttontostarttheexport/backupprocedureforyourdatabase:
Adownloadwindowwillpopuppromptingfortheexactplacewhereyouwouldliketosavethefileon yourlocalcomputer.Itispossiblethatthedownloadstartsautomatically.Thisdependsonyour browser'ssettings.
MySQLImport:HowtorestoreyourMySQLdatabasefromabackupTorestore(import)adatabasevia phpMyAdmin,firstchoosethedatabaseyou'llbeimportingdata into.Thiscanbedonefromthedropdownmenuontheleft.ThenclicktheImporttab:
Youhavetheoptionofimportingan.sqlfile.UsetheBrowsebuttontofinditonyourlocalcomputer. Notethatyouaregiventheoptiontochoosethecharactersetofthefilefromthedropdown menujust belowtheuploadbox.Ifyouarenotcertainaboutthecharactersetyourdatabaseisusingjustleavethe defaultone.
InordertostarttherestoreclickontheGobuttonatthebottomright.Anotificationwillbedisplayed uponasuccessfuldatabaseimport.
MySQLTutorial AddingMySQLaccesshostsYoucanallowaccesstoMySQLdatabasesfromanexternallocationbyaddingitsdomainnameorIP addresstothelistofhoststhatareallowedtoaccessyourdatabasesremotely.Additionally,ifyouwould liketomanageyourdatabaseusinganapplicationforremotedatabasemanagement,theIPaddress fromwhichtheconnectionisestablishedshouldbeaddedtothelistofallowedhosts. InordertoaddallowedhostsyoushouldaccessthetoolviacPanel>RemoteMySQL:
IntheHostfieldyoushouldenterthedesireddomainnameorIPaddress:
ClickontheAddhostbutton. Aconfirmationmessagewillinformthatthehostissuccessfullyadded.Nexttimeyouaccess Remote MySQLthenewlyaddedhostwillbelistedunderAccessHosts.
PHP/MySQLTutorialCreatingadatabasetableBeforeyoucandoanythingwithyourdatabase,youshouldcreateatableandsetthecorresponding fieldsinit. CreatingatableinPHPMyAdminissimple.Justtypethename,selectthenumberoffieldsandclickthe Gobutton.Youwillthenbetakentoasetupscreenwhereyoushouldcreatethefieldsforthedatabase.
Alternatively,youcanrunaMySQLquery,whichwillcreatethetable.Theformatis: CREATETABLEtablename( Fields ) Thefieldsaredefinedasfollows: fieldnametype(length)extrainfo, Thefieldsareseparatedbycomma. Forexample,ifyouwishtocreateatablecalledMemberswith3fieldsinitFirstName,LastNameand Age,youshouldexecutethefollowingquery: CREATETABLEMembers ( FirstNamevarchar(15), LastNamevarchar(15), Ageint ) Moreinformationonhowtoconnecttothedatabaseandhowtoqueryitcanbefoundinthefollowing tutorials: Step2:Connecttothedatabase Step3:Querythedatabase Step4:Displaytabledata Step5:Selectindividualrecords
PHP/MySQLTutorialPHPMySQLConnection HowtoConnecttoYourDatabaseStep2:YoushouldestablishaconnectiontotheMySQLdatabase.Thisisanextremelyimportant stepbecauseifyourscriptcannotconnecttoitsdatabase,yourqueriestothedatabasewillfail. Agoodpracticewhenusingdatabasesistosettheusername,thepasswordandthedatabasename valuesatthebeginningofthescriptcode.Ifyouneedtochangethemlater,itwillbeaneasytask. $username="your_username" $password="your_password" $database="your_database" Youshouldreplace"your_username","your_password"and"your_database"withtheMySQLusername, passwordanddatabasethatwillbeusedbyyourscript. Atthispointyoumaybewonderingifitisasecurityrisktokeepyourpasswordinthefile.Youdon't needtoworrybecausethePHPsourcecodeisprocessedbytheserverbeforebeingsenttothe browser.Sothevisitorwillnotseethescript'scodeinthepagesource. NextyoushouldconnectyourPHPscripttothedatabase.Thiscanbedonewiththe mysql_connect PHPfunction: mysql_connect(localhost,$username,$password) ThislinetellsPHPtoconnecttotheMySQLdatabaseserverat'localhost'(localhostistheMySQLserver whichusuallyrunsonthesamephysicalserverasyourscript).
Aftertheconnectionisestablishedyoushouldselectthedatabaseyouwishtouse.Thisshouldbea databasetowhichyourusernamehasaccessto.Thiscanbecompletedthroughthefollowing command: @mysql_select_db($database)ordie("Unabletoselectdatabase") IttellsPHPtoselectthedatabasestoredinthevariable$database(inourcaseitwillselectthedatabase "your_database").Ifthescriptcannotconnectitwillstopexecutingandwillshowtheerrormessage: Unabletoselectdatabase The'ordie'partisusefulasitprovidesdebuggingfunctionality.However,itisnotessential. AnotherimportantPHPfunctionis: mysql_close() Thisisaveryimportantfunctionasitclosestheconnectiontothedatabaseserver.Yourscriptwillstill runifyoudonotincludethisfunction.AndtoomanyopenMySQLconnectionscancauseproblemsfor youraccount.ThisitisagoodpracticetoclosetheMySQLconnectiononceallthequeriesareexecuted. Youhaveconnectedtotheserverandselectedthedatabaseyouwanttoworkwith.Youcanstart queryingthedatabasenow. Step3:Querythedatabase Step4:Displaytabledata Step5:Selectindividualrecords
PHP/MySQLTutorialPHPMySQLConnection HowtoQuerytheDatabaseStep3:Thereareatleasttwowaystoqueryadatabase.Oneisto enterthecommandin PHP. Anotherwayistodefinethecommandasavariable. Inthispartofthetutorialwewillshowthefirstway.Thecommandwilllooklikethis: mysql_query($query) Thecommandcanberepeatedoverandoveragaininthesourcecode.Allyouneedtodoistochange thevariable. HereisthecompletecodethatshouldbeusedtocreateaMySQLtableinPHP: Enteryourdatabase,MySQLusernameandMySQLpasswordintheappropriatepositionsonthefirst threelinesabove. Thenextqueryshouldfillinthetable.Hereisasampleone: $query="INSERTINTOtablenameVALUES ('','$field1name','$field2name','$field3name','$field4name','$field5name')" Youcan'tinsertmorevaluesthanthenumberoffieldsyouhavecreatedwiththefirstquery. Step4:Displaytabledata Step5:Selectindividualrecords
PHP/MySQLTutorialPHPMySQLConnection
HowtoDisplayMySQLTableData?Step4:Afteryouhavecreatedthetableandenteredthedata,youwillprobablyneedtodisplay
it.ThisisusuallydoneusingbasicHTMLcodewhichinvokesaPHPscript.
Wewillstarttheexamplefromthebeginning.Wewillpopulateanewdatabasetablewithdata.
ThefollowingHTMLcodewillcollectthedatafromthetextboxesandpassittothePHPscript:
Value1:
Value2:
Value3:
Value4:
Value5:
ThenextthingyouneedisanewPHPscriptwhichwillenterthedatainthedatabase.