Sunteți pe pagina 1din 94

PHP

LearnPHP&mySQLWithUltimateZerotoHero

ProgrammingCrashCourseforBeginners

PaulMadoff

ZerotoHero

Introduction

TableofContents

Chapter1:WhyUseaDatabaseforYourWebsite

Chapter2:IntroductiontoPHP

Chapter3:SettingUptheDatabase

Chapter4:InterestingandUsefulTipsforPHPLanguage

Chapter5:DisplayingData

Chapter6:MoreOutput

Chapter7:SingleRecordsandErrorTrapping

Chapter8:UpdatingandDeleting

Chapter9:FinishingtheScript

Chapter10:CommonPHPandmySQLDevelopmentMistakestoAvoid

Conclusion

CheckOutOtherBooksby‘ZEROtoHERO’

*Bonus*:FREEPHPCourse!

Introduction

Wewanttothankyouandcongratulateyoufordownloadingthebook,“PHP:LearnPHP&MySQL

withUltimateZerotoHeroProgrammingCrashCourseforBeginners”.

ThisbookcontainsprovenstepsandstrategiesonhowtousePHPwithMySQLtointeractwithyour

websitedatabases.

ThroughoutthiseBook,youwilllearnthebasicsofusingPHPandMySQLintandem.Youwillfinda

lotofexamplesthatcanhelpspeedupyourlearningprocess.

Forone,youwilllearnhowtocreateaninternet-basedcontactmanagementprogramthatyoucanuseto

storenames,addresses,andothercontactinfo.Youwilllearnhowtoupdaterecordsandsearchthrough

thedatabase.Youcanevensendemails(notforpurposesofspammingorsendingunsolicitedemails)to

thecontactsinthedatabase.Onceyouhavecreatedthissystem,youshouldbeequippedtogoonand

createvirtuallyanytypeofdatabase-enabledwebsitethatyouwant.

YouwillalsolearnthecommonmistakesthatPHPandMySQLdevelopersmakesoyoucanavoidthem

onceyoustartwritingyourownscripts.

Thanksagainfordownloadingthisbook,Ihopeyouenjoyit!

Chapter1:WhyUseaDatabaseforYourWebsite

AlotofpeopleaspiretolearnscriptinglanguagessuchasPHPprimarilybecauseofthecapabilityofthe

saidlanguagestointeractwithdatabases.ThisbookwillteachyouhowyoucanusePHPwithMySQL

tostoreinformationincyberspace,andincorporatethesameinyourwebsite.However,beforeyoucan

learntoworkwithMySQLdatabases,youneedtohaveabasicknowledgeinusingPHP.Thenext

chapterisdevotedtothebasicsofPHP,incaseyouarenotyetfamiliarwiththelanguage.Youmayskip

itifyoufeelconfidentaboutyourPHPprogrammingskilllevel.

UsingaDatabaseforYourWebsite

Youwillbesurprisedthatyourwebsitecanbenefitalotfromusingadatabase.Thereisawidearrayof

thingsthatinteractingawebsitewithadatabasecando.Itcanbeassimpleasdisplayingalistto

runningyourentirewebsitefromadatabase.FollowingaresomeexamplesofapplicationswherePHP

canbeusedtogetherwithMySQL:

BannerRotation–Onawebsitethatmaintainsnumerousbanners,aPHPscriptisusedtocallabanner

atrandomtodisplaytothesitevisitor.Thescriptalsomonitorsthenumberoftimesaparticularbanner

isviewed.Withsomeminorediting,itcanalsobeusedtotrackclicks.Allyouhavetodotoadd,

replace,oreditthebannersistomodifythedatabaseandthePHPscriptwillthenbeabletoselectthe

correctbannersforthevariouspagesonthewebsite.

Databases–Obviously,thebestexampleisawebsitethatgetsalltheinformationitprovidesfroma

databaselikeScriptAvenue.Onlyafewscriptsisneededtorunthesite.Thesescriptsareusedtoobtain

alltheinformationfromabigdatabase.Onescriptcanaccessthevariousscriptcategoriesjustby

modifyingtheURLtoaccessanotherareaofthedatabase.

Forums–PHPandMySQLareusedtorunahugenumberofmessageboardsorforumsonthenetas

thisisproventobemoreefficientthanothermethodstocreateapageforeverymessage.Itlikewise

offersalotofoptions.Justbychangingonescript,everypageintheforumisupdated.

Websites – If your website is sizeable, and you want some changes in the design, updating and uploadingallthepagescantakeaconsiderableamountoftime.ByusingPHPandMySQL,allitwould takemaybejustaPHPscriptortwothatwillaccessaMySQLdatabaseandgetalltheinformation neededtoupdatethepages.Simplyput,updatinganentirewebsite’sdesignmayonlyrequirechanging onepage.

WhatYouNeed

Basically,thereareonlythreethingsthatyouneedinordertorunPHPscriptsthatwillaccessMySQL

databases.

Webserver–Thiscaneitherbeonawebhostoryourowncomputer.Althoughmostwebserverswould

workwithPHP/MySQL,Apacheishighlyrecommendedforuse.Itisalsofree.

InstalledPHPontheServer–IfyourserverdoesnothavePHPpre-installed,youcandownloaditfrom

PHP.netforfree,andinstallit;oryoucanrequestyourwebhosttodotheinstallationforyou.Ifyoudo

notknowhowtocheckifPHPisalreadyinstalledinyourserver,youcanlearnawaytocheckitlaterin

thischapter.

InstalledMySQL–Thisisthedatabasesoftware.Althoughyoucanuseotherdatabasetypessuchas

OracleandSQL,thistutorialwillonlyfocusonMySQL.Mostofthecommandsthatwillbeusedhere

willworkonSQLdatabases,anyway.MySQLisfreetodownloadformtheMySQLwebsite.Ifyou’re

notsurewhetheryoualreadyhavethedatabasesoftwareinstalled,again,youwilllearnawaytocheck

itlater.

Ifyoucan’tinstallPHP/MySQLoryourwebhostdoesn’tallowit,itisbesttofindawebhostthat

supportsthesoftware.

HowtoTestifPHPandMySQLAreAlreadyInstalled

YoucantestbothPHPandMySQLbyopeningatexteditorandtypingin:

<?

Phpinfo()

?>

andsavingitasphpinfo.php.

Next,uploadthefiletoyourwebspaceandviewitinyourbrowser.IfPHPisinstalled,ahugepage

containingallyourPHPinstallationdetailswillappear.Scrolldownthroughalltheinformationandyou

shouldfindasectiononMySQLthatwilltellyouwhetheritisinstalledornot.

ManagingYourDatabases

WhilealldatabaseadminoptionscanbeperformedusingPHPscripts,itishighlyrecommendedthat

youinstallacopyofPHPMyAdminonyourwebserver.Itincludesanexcellentsetoffreescriptsthat

offersanadminoptionforyouMySQLdatabase/s.Youcanadd,edit,remove,view,andbackupyour

databasewithit.Itisparticularlyusefulwhentroubleshootingyourdatabase.

Chapter2:IntroductiontoPHP

PHPBasics

Itwasnotsolongagowhenonlyafewpeopleattemptedtomasterorevenjusttoperformscriptingon

thenet.Recently,however,whenthenumberofpeoplewhoarebuildingtheirownwebsiteshasgrown

byleapsandbounds,learningandusingscriptinglanguageshavebecomeofprimaryimportance.

Becauseofthis,easiertolearnscriptinglanguageshavebecomeavailable.Amongtheselanguages,

PHPisconsideredasoneofthemostpowerfulandeasiesttouse.

WhatIsPHP?

PHPis the acronym for Hypertext Preprocessor, and is categorized as a server-side programming language.ThissimplymeansthatthescriptscreatedusingPHParerunonyourwebserver,andnoton thevisitor’sbrowser.Thisway,therearenocompatibilityissuestoworryabout.Comparedtolanguages likeJavaandPeri(CGI),PHPisnewer,butitisfastbecomingamongthemostpopularscripting languagesonthenet.

WhyOptforPHP?

Now,youmaybethinkingoutloudwhyintheworldyoushouldlearnascriptinglanguage,andwhy

PHPamongallothers.First,learning,orattheveryleast,understandingascriptinglanguagehelpsopen

upalotofpossibilitiesforyourwebsite.Whileyoucaneasilydownloadready-madescriptsonline,

theseareusuallyincorporatedwithadsfortheauthor.Insomecases,theydonotdelivertheexact

resultsthatyouwant.Ifyouhaveabasicknowledgeofascriptinglanguage,youcancreateyourownor

editpre-madescriptseasily.

Includingscriptsonyoursite,givesyoutheflexibilitytoaddnumerousinteractivefeatureslikeguest

books,feedbackforms,counters,messageboards,andeventhemoreadvancedfeaturessuchascontent

managementsystems,portalsystems,andadvertisingmanagers,amongothers.Withalltheseuseful

featuresonyoursite,itwillexudeamoreprofessionaldemeanor.Inaddition,ifyouintendtoworkor

getprojectsinthewebsitedevelopmentindustry,knowledgeinascriptinglanguagewillgiveyoua

decidedadvantage.

WhatYouNeed

Aspreviouslymentioned,PHPiscategorizedasaserver-sidescriptinglanguage.Assuch,although

usersdonothavetoinstalltheprogrammingsoftwareontheircomputer,PHPmustbeinstalledonyour

webhost,soitisimportanttomakesurethatitispartofthepackagethatyousignupfor.Youcancheck

ifyourserveralreadyhasPHPinstalledbyusingthemethodgivenintheprecedingchapter.

WritingPHPScripts

Prettysoon,youwilllearnthatwritingPHPscriptsisquitesimple.Youdonotneedtobuyorinstallany

specialsoftware.AllyouneedisatexteditorsuchasNotepadinWindows.Justruntheeditorandyou

aregoodtogo.YoucanimmediatelycreateyourveryfirstPHPscript.

DeclaringPHP

ScriptswritteninPHParealwaysenclosedinapairofPHPtags.Thiswillletyourserverknowthatthe

informationtoparseasPHPisbetweenthetags.Therearethreedifferentformsofwritingscripts,and

theseare:

<?

InsertPHPcodehere

?>

<?php

InsertPHPcodehere

php?>

<scriptlanguage="php">

InsertPHPcodehere

</script>

Allthesescriptformsworkexactlyinthesamemanner,butforthisparticularPHP/MySQLtutorialfor

beginners,thefirstoptionwillbeused.Thereisnoearth-shakingreasonforthis,exceptthattheauthor

ismostcomfortablewithit.Youcanuseanyformthatsuitsyou,however.Justmakesurethatyoustart

andendyourcodeswithmatchingtags.Forinstance,youcannotstartacodewith<?phpandthenendit

witha</script>.

YourVeryFirstPHPScript

Now,it’stimetowriteyourfirstPHPscript.Letusstartwithsomethingverybasic.Whatitwilldois

simplytoprintoutalltheinfoaboutPHPonyourwebserver.Openyourtexteditorandtypethe

followingcode:

<?

phpinfo();

?>

Youwillnoticethatthescriptconsistsofjustonelineofcode.“phpinfo”isastandardfunctioninPHP

thatwillcommandtheservertohaveastandardinformationtableprintedouttocontainpertinent

informationontheserver’ssetup.

Anotherthingthatyoushouldtakenoteofintheexampleabove,whichisveryimportant,isthata

semicolonendsthelineofcode.Youshouldnotforgettoendyourlineswithasemicolonasmissingit

willresulttoanerror.Thisistrueformostotherprogrammingandscriptinglanguages.

FinishingandTestingYourScripts

Atthispoint,youhavealreadyfinishedyourscript.Thenextstepistosaveitwiththefilename

phpinfo.php,andthenuploadittoyourwebserverintheusualway.Usingyourwebbrowser,gotothe

script’sURL.Youknowthatyourscriptworked,andifyouhavePHPinstalledintheserverifyougeta

fullpagecontainingalltheinformationonthePHPinstalledonyourserver.

Ifablankpageappearsinstead,thisisanindicationthatyourscriptdoesnotwork.Inthiscase,you

mayhavemistypedthecode.Itisalsopossible,althoughitishighlyunlikely,thatyourserverdoesnot

supportthefunction;highlyunlikelybecausetheauthorhasyettoencounteraserverthatdoesn’t

supportit.

YouwillknowthatyourserverdoesnothaveaninstalledPHPif,insteadofdisplayingapage,youare

givenamessagetodownloadthefile.Whenthishappens,it’seithertimetolookforawebhostor

requestyourcurrenthostingserviceprovidertoinstallPHP.

Keepthescriptasyoumayneeditforfuturereference.

Tosummarizewhatwehavediscussedsofar:youhavelearnedsomeofPHP’sadvantagesasascripting

languageandyouhavelearnedhowtocheckifitisinstalledinyourserver.Inthesucceedingsections

ofthischapter,youwilllearnhowtodisplayinformationinthebrowseraswellashowyoucanuse

variablesinyourscriptstoholdinformation.

PrintingText

ItisactuallyquitesimpletoprintoutthetextinyourPHPscripts.Likealmosteverythingelsethatyou

havelearned,andwilllearn,aboutthelanguage,youcandothingsinvariousdifferentways.Forthis

section,wewillmainlybeusing“print.”Thecommandprintallowsyoutooutputvariables,text,ora

combinationofbothsotheywillbedisplayedonthecomputerscreen.

Printisusedinthefollowingmanner:

print("Higuys!");

Inthelineofcodeabove,thecommandprintgivestheinstructionsonwhattodo.Thebracketscontain

theinformationorwordstobeprinted.Becausetheintentionistooutputtext,thetextitislikewise

enclosedinquotationmarks;AND,notethatlikealmosteveryotherlinesofcodeinPHPscripts,a

semicolonisusedtoendtheline.

Tocompletethescript,youhavetoencloseitinthestandardPHPtags,thusitshouldappearthisway:

<?

print("Higuys!");

?>

Runningthecodewilldisplay

Higuys!

onthescreen.

Variables

Likeinmostotherprogramming/scriptinglanguages,youcandefinevariablesinPHP,whichoffers

severaltypesofvariables.“Stringisthemostcommontypeofvariable.Itcanholdnumbersandtext.

Stringsalwaysfollowa$sign.HereishowyouassigntextvaluestoastringinaPHPscript:

$welcome_text="Hiandwelcometoourwebsite.";

Youshouldeasilyunderstandthislineofcodebynow.Thetextenclosedinquotationmarksisassigned

tothestring.Thereareafewrulesaboutusingstringsthatyoushouldkeepinmind,though.

Forone,stringsarecase-sensitive;thus,$Welcome_Textand$welcome_textaretwodifferentstrings.

Althoughstringsmaycontainnumbers,letters,andunderscores,theycanonlybeginwithletters,not

numbersorunderscores.Also,whenyouassignanumbertoastring,youneednotencloseitinquotes.

Forexample:

$user_id=754

Thiscodeisacceptable.

OutputtingVariables

Thesamecodeusedwhendisplayingtextonthescreenisalsousedwhendisplayingvariables,though

inaslightlydifferentformat.Thefollowingscriptwilldisplaytheinformationstoredinthevariable.

<?

$welcome_text="Hiandwelcometoourwebsite.";

print($welcome_text);

?>

Notethattheonlysignificantdifferenceisthatquotationmarksarenotnecessarywhenprintinga

variable.

FormattingYourText

YoumaybethinkingthattheoutputsfromthePHPscriptsyouhavethusfarcreatedareboring.Well,

youareright.Afterall,allprogramsyouhavecreatedjustrequireoutputusingthedefaultfontofyour

browser.BecausePHPis,asyouhavelearnedbefore,aserver-sidelanguage,thecodehasalreadybeen

executedevenbeforeitgetstothebrowser.Onlytheoutputfromthecodeissent.

Intheexampleabove,thebrowserwillonlyreceive:

Hiandwelcometoourwebsite.

Youcanmakethingsabitinteresting,though,byusingHTMLtoformatyourtext,meaningyoucan

incorporatestandardHTMLmarkupinyourcodesandstrings.Thereisoneproblem,though.Sincealot

ofHTMLtagsrequiretheuseofthe“sign,itmayhaveaconflictwiththequotationmarksyouusein

printingyourtext.Youmustthereforemakeitclearinthescriptwhatquotestouse(thoseusedto

enclosetheoutput)andwhichonestoignore(thoseintheHTMLcode.)

Inthefollowingexample,we’llchangethetextfonttoVerdanainred.Followingisthecodethatis

normallyused.

<fontface="Verdana"color="#FF0000">

</font>

Notethatthecodehasfourquotationmarkswhichwillconfusethescript.Toresolvetheissue,usea

backslashbeforeeveryquotationmarktopromptthePHPscripttoignorethem.Thecodewouldthus

appearas:

<fontface=\"Verdana\"color=\"#FF0000\">

</font>

Now,youcanincorporatethecodeinyourprintstatement

print("<fontface=\"Verdana\"color\"#FF0000\">Hiandwelcometoourwebsite.</font>");

Thebrowserwillthendisplay:

Hiandwelcometoourwebsite.

Thisisbecausethebrowseronlyreceivedthecode:

<fontface="Verdana"color="#FF0000">Hiandwelcometoourwebsite.</font>

Don’tworryif,atthispoint,youfindoutputtingHTMLcodedifficult.Later,youwilllearnanotherway

todothisthatisalittlebiteasier.

Chapter3:SettingUptheDatabase

Beforeyoucanactuallybeginbuildingscriptsforyourdatabase,youneedtohaveadatabasefirst whereyoucanstoreinformationinto,andread/accessfrom.Inthischapter,youwilllearnhowtocreate a MySQLdatabase and make it ready for the data. You will also learn how to create a contacts managementdatabase.

DatabaseConstruction

DatabasesinMySQLuseastandardsetup.Thisincludesadatabasethatcontainstables.Eachtableis

separateanddistinct,andismadeupofrecords.Records,inturn,arecomprisedoffields.

LoginsandDatabases

TheMySQLsetupprocessmaydifferbetweenhosts.However,itwillalwaysrequirehavingadatabase

name,username,andpassword.Alltheseinformationareneededwhenloggingintothedatabase.

If you have installed PHPMyAdmin or something similar, you can simply login to it with your usernameandpassword.Otherwise,youmustcreateallyourdatabaseadminscriptsusingPHP.

CreatingaTable

Withoutatable,youcannotdoanythingwithyourdatabase.Atableistheparticularsectionofyour

databasewhererelatedinformationisstored.Whencreatingatable,youwillsetupthevariousfields

thatthetablewilluse.Awell-designedandconstructeddatabaseisimportantasjustonemaybe

sufficienttoprovidenearlyallofthewebsitesdataneeds.

WithPHPMyAdmin,creatingtablesiseasyandsimple.Allyouhavetodoistypethetablename,

choosethenumberoffields,andpressthebutton.Thesetupscreenwillthenappearwhereyouneedto

createallthefieldsthatthedatabasewilluse.Ifyou’reusingPHPscriptsincreatingyourdatabase,

everything–theentirecreationandsetupprocess–canbeperformedusingjustonecommand.

Fields

ThereisawideselectionoffieldsandattributesprovidedbyMySQL,andthesewillbediscussedinthis

section.

FieldType

Description

TINYINT

SmallIntegerNumber

SMALLINT

SmallIntegerNum.

MEDIUMINT

IntegerNum.

INT

IntegerNum.

TEXT

Text

Therearemanyotheravailablefieldsthatyoucanuse.Youcansearchonlineforalltheallowedfield

types.

CreatingaTableUsingPHP

CreatingatableisabitmoredifficultwithPHPcomparedtoMySQL.Followingistheacceptedformat:

CREATETABLEtablename{

Fields

}

Youdefinethefieldsthisway:

fieldnametype(length)extrainfo,

Remembernottoputacommaafterthelastfieldyouenter.Moreexampleswillbegiveninthe

succeedingchapters.

TheContactsDatabase

Thistypeofdatabasewillstorethecontactinformationofthepeopleyouincludeinyourdatabase.You

canedittheinformationanditcanbeviewedonthenet.Followingaresomesamplefieldsyoucanuse.

Name

Type

Length

Description

id

INT

8

Uniqueidentifierforeveryrecord

first

VARCHAR

16

Person'sfirstname

last

VARCHAR

16

Person'slastname

phone

VARCHAR

18

Person'stelephonenumber

fax

VARCHAR

18

person'sfaxnumber

mobile

VARCHAR

18

person'smobilephonenumber

email

VARCHAR

25

person'se-mailaddress

web

VARCHAR

25

person'swebaddress

Ifyounotice,VARCHARfieldsareusedforfax/phonenumbersalthoughtheymaybemadeupof numbers.AlthoughyoucanuseINTfields,usingVARCHARwillallowyoutoinputspacesanddashes

inthefield,andtextualnumbers(like1800-CORPORATION).Thereshouldbenoproblemssinceyou

won’tbeinitiatingcallsfromtheweb.

Notethattheidfieldwillbesettoauto_increment(underextrainPHPMyAdmin),anditwillbeusedas thePRIMARY,UNIQUE,andINDEXfield.Thismeansthefieldmustbeuniquesinceitwillbethe primary and index field or field identifier. When set to auto_increment, the next number will be assignedwheneveranewrecordisadded,evenifyoudon’tspecifyanid.

WhenyouareusingamanagementprogramsuchasPHPMyAdmin,youcanstartcreatingatableyou

canname“contacts.”

CreatingaTableinPHP

UsethefollowingcodetocreatethetableinPHP.Partsofthecodethatwehavenotcoveredyetwillbe

explainedlaterinthischapter.

explainedlaterinthischapter.

Inputthedatabase,YourMySQLusernameandpasswordintheproperpositionsinthefirst3linesof

thecodeabove.

Chapter4:InterestingandUsefulTipsforPHPLanguage

Inthepreviouschapters,youhavecreatedthedatabasethatyouwilluseforthisbook.Inthesucceeding

sections,youwilllearnhowtomakeyourdatabasemoreusefulbyinsertingsomeinformationthatyou

willneed.

ConnectingtotheDatabase

Beforeyoucanproceed,youfirsthavetoconnecttoyourMySQLdatabase,whichisveryimportant

becauseifyouaren’tconnected,thedatabasewillnotexecutethecommandsyouissue.Agoodpractice

whenusingadatabaseistoprovidethedatabasename,yourusername,andpasswordfirst.Thisway,

whenyouneedtomakechangestoanyoftheminthefuture,youwillonlyneedtomodifytheaffected

line.Thisishowyoudoit:

whenyouneedtomakechangestoanyoftheminthefuture,youwillonlyneedtomodifytheaffected line.Thisishowyoudoit:

Ifyouareworriedaboutsecurityifyoukeepyouruserinfointhefile,thereisnothingtoworryabout.It

isgenerallysafe.TheuserwillnotbeabletoseethesourcecodesincePHPprocessesthecodebeforeit

sendstheinstructionstothebrowser.

Thenextstepistogivethecommandthatwillinitiateconnectiontothedatabase:

mysql_connect(localhost,$username,$password);

ThelineofcodeinstructsPHPtoconnecttothe‘localhost’databaseserver.Thismeanstheserveryou

siteisrunningonusesone,andunlessyourwebhostsaysotherwise,uselocalhost.Now,ifyouare

providedwithaspecificserveraddresslikesql.myserver.com,useitinsteadoflocalhost.Don’tforget

toencloseitinquotes.Thisishowyourcodeshouldappear:

$username="username";

$password="password";

$database="sql.myserver.com";

Before,weproceedtoworkingwiththedatabase,youhavetolearnonemorecommandwhichis:

mysql_close();

Thiscommandisveryimportantbecauseitclosesyourconnectiontoyourdatabaseserver.Although

yourscriptwillstillbeexecutedevenwithouttheclosecommand,youmayencounterproblemswith

thewebhost,especiallyiftherearenumerousopenMySQLconnections.Itisthereforesoundpracticeto

makesurethatthislineisalwaysincludedonceyouaredonegivingallthecommandstotheparticular

databaseyouareusing.Thiswillhelpensurethattheserverwillrunwell.

SelectingtheDatabase

Onceyouhaveestablishedconnectionwiththedatabaseserver,thenextstepistoselectthedatabase

youintendtouse.Makesurethatyourusernamehasaccesstothisparticulardatabase.Theappropriate

commandis:

@mysql_select_db($database)ordie("Unabletoselectdatabase");

This command instructs PHP to connect to a database stored in your previously set up variable $database.Ifnoconnectioncanbeestablished,executionofthescriptwillbestoppedandthesystem willoutputthemessage:

Unabletoselectdatabase

Inthepreviouscodewewrote,the“ordie”portionisidealtohavebecauseitprovidessomesemblance

oferrorcontrol,althoughitisnotreallyessential.

ExecutingCommands

Afterconnectingtotheserverandselectingthedatabaseyouwishtoworkwith,youcannowstart

executingcommandsonthedatabaseserver.

Youcanexecutecommandsintwoways.FirstistosimplyinputthecommandinPHP.Youcanusethis

iftherearenoexpectedresultsfromtheoperation.Secondishavethecommanddefinedasavariable.

Doingthiswillsetthevariableupwiththeexpectedresultsoftheoperation.

Forpurposesofthistutorial,wewillbeusingthefirstmethodbecausewedonotexpectanyresponse

fromtheserver.Here’showthecommandshouldbewritten:

mysql_query($query);

Thiscommandformisveryusefulsinceyoucanrepeatitagainandagainwithouthavingtolearnnew

commands.Allyouhavetodoistoreplacethevariable.

InsertingData

Forthissection,wewillgobacktothecontactsdatabasewecreatedearlier.Letusaddthefirstbitof

informationtothedatabase:

First:Jim Last:Doe

Phone:01134567899

Mobile:00111222333

Fax:02234567811

E-mail:jimdoe@abcdenet.com

Thesewillallbeincludedinasinglecommand:

$query = "INSERT INTO contacts VALUES ('','Jim','Doe','01134 567899','00111 222333','02234

567811','jimdoe@gabcdenet.com','http://www.abcdenet.com')";

Initially,youmayfindalltheseconfusing.Don’tworry,thoughaswewillbediscussingeverythingin

thissection.

The

$query=

isincludedaswewanttoassignvaluetothevariable$query.

Next,thepartthatsays

INSERTINTOcontactsVALUES

isveryeasytounderstand.ItsimplyinstructsPHPtoinsertvaluesenclosedinparenthesisintothe

contactstable.Theitemsintheparenthesisaretheinformationtoadd.Thefieldsareusedinorder,and

theinformationbetweenquoteswillbeinserted.Forinstance,

Jim

willbeinsertedintothefieldnamed‘first’whichisthe2 nd fieldinthetable.

Noticethatthereisnovalueinsertedintothe1 st fieldinthetable,id.Rememberthatthisfieldactsasan indexfield,meaningnotworecordsinthetablewillbearthesameid.Thus,whenthedatabasewas created, the id filed was set to auto_increment. Once no value is assigned to it, the record will automaticallyassumethenextnumberintheseries.Unlessastartingnumberisspecified,thefirst

recordwillgetid1.

Inthenextchapter,wewilldiscussthecommandstoexecutewhenusingvariablesandformstoadd

information,anddisplayinginformationinthedatabase.

Chapter5:DisplayingData

Previously,youhavesetupadatabasetableandaddedsomeinfointoit.Now,letuslearnhowyoucan

generatetheinputpagesyourtable,aswellashowyoucandisplaytheentirecontent.

HTMLInput

UsingHTMLtoinputdataisverysimilartoinsertingdatausingPHPscripts.Theadvantage,thoughof

usingHTMListhatyoudon’thavetomodifythecodeforeverybitofinformationyouwishtoinput.

Youcanlikewiseallowuserstoentertheirowndata.

ThecodebelowwilldisplayanHTMLpagecontainingtextboxeswhereappropriatedetailsmustbe

entered:

Thispagecanbeformattedandyoucanapplyotherchangestoit.Whatwehavecreatedisasimple

Thispagecanbeformattedandyoucanapplyotherchangestoit.Whatwehavecreatedisasimple

formjusttogetyougoing.Youwillnexthavetomodifythescriptwepreviouslywrote.Insteadofinfo

toinputinthedatabase,wewillnowusevariables.

toinputinthedatabase,wewillnowusevariables.

Savethescriptasinsert.php.Thisway,theHTMLformcancallit.Itwillworkbecause,ratherthan

havingthedataenteredlocally,thesamewillbeinputtedtotheformandheldinvariablesthatare

passedontothePHP.

Youcanlikewiseopttoaddamessagetothescripttoconfirmthedatainput.Youcanbrushuponyour

PHPskillsifyoudon’tknowyethowtodoit,asthisrequiressomebasicPHPcoding.

OutputtingData

Yourtableshouldbynowcontainatleastsinglerecord,maybealotmore,andyouareprobablyitching

tolearnhowtooutputtheinformationusingPHP.Beforeproceeding,however,youmustbefamiliar

withhowloopsworkinPHPastheseareusedinthisbooktooutputdata.

Theveryfirstcommandyouneedtoissueisaquerythatshouldlooklikethis:

SELECT*FROMcontacts

ThisbasicMySQLcommandtellsPHPtoselectallrecordsinthetablenamedcontacts.Becausewe

expectanoutputwhenthecommandisexecuted,avariablemustbeassociatedtotheresults:

Forthisparticularcase,theentiredatabasecontentisnowstoredinthespecialarraythatisnamed

Forthisparticularcase,theentiredatabasecontentisnowstoredinthespecialarraythatisnamed

$result.Inordertooutputthedata,youmustfirstassigneveryitemasaseparatevariable.Thisisatw0-

stageprocessthatinvolvescountingrowsandsettinguptheloop.

CountingRows

Justbeforegoingthroughtheentiredataintheresultvariable,youfirsthavetoidentifytheexact

numberofrowspresent.Sure,youcanalwaysincludethisinthecode,butthisisn’tarecommended

solutionbecauseyouwouldhavetochangetheentirescripteachtimeanewrowiscreatedoradded.

Youcanusethefollowingcommand,instead:

$num=mysql_numrows($result);

Thisassignsthecountofrowssavedin$resultto$num.Youcanthenuseitinalooptogenerateallthe

informationandsenditasanoutputscreen.

HowtoSetuptheLoop

Now,youneedtosetupaloopthatwilltakeeachoftheresultsrowandprintthestoreddata.Through

the$numyoudefinedearlier,youcanveryeasilyloopthrougheachoftherows.$iinthecodebelow

representstherepetitionstheloopismadetorun.Itislikewiseusedtoensurethattheloopendsonce

theresults’endisreachedsoerrorscanbeavoided.

$i=0;

while($i<$num){

CODE

$i++;

}

ThisbasicPHPloopexecutesthecodeattherightnumberoftimes.Ateverypass,$iwillassumea valuehigherthanthepreviouspass.Thisisquiteusefulasthevariablecanbeusedtoinstructthescript astowhichparticularlineoftheresultstoread.BecausethefirstlineoftheMySQLoutputhasthe

valueof0,thescriptwillbecorrectlyexecuted.

AssigningDatatoVariables

Thefinalsectionofthescriptistoassignavariabletoeachbitofdata.Hereisthepropercodetouse

forthispurpose:

Thefinalsectionofthescriptistoassignavariabletoeachbitofdata.Hereisthepropercodetouse forthispurpose:

Takeeverypieceofdatafromthedatabaseindividually,thenusethefollowingcode:

Atthispoint,thereisnoneedtogettheidfield,thoughitcanbedone,sinceitisnotrequiredinthe

outputpagewearecurrentlyworkingon.

CombiningtheScript

Youcannowcreateanentirescripttosendthedataasoutput.Notethatthefollowingscriptdoesnot

haveaformattedoutput.

Inthenextpartofthistutorial,youwilllearnhowtoformatyourdataoutput,aswellashowyoucan selectvariousdatafromthedatabase.

Inthenextpartofthistutorial,youwilllearnhowtoformatyourdataoutput,aswellashowyoucan

selectvariousdatafromthedatabase.

Chapter6:MoreOutput

Inthepreviouschapters,youhavelearnedhowtocreatetablesanddatabases,andinsertanddisplaythe

informationcontainedinthedatabase.Inthischapter,youwilllearnotherwaysonhowyoucandisplay

andoutputtheinformationcontainedinthedatabase.

FormattingOutput

Younowknowhowtooutputalistcontainingallthenamesandinfoofpeoplemaintainedinyour

database.Theoutputyougot,however,wasverybasic,andwouldnotbeofanygoodusetoyour

workingwebsite.Thisproblemcanbeaddressedbyformattingtheoutput,anddisplayingitintable

format.

Formattingyouroutputisnotreallycomplicated.AllyouhavetodoistocreateacodeusingPHPto

outputHTML.Justmakesuretoincludethevariablesintheirrespectivespaces.Oneoftheeasiest

methodstoachievethisiscloseyourPHPtag,andthennormallyenteringtheHTML.Onceyougettoa

variable,includeitusingthefollowingcode:

<?echo$variablename;?>

intheappropriatepositioninyourscript.

Likewise,youcanusethePHPloopforrepeatingthenecessarycodeandincludingitaspartofabigger

table.Forinstance,youcanuseapartofthecodefrompreviouslessonsthatwasintendedtoloopand

outputthecontentsofthedatabase.Youcanmodifytheformattodisplaytheresultsinonelargertable.

Thecodewillgeneratetableheaders,andthenaddoneextrarowforeveryrecordinthetable.Itwill

formatthedataasitissentforoutput.

IfyouarefamiliarwithPHPandHTML,whichyoushouldbebynow,youwillfinditself-explanatory.

However,thelasttwolinesinthetablewillstillbeexplained.Forinstance:

<ahref="mailto:<?echo$email;?>">E-mail</a>

ThisexemplifiesoneoftheadvantagesofusingPHPinincludingMySQLdataasitcanbeusedto

outputportionsofyourcodeandcreatefullydynamicpages.

SelectingBitsofData

Asidefromshowingtheentiredatabase,PHPcanalsobeutilizedtoselectsingleorindividualrecords,

orthosethatmatchcertaincriteria.YoucandothisbyusingaSELECTqueryvariation.Toshowthe

entiretable,usethequery

SELECT*FROMcontacts

Ifyouwanttochooseonlythosewhohavethefirstname“Jim,”youcanusethefollowingquerycode:

SELECT*FROMcontactsWHEREfirst='john'

JustlikeotherMySQLqueries,thecodereadslikeplainEnglish,similartohowyouwouldchoose

recordsbasedonaparticulardatabasefield.Likewise,youhavetooptiontoselectmorethanasingle

fieldjustbyaddingmoresectionsinthequery:

field='value'

WhilewewillnotdwelldeeperaboutthistopicinthissectionoftheeBook,youcanusevariablesto

providethedatabasecriteria.Ifyouarecreatingasearchform,forexample,youcangetthelastname

ofthepersonyouwanttosearchforandstorethevalueinavariablenamed$searchlast.Youcanthen

executethescriptthatfollows:

$query="SELECT*FROMcontactsWHERElast='$searchlast'";

$result=mysql_query($query);

Notethatattheendofthe1 st lineyoucanfinda‘thatisfollowedbya‘priortothesemicolon.

Security

Itisimportanttorememberthatyouneedtobeverycarefulwhenyouusetheabove-giventechnique.

Thisisbecauseintheabsenceofpropersecuritymeasures,itwouldbequiteeasyforanyonetoaccess

thedataonyourdatabaseserver,oreveneffectchangestoyourdatabase.Thiscanhappeniftheuseris

abletosetthevariabletoavaluethatwilledittheSQLstringgeneratedinawaythatwillservetheir

ownpurpose.Wewillnotgointodeeperdiscussionofthismatter,butifyouwantmoreinformation,

youcansearchforsitesthatprovidemoredetailedinformation.Justtype“sqlinjectionattack”onyour

searchengine.

Simplyput,thisisonesecurityholethatisveryeasytoaddress,althoughitrequiressomework.

Alwaysmakesuretocheckinputdataforanyinvalidcharacters,andutilizethebuilt-infunctionsin

PHPtogetridofHTMLcode,controlcharacters,andotherunnecessarycharacters.Again,youcan

refertootheronlinesourcesformoreinformationonthistopic.

Chapter7:SingleRecordsandErrorTrapping

Inthepreviouschapters,youhavelearnedhowtotakedatabasedataandhowtodisplaythesameonthe

screen.Forthischapter,wewillbecoveringthefinalaspectofdisplayingdata,selectingindividual

piecesofdata,andpreventingerrorsfromhappeningasyououtputdata.

ErrorTrapping

Whenyououtputalltheinfocontainedinthedatabase,itishighlyunlikelythatyouwillfindnodataat

all,althoughitisapossibilitywhenyouallowrecordupdatinganddeleting.Fortunately,ifyouare

usingPHPandMySQL,youhaveaneasyoptionthatyoucanusetogetaroundthisissue.

$num=mysql_numrows($result);

$result stores the database query result (similar to selecting all available records). As previously explained,thiscodewillassignavalueto$num,whichcorrespondstothenumberofresultrows

(which,inturn,wasemployedinaloopinprevioussectionsofthistutorial).Youcanthuscreatea

simpleerrortrappingscriptwiththeuseofanIFstatement:

if($num==0){

echo"Thedatabasedoesnotcontainanycontacts";

}else{

OutputLoop

}

Youcanmakethescriptmoreuser-friendlybyexpandingonit.Forinstance,youcanprovidealinkto

your“AddData”pageiftherearenoexistingcontacts.

OrderingData

Youhavetheoptionnotonlytooutputinformationbasedonthefieldcontents,youcanlikewiseorder youroutputbasedonaparticularfield.Anexamplewouldbetolisttheresultsinalphabeticalorder.

Thedefaultoutputfromyourqueriesisalistbasedontheidfiled,startingfrom1goingupwards.You

can,however,sorttheresultsbasedonanyfieldyouprefer.

Agoodexampleofausefulsortingorderwouldbetolistallusersalphabeticallybasedonthelast names.Ifyouarenotfamiliarwithhowstandarddatabaseswork,thisissimplysortingthelistin

ascendingorder–fromAtoZ.Fornumericlists,ascendingordermeansdisplayingfrom1onwards.

Descendingorder,ontheotherhandwilldisplayfromZtoA,or10to1.Youcanusethefollowing

querytoperformthistask:

SELECT*FROMcontactsORDERBYlastASC

Tosortthelistindescendingorder,youcanuseDESC.

OtherusesofSortingandmysql_numrows

Thevalueyouassignto$numservesaveryimportantpurposebecauseasidefromloopsanderror

trapping,ithasalotofotherapplications.Forexample,youcangiveinstructionstoprintoutjustthe5

recordsthatwerelastaddedtothedatabase.Initially,theresultswillbelistedinasortorderbasedon

theidfield.Thismeansthattherecordwiththenewestidwillbeaddedlast.Theresultthatyouwantis

alistsortedindescendingorder.

Youmayfindalistofnamessortedfromthelatestadditiontotheoldest;however,thescriptisnot

limitedtodisplayingonlythelast5.Youcandothisbysettingyourlooptorunonlyupto5,insteadof

thevalueof$num.Becausetheloopwillrunonly5times,itfollowsthatonly5recordswillbeinthe

output.

Priortothis,itisveryimportanttomakesurethat$numpreviouslyhadavaluethatismorethan5.

Onceyouruntheloopfor5times,andtheexistingnumberofrowsislessthan5,sayonly3,thiswould

resulttoanerror.Thesolutionisveryeasytoperform,though,andthescriptthatfollowsisagood

exampleofwhatyouneedtoachieve:

if($num>5){

$to=5;

}else{

$to=$num;

}

$i=0;

while($i<$to){

RESTOFCODE

Thescriptwillcheckifthereareatleastfiverowsinthetable.Ifthisconditionismet,theloopwill

thenbesettorepeat5times.Incasethereislessthanthesetnumberof5,theloopwillstillrunthe

requiredrepetitionsinoutputtingtheentiredatabase.

TheidField

YoumayrecallthatatthestartofthiseBook,specificallywhentheprocessofcreatingadatabasewas

covered,anumericalfieldnamedidwasincluded.Thisparticularfieldwassetupasauto_increment,

andastheprimaryfield.Itwasalreadyexplainedwhatmakesthisfielduniqueintheentiredatabase

table.Inthesucceedingsections,furtherexplanationwillbeprovidedastohowthefieldcanbeusedin

selectingindividualrecordsfromthedatabase.

SelectingaParticularRecord

Youhavepreviouslylearnedhowyoucanselectarecordfromthetablebasedonparticularvalues

containedinspecifiedfieldsusingthefollowingcode:

SELECT*FROMcontactsWHEREfield='value'

Thistime,wewillusetheuniqueidfieldtoselectanyrecordfromthetable,towit:

SELECT*FROMcontactsWHEREid='$id'

idisthevariablethatholdsthenumberofaparticularrecord.Asitis,itmayseemuseless,butthereare

specificinstanceswhenyouwillfinditveryuseful.Forinstance,ifyouneedtohavewebsitethatis

dynamicallygeneratedandrunthroughdatafromadatabaseusingjustonePHPscript,youcancreatea

codethatwillincorporatedatabasedatainthedesign.Next,youcanselectaparticularpageand

outputtingitbyusingtheidfield.YouevenhavetheoptiontousetheURLofthepagetospecifywhich

recordyouwant.ForExample:

ThePHPscriptwillthenlookfortherecordwiththeidvaluethatcorrespondsto$item;inthiscaseitis

therecordwithidfield1969.

LinksforSingleorIndividualRecords

ThismethodofselectingarecordbyusingtheURLcanbefurtherexpandedbydynamicallygenerating

theURL.Sure,itsoundsalittlecomplicated,butdon’tworryaswewilldiscussitinfurtherdetail.We

willbecreatingacontactsscriptwhereyouwilllearnhowtomakeanupdatepagethatallowsusersto

updateormodifycontactdetails.

Thiscanbedonebyincludinganothercolumnintheoutputthatcontainsanupdatelink.Thelinkwill

directtheusertoaspecificpagewherehecanupdatetherecord.Selectingtheparticularrecordinthis

pagewillbepossiblebyincluding:

?id=$id

Oncetherecord’sid,aswellastheotherrelatedinformationisobtained,youcannowoutputitfromthe

database.Thecodewillgeneratealinkthathastherecord’sidvaluestoredinit.Ontheupdatepage,a

codewillbeprovidedandmadeavailableforselection.

Chapter8:UpdatingandDeleting

Bythistime,youalreadyknowhowtoinputdataintotheMySQLdatabase,viewthedata,andselect

whichparticularinfoyouliketosee.Inthischapter,youwilllearnhowyoucanperformthelasttwo

actions–updatingthedatabase,aswellasdeletingpreviouslymaintainedrecordsfromthedatabase.

TheUpdateScript

Creatinglinksforeveryrecordtodirecttotheupdatescriptwasdiscussedinthepreviouschapter.

Whenyouusethevariable$id,yousendlinksthatwouldtransfertheappropriateidtothescriptsoit

canthenupdatethevaluesinthedatabase.Thiscanhelpyouwritetheupdatescriptthatwillbe

comprisedoftwosections.

HowtoDisplaytheUpdatePage

Remembertheindividual/singlerecordselectiondiscussedpreviously?Theinitialpartoftheupdate

scriptwillincludesomethingsimilar,buthasalittlebitofHTMLaddedtoitsoitcanbemore

functional.Butfirst,youhavetoconnecttothedatabaseandchoosetheappropriaterecord.

Inthescript,the‘SpaceforCode’iswheretheupdatepagecodewillgo,whichisactuallymerelyatype

ofoutputformatusingHTML.

Notethatthecodeisintendedtosendastandardformoutput,butratherthanshowingblankboxes

Notethatthecodeisintendedtosendastandardformoutput,butratherthanshowingblankboxes

similartotheformweusedforinsertingnewrecords,thisoutputalreadycontainsthelatestinformation

fromthetable.Thus,itisalotmoreeffectivewhenusedasanupdatescript.

UpdatingtheDatabase

Thesecondandfinalstageofthescriptisupdatingthedatabase.Therequiredoperationisverysimple,

andmerelyinvolvesaddinganewdatabasequery.

Thequeryinstructsthedatabasetohavethecontactstableupdatedwheretheidvalueisequaltothe

Thequeryinstructsthedatabasetohavethecontactstableupdatedwheretheidvalueisequaltothe

storedvalueinthevariable$ud_id.Intheformweusedinprevioussections,(youwillnoticethatitwas

setasthevalueoftheidwearetryingtoupdate)andassignedthespecifiedvaluestothesubsequent

fields(setusingthesameformweusedpreviously).

Youcanthenincorporatethefollowingqueryintoasimplecode:

Thecodewillupdatethetableandprovideconfirmationtotheuser. DeletingRecords

Thecodewillupdatethetableandprovideconfirmationtotheuser.

DeletingRecords

Thelastareaofthecontacttablethatweneedtocreateisthepagethatwillbeusedtodeleteorremove

records.SimilartotheUpdatepage,thisparticularpagemustreceivearecordidthatissentintheURL.

Forexample:

delete.php?id=9

Thiscodeissimilarastheoneusedinupdatingthedatabase,butwithaslightvariationintheMySQL

query.InsteadofusingtheUPDATEquery,therightcodetouseis:

DELETEFROMcontactsWHEREid='$id'

Thecodewillthenbeutilizedwiththeconfirmationandconnectioncodeliketheoneabove.

Loops

Nowseemstobethemostappropriatetimetodiscussanotherimportantapplicationofloopsina

database.Otherthanusingalooptoobtaininfofromdatabasesjustlikewhatwehavedonepreviously,

youcanlikewiseusealooptoperformqueries.Forinstance,ifyouwanttomodifyallrecordsinthe

table,andhaveallrecordsbearingthelastname“Doe”,containthewebsitewww.doe.com,

Youarelearningfastifyounoticethatthesametaskcanbedoneusingafasterandeasiermethodsuch as:

Youarelearningfastifyounoticethatthesametaskcanbedoneusingafasterandeasiermethodsuch

as:

$query1="UPDATEcontactsSETweb='http://www.doe.com'WHERElast='Doe'";

Thisway,aloopisnotnecessary.

Chapter9:FinishingtheScript

ThroughtheentirecourseofthiseBook,wehavediscussedhowyoucanusePHPtoworkwitha MySQLdatabase,aswellashowyoucanusethesimpleandmorecommoncommandsavailableat your disposal. Likewise, we have covered the necessary procedures in creating a simple contacts managementsystemthatshowedyouanumberofoptionsavailableforyoutouse.Inthischapter,we willdiscussseveralMySQLtips,andwewillcomeupwithafinalversionofyourPHPscript.

SavingTime

Ifyouhavebeenobservingandkeepingwhatwehavebeendoinginmind,youwillnoticethatwhen

youcreatecomplexscriptsthatworkwithdatabases,amongthemostcommonthingsthatwearedoing

istoconnecttoadatabase.Ifyousaywecanactuallysavealotoftimeifwecreateeitheraconnection

fileorausername/passwordfileandhaveitreadytouseanytime,youareabsolutelycorrect.Onegreat

exampleforthistypeoffilewouldbetocreateonethatisaptlynamed

dbinfo.inc.php

andincludingthefollowinginfointhescript:

andincludingthefollowinginfointhescript: Justreplacetheappropriateparts,andtheninyourPHPfiles,youcanusethefollowingscript:

Justreplacetheappropriateparts,andtheninyourPHPfiles,youcanusethefollowingscript:

include("dbinfo.inc.php");

or

include("/full/path/to/file/dbinfo.inc.php");

inthebeginning,afterwhichyoucanusethe$database,$username,and$passwordvariablesforthe

restofyourcodeswithoutthefindingtheneedtohavethemdefinedeachandeverytime.Likewise,if

inthefutureyouhavetomodifytheinformation,likeifyoutransfertoanewwebhost,youonlyhave

toeditonefile.

Thesameprinciplecanbeusedwhenconnectingtoadatabase.Youjusthavetoputtheappropriate

connectioncodeinthesavedfile,butbesuretoalwaysclosetheconnectionineachscript;otherwise,

issueswithyourMySQLservermayarise.

Searching

Youcanperformalimitedtypeofsearchingonyourdatabasethroughabuilt-infunctioninMySQL.To

dothisoperation,youhavetousetheLIKEfunctionthisway:

dothisoperation,youhavetousetheLIKEfunctionthisway:

ThecommandLIKE,toexplainabitfurther,instructsthedatabasetoperformthe“searching”feature.

The%signs(orpercentsigns)indicatethattheycanbereplacedbyanyotherdata.The$stringvariable,

meanwhile,willholdthesearchstring.Anynumberorwordcantakeitsplace.Forexample:

LIKE'%guitar%'

Thiswilloutputalltherowsthatcontainguitarinthefieldthatwasspecified.

Inthesamemanner,youcanmakedowithoutoneofthe%signs.Thisway,youcanspecifythestring

position.Thisishowyoudoit:

LIKE'guitar%'

Thiswilloutputonlytherowswherethefieldbeginsspecificallywithguitar.Thus:

Theguitarisnexttothetable

willnotappear.

Summary

To sum up everything we have covered thus far, you should, at this point, know the basics of programminginPHPandMySQLincreatingdatabase-enabledprogramsandwebsites.Youknowthat beingabletousedatabaseswiththewebprovidesyouwithawidearrayofthingstodothatcangive yourwebsiteabigboost.Youcanmakeyourwebsitealotmorepowerful.Youcanalsosavealotof timeinupdatingyoursite,aswellasallowuserinteractiontogainmorefeedback,andalotmore.

Chapter10:CommonPHPandMySQLDevelopmentMistakesto

Avoid

AccordingtothedefinitiongivenbyWikipedia,LAMPisafreeandopensourcesoftwareintendedto beasolutionstack.TheacronymrepresentstheinitiallettersofthewordsLinux(anoperatingsystem), Apache(anHTTPserver),andMySQL(adatabasesoftware),andanyoneamongPHP,Python,orPerl. These are the prime components you need in building and setting up a viable general purpose webserver.

Fromthatverydefinition,itisobviousthatthedatabaseisabasiccomponentofalmostallweb

applications.TheseincludeeventhedevelopmentofstaticwebsitesthatusedifferentCMSsoftware

likeWordPress,Drupal,andJoomla.Alltheseplatformshaveabackenddatabasethattheyusetostore

staticinformationandcontent.IfyouareauserofPHP,Python,orPerl,thenitisalmostcertainthat

MySQLislikewiseanimportantpartofthedevelopmentprocess.

PHPisveryeasy.Now,isitanadvantageoradisadvantage?

Asascriptinglanguage,oneofPHP’sbiggeststrengthshasbeenitsuser-friendlinessandeaseofuse.

Anyentry-leveloraspiringprogrammerwhoisluckyenoughtohavesomebackgroundofCLanguage

andhasagoodunderstandingofHTML/JavaScript/CSScangetagoodheadstartinprogramming

usingPHP.However,thissameadvantagedoesnotguarantyanefficientandsuccessfulcompletionof

projects.Afterall,tobesuccessful,whatisimportantarestability,sustainability,reliability,andfail

safeness.

Foryoutocomeupwithareliableandstablecode,aswellasbuildingarobust,dependable,andsolid

database,itwouldtakeacertainlevelofexpertise,andthiswillonlycomewithexperience,practice,

andlearningfromyourmistakes.

Havingsaidthat,herearethe10mostcommonpitfallsthatoftenbefallalotofPHPandMySQL

developers,whichyouarewell-advisedtoavoid:

1. OptingfortheWrongStorageEngine:InnoDBvs.MyISAM

TherearenumerousstorageengineoptionsthatMySQLoffers;however,themostpopularamong

themareInnoDBandMyISAM.

ThedefaultstorageengineisMyISAMthatisbasedontheancientversionoftheISAMstorage

enginethatiscurrentlynolongeravailable.EverytableinMyISAMisstoredinthreefilesondisk.

• <tablename>frm–thisstoresthetableformatorstructure

• <tablename>MYD–thisstorestabledata

• <tablename>MYD–thisholdstableindexinfo

On the other hand, InnoDB is a high-performance, highly reliable MySQL storage engine.

BeginningwithMySQLver.5.5,InnoDBisthedefaultstorageengine,andisclassifiedasACID

compliant.ACIDstandsforatomicity,consistency,isolation,anddurability.

MyISAMemploystablelevellocking,whileInnoDButilizesrow-level-locking.Inthiscase,table-

level-lockingcanposeasavitalperformancebottleneckwhennumerouswritestothetableare

simultaneouslybeingdone.

AmongPHPdevelopers,thereisacommontendencytoselectMyISAMoverInnoDBmainly

becausetheydeemthattheformerismucheasiertousecomparedtothelatter.

2. FailuretoEncryptthePasswordField

Again,thisisaverycommonpropensityofPHPprogrammerstohavetheirpasswordsstoredinina

stringwithoututilizinganytypeofencryptionfunction/algorithmlikeMD5orbase_64.Thismakes

thingsaloteasierforhackerstoemploySQLinjections.Youmustthereforealwaysstoreyour

passwordfieldasMD5(password)sinceMD5isnotreversible,andeventheDBAhimselfcannot

viewthepassword.AlthoughtheDBAcanalwaysresetitthroughasimpleUPDATEquery,the

pointisthatthepasswordfieldinformationisexposedneithertotheDBAortheprogrammer.

3. FailuretoValidateUserInputs

Sure,itisverydifficulttoblindlytrustuserinputs.Thus,youneedtovalidateeachandeverystring

usingserver-sidecodes.Don’trelyonJavaScript,either.HereisaverysimpleexampleofanSQL

injectionattackscriptthatworksjustfine.

injectionattackscriptthatworksjustfine.

Topenetrateit,ahackerwilljustenter“admin';–”inthefieldprovidedfortheusername,andthe

querywillappearsomethinglikethis:

SELECTuseridFROMusertableWHEREusername=’admin';

Thehackermaybeeasilyloggedinas“admin”,buthemustknowthecorrectpasswordsinceitis

commentedoutsideoftheSQL.

4.

Useof*inSELECTQueries

Donotuse*toreturnacolumninqueries–notnow,notever!Wheneverpossible,specify

explicitlythecolumnsthatyouwant.Ifallthecolumnsthatarereferenced(selectedandfiltered)in

thequeryexistasnaindex(akacoveringindex),thereisnoneedforthedatabasetotouchthetable.

Everythingcanberesolvedsimplybyscanningonlytheindex.Whenyouselectallcolumns,you

takeawaythisoptionfromtheoptimizer.Likewise,selectingafewernumberofcolumnscanspeed

uptheresults.

5. UseoftheWrongDataTypes

There’sawiderangeofstring,numericandtimedatatypesofferedbyMySQL.Exertsomeeffort

andalittlethoughtwhenchoosingwhichparticulardatatypetouseforafield.

If you intend to store Boolean value such as 1 or 0 in an INTEGER field, instead of using

INTEGER(10),useTINYIN(3)instead.

Ontheotherhand,ifyouneedtostoreone-charactervaluessuchas“T”or“F”,orA,B,C,etc.,

thenyoucangoforCHAR(1),insteadofusingVARCHAR.

Now,ifyouneedtostoreadatevalue,useaDATE,TIMESTAMP,orDATETIMEfield.Youwill onlycomplicateyourSQLqueriesbyusingaSTRINGorINTEGERfield;itcanalsoresultto errors. TIMESTAMP likewise allows you to set default values as CURRENT_TIMESTAMP. Remember,however,thatonlyasingleTIMESTAMPfieldcancarryaCURRENT_TIMESTAMP defaultvalue.

6. Over-orUnder-Indexing

Indexes(orindices),asaruleofthumb,mustbeappliedtoallcolumnsthatarenamedina

SELECTquery’sWHEREclause.

Forinstance,assumethatthereisausertablethathasanumericid(primarykey)aswellasan

emailad.Whileloggingin,MySQLmustbeabletofindthecorrectIDsimplybysearchingforan

emailaddress.Withproperindexing,MySQLisabletouseaspeedysearchalgorithmtoquickly

findtheemail–instantly.Ifthereisnoindex,MySQLwillgothelongtrekofcheckingevery

recordinthecurrentsequenceuntilitfindstherightaddress.

Itcanbequitetemptingtoaddanindextoeachcolumn.Keepinmind,howeverthatindexesare regenerated each time an UPDATE or INSERT command is executed on the table. This can adverselyaffectperformance,soaddindexesonlywhennecessary.

Amongallerrorscitedinthischapter,thisisprobablythemostcommonmistakebroughtaboutby

thelazinessinmanyPHPandMySQLdevelopers.

Basically,therearethreemostpopularwaysinconnectingtoMySQLviaPHP:

• PDO

• mysql_connect

• mysql_pconnect

Bothmysql_pconnectandmysql_connecthavebeendepreciatedasofthearrivalofPHP5.5.0,and

arelikelygoingtoberemovedinthenotsodistantfuture.PDOthereforeremainsastheonlyviable

optionsfordevelopersandprogrammers.

Ifyouprefertousemysql_connect,itisimportanttomakesurethatyoucloseallconnections

properlytopreventreceiving“toomanyconnections”errormessages.Inaway,mysql_pconnectis

safertouse,butsinceboththesemethodshavealreadybeendepreciated,itishightimeforyouto

moveonandstartusingPDOforyourcurrentandfutureapplications,regardlessofwhetheritisa

newsystemoralegacysystem.

8. FailuretoOptimizeQueries

Approximately99%ofallperformanceissuesinPHPareduetothedatabase(akanotoptimized

SQLqueries).AsinglebadSQLqueryiscapableofdoingasignificantamountofdamagetoyour

webapplication.TheEXPLAINstatementinMySQLcanbeofhelp-somewhat.Inaddition,you

willalsohavetoturnonveryslowqueryanderrorlogsinyourDBserverinordertounderstand

whichofyourqueriesarepoorlyperforming,andwhichqueriesarecausingtheerrorsthatyouhave

topromptlyresolve.

9. PreferringPHPoverMySQL

MostnewbiestoLAMPtendtoprefersolvingproblemsusingPHPcodes,insteadofwritingan

efficiently-workingMySQLquery.

Forexample,insolvingaprobleminvolvingthecomputationofaveragevaluesbasedongiven

attributevalues,inexperiencedPHPprogrammerswouldresorttocomputingtheaverageusingthe

PHPloopfunction.Thereisamuchbetterwaytodothis,whichistousethebuilt-inAVG()

functioninMySQL.

ItisamistaketorunanSQLqueryinsidealoop.Instead,usingasinglequery,obtaintherequired

records;andthenusetheWHILElooptoprocesstheinformation.

10.NotUsingUTF-8

For internationalization purposes, UTF- 8 has been proven to be vital. Although PHP won’t properly support it until the release of PHPver. 6.0, you cannot avoid setting your MySQL

charactersetstoconformtoUTF-8.Theimportanceofinternationalizationcanbeseenfromthe

factthatotherthantheUS,UK,Australia,andsomepartsofAsia,therestoftheworldprefers

usingtheirnativelanguageoverEnglish.

Likewise,neverforgettoregularlyback-upyourdatabasetomakesurethatyourapplicationsare

failsafe,asfarasdatasecurityisconcerned.

ItmaybetruethatMySQListhemostprevalentdatabaseusedbyLAMPdevelopers,aswellasby other open-source technology programmers including Groovy, Python, and Ruby, among others. However,thereareotheroptionsasidefromMySQL.TheclosestcompetitorsareprobablyFirebirdand PostgreSQL. Oracle offers 10g Express, while Microsoft has SQL Server Express. Both are free versionsofbiggerenterpriseeditions.Forembeddedorsmallerapplications,SQLitemaybeagood option.WiththearrivalofthenewNOSQLera,otheroptionslikeCouchDBandMongoDBare emergingforhugedatavolumes.

Conclusion

Thankyouagainfordownloadingthisbook!

IhopethisbookwasabletohelpyoutolearnthebasicsincreatingscriptsinPHPwithMySQL.

Thenextstepistopracticeandapplywhatyouhavelearnedfromthisbook.Createusefulscriptsthat

willinteractwiththedatabaseinyourwebsiteandmakefulluseofthestoredinformationyoucan

extract.

Finally,ifyouenjoyedthisbook,thenI’dliketoaskyouforafavor,wouldyoubekindenoughtoleave

areviewforthisbookonAmazon?It’dbegreatlyappreciated!

Thankyouandgoodluck!

CheckOutOtherBooksby‘ZEROtoHERO’

Belowyou’llfindsomeofourotherpopularbooksthatarepopularonAmazonandKindleaswell.

Simplyclickonthelinksbelowtocheckthemout.Alternatively,youcanvisitmyauthorpageon

Amazontoseeotherworkdonebyme.

ProgrammingLanguages

•HTML:LearnHTMLProgrammingWithUltimateZerotoHeroProgrammingCrashCoursefor

Beginners

•PHP:LearnPHP&mySQLProgrammingWithUltimateZerotoHeroProgrammingCrashCourse

forBeginners

•R:LearnRProgrammingWithUltimateZerotoHeroProgrammingCrashCourseforBeginners

•Ruby:LearnRubyProgrammingWithUltimateZerotoHeroProgrammingCrashCoursefor

Beginners

•Java:LearnJavaProgrammingWithUltimateZerotoHeroProgrammingCrashCourseforBeginners

•Python:LearnPythonProgrammingWithUltimateZerotoHeroProgrammingCrashCoursefor

Beginners

*BONUS*:FREEPHPCourse!

Iknowhowimportantitistoimplementwhatyoulearn,orevenlearnbytakingaction.Asmy“Thank

You”fordownloadingthisbookIprovideyouwithFREEPHPcoursewheremorethan900kstudents

areenrolled!WiththiscourseyouwilllearnandusemoreofPHPprogramminglanguage,awidespread

languagethatpowerssiteslikeFacebook

Sowhatareyouwaitingfor?Clickheretogetstartednow!

WewantyoutosucceedinyourgoaltomasteringPHP!Pleasemakeuseofthiscourse,itwillhelpyou

alot!

©Copyright2014byZerotoHero-Allrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicand issue covered. The publication is sold with the idea that the publisher is not required to render accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or professional,apracticedindividualintheprofessionshouldbeordered.

-FromaDeclarationofPrincipleswhichwasacceptedandapprovedequallybyaCommitteeofthe

AmericanBarAssociationandaCommitteeofPublishersandAssociations.

Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronic

meansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthis

documentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsof

inattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithin

isthesolitaryandutterresponsibilityoftherecipientreader.Undernocircumstanceswillanylegal

responsibilityorblamebeheldagainstthepublisherforanyreparation,damages,ormonetarylossdue

totheinformationherein,eitherdirectlyorindirectly.

Respectiveauthorsownallcopyrightsnotheldbythepublisher.

The information herein is offered for informational purposes solely, and is universal as so. The presentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.

Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithout

permissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookarefor

clarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.