+ All Categories
Home > Documents > SiteGround Php-MySQL Tutorial

SiteGround Php-MySQL Tutorial

Date post: 10-Apr-2015
Category:
Author: sitegroundcom-inc
View: 5,101 times
Download: 0 times
Share this document with a friend
Description:
The PHP/MySQL Tutorial will help you learn more about PHP and MySQL and how to use them. Here you will learn how to create MySQL database and user, how to manage MySQL database, how to connect MySQL with PHP, how to execute PHP commands on the server and more.
Embed Size (px)
of 17 /17
SiteGround Tutorials PHP/MySQL Tutorial: How to Use PHP and MySQL? PHP is the most popular scripting language for web development. It is free, open source and serverside (the code is executed on the server). MySQL is a Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is also free and open source. The combination of PHP and MySQL gives unmet options to create just about any kind of website from small contact form to large corporate portal. This PHP/MySQL tutorial is part of the rich collection of web hosting tutorials which SiteGround experts have prepared for you. Find out how to start your website, how to promote it, how to deal with cPanel, webmail and FTP. PHP/MySQL Tutorial includes: A short introduction on what is PHP; What is MySQL and what are its benefits; Creating MySQL database and user useful information for installing a PHP/MySQL script on your website; Removing MySQL database and user ; Learn how to manage MySQL databases with phpMyAdmin MySQL Backup/Restore functionality and how to use MySQL Access Host ; Creating a database table ; Connecting to the database; Querying the database ; Displaying table data in HTML; Selecting individual records ; How to use the MySQL GUI tools to backup, restore and execute queries on your database; Information about Zend Optimizer ; Learn how to install Pear modules . PHP Tutorial What is PHP? PHP was at first created as a simple scripting platform called "Personal Home Page". Nowadays PHP (the short for Hypertext Preprocessor) is an alternative of Microsoft's Active Server Pages (ASP) technology. PHP is an open source serverside language which is used for creating dynamic web pages. It can be embedded into HTML. PHP is usually used in conjunction with a MySQL database on Linux/UNIX web servers. It is probably the most popular scripting language. PHP is a widelyused generalpurpose scripting language and interpreter that is freely available. A full explanation of all the PHP tags, complete user manual and lots of tutorials can be found on the PHP's official page . One of the most important things about using PHP is to have a PHP specialized host. Here are some of the things we at SiteGround are proud of: We have long experience in providing technical support for PHPbased web sites. Thanks to it our servers are perfectly optimized to offer the best overall performance for most PHP applications. We offer a lot of FREE PHP tools including CMS systems, forums, galleries, blogs, shopping carts and more. We provide several versions of PHP (PHP 5.0, PHP 5.1, PHP 5.2) on a perfolder basis. Our PHP hosting package is the best offer on the market it has the lowest price for the quality and features it includes. Sign up now for our Professional PHP Hosting ! MySQL Tutorial What is MySQL? MySQL is a freely available open source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease and flexibility of use. MySQL is an essential part of almost every open source PHP application. Good examples for PHP/MySQLbased scripts are phpBB , osCommerce , and Joomla .
Transcript

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.


Recommended