21
Table of Contents 1.1 Introduction 1 1.2 Getting Setup 2 1.3 Your first PHP webpage 3 1.4 Working with text 4 1.5 Talking to the user 5 1.6 Comparison & If statements 6 1.7 If & Else 7 1.8 Cleaning up the game 8 1.9 Remembering values 9 1.10 Finishing your game 10 I'm learning: PHP BEGINNER PHP 1

Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

  • Upload
    lyminh

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

TableofContents

1.1Introduction1

1.2GettingSetup2

1.3YourfirstPHPwebpage3

1.4Workingwithtext4

1.5Talkingtotheuser5

1.6Comparison&Ifstatements6

1.7If&Else7

1.8Cleaningupthegame8

1.9Rememberingvalues9

1.10Finishingyourgame10

I'mlearning:PHP

BEGINNERPHP

1

IntroductionI'mlearning:PHP

BEGINNERPHP

2

TheseSushiCardswillhelpyoulearntobuildwebpagesusingPHP,averypopular

programminglanguagethat'susedtobuildwebsiteslikeFacebookandWikipedia.You

cancombineitwithHTML(andcheckouttheHTMLSushiCardsifyoudon'tknowhowto

codeHTMLyet!).

1

First,you'regoingtoneedsomewheretocode!PHPneedsafewdifferentpiecesinplace

tomakeitworkand,ifyou'regoingtoreleaseawebsitelater,you'lleventuallyneedto

learnhowtosetthatup.Fornow,though,let'sjustgetgoingquicklybyusingCloud9,an

onlineeditorthatwilldoallthesetupforyou!Checkitoutatdojo.soy/php-edit.

2

YoucanuseyourGitHuborBitbucketaccounttosigninifyouhaveone.Otherwise,sign

upwithyouremailaddress.3

Choose"Createanewworkspace"andfillitinasfollows:

Workspacename:beginner-php

Description:MyfirstPHPwebsite

MakesurethatHostedworkspaceisselected

ChooseaPrivateworkspace

SkipovertheClonefromGitorMercurialURL—youdon'tneedto

cloneanything

ChoosethePHP,Apachetemplate

4

GettingSetupI'mlearning:PHP

BEGINNERPHP

3

NowjustclickonCreateworkspaceandyou'reallset!5

Onceyourworkspaceisupandrunning,you'llnoticeyou'vebeengivenafewfiles,which

youcanseeinthesidebar.6

You'regoingtoneedtocreateanewfiletoputallyourcodein.Youcandothisby

choosingFile>NewFileinthemenu.7

Oncethefileisopened,youcansaveitbychoosingFile>SaveAsandgivingitaname.

Savethisonenowasindex.php8

You'rereadytomakeyourfirstPHPwebpage!9

GettingSetupI'mlearning:PHP

BEGINNERPHP

4

TimetostartcodingyourfirstrealPHPwebpage!You'regoingtostartwithoneofthe

classics,saying"Hello!"toyouruserand,bytheendofthesecards,you'llbemakinga

numberguessinggamefortheusertoplay!

1

So,tobeginwith,everyPHPwebpagewillhaveatleastalittlebitofHTMLinit.Startby

makingareallybasiconebytypingthiscodeintoyourindex.phpandsavingit.

<!DOCTYPEhtml>

<html>

<head>

<title>MyPHPwebpage</title>

</head>

<body>

ThisisjustHTMLtext,itisnotcleverlikeyourPHPtextwillbe!

</body>

</html>

Thethingsintheanglebrackets(<>)arecalledHTMLtagsandyou'llbecomingacross

afewoftheminthesecards.Therearelotsmore,though,andyoucanlearnaboutthem

intheHTMLSushiCardsandinloadsofotherplacesonline!

2

YourfirstPHPwebpageI'mlearning:PHP

BEGINNERPHP

5

Runthatpageandyou'llseeabasicHTMLpage.Tobeginwith,yourPHPpageisgoing

tolookprettysimilar,butveryquicklyyou'llbeusingthepowerofPHPtodothingsthat

HTMLnevercouldalone!Togetstarted,replacethatHTMLtextwithsomespecialPHP

code.

<body>

<?php

echo"Helloeveryone!ThisismyfirstPHPprogram!";

?>

</body>

NoticethatPHPcodealwaysappearsinside<?phpand?>.Thisissothecomputercan

tellwhichpartsarePHPandwhichpartsareHTML.Usingthese,youcanputPHPcode

anywhereinsidetheHTML.

Also,noticethatthePHPcodealwaysendseachlinewithasemicolon(;).Thisisso

PHPknowstoendthiscommandandstartanother.Ifyouforgettodothis,PHPcanget

veryconfused.

3

NowsaveandrunyourPHPfile.Congratulations!Ifitallworked,you'vejustwrittenyour

firstPHPwebpage!4

YourfirstPHPwebpageI'mlearning:PHP

BEGINNERPHP

6

Nowit'stimetostartworkingonyourgame!Thefirstthingyou'regoingtoneedistoteach

theplayertherules.

Youmightwanttochangethingslikethesmallestandbiggestnumbers,orthenumberof

guessesyou'regoingtogivetheplayer.IfyouwroteouttheruleswithplainHTML,you'd

havetogobackandre-writethemeverytimeyouchangedanyofthosethings.Youdon't

needtodothat,though.YoucanusePHPandvariablestoincludethenumbersaspart

ofyourtext!

1

First,you'regoingtoneedtotoupdateyourtext,sochangethePHPcodeonyourpage

tothis:

echo"I'vepickedanumberbetween1and9<br/>";

echo"Youwillhave5chancestotrytoguessmynumber!";

The<br/>isapieceofHTMLthattellsthebrowsertostartanewlineafterit.Youcan

putanyHTMLinsideyourPHPanditwillbetreatedexactlyasifithadbeenwrittenas

HTML.

Noticethatyou'reusingdoublequotes(")aroundyourtextinsteadofsinglequotes

('),fortworeasons:

PHPwillgetconfusedifyouuseanapostropheinsideofsinglequotes.

Tryitandsee!Whathappens,andwhy?

PHPwilldosomethingspecialinsideofdoublequotesthatitwon't

insideofsinglequotes,whichyou'llseebelow.

2

WorkingwithtextI'mlearning:PHP

BEGINNERPHP

7

Nowit'stimeforyoutostartaddingvariables!Thesearelabelsthatyoucanusetostore

values,likeastringoftextoranumber.PHPremembersthosevaluesandletsyouuse

thevalueslaterbyusingtheirlabel.Thisletsyousetavalueonceanduseitloadsof

timesinyourprogram.

InPHP,allvariablenamesstartwithadollarsign($)andareusuallywrittenin

camelCase,wherethefirstwordstartswithasmall(lowercase)letter,thereareno

spaces,andanylaterwordsstartwithcapital(uppercase)letter.

Putthislinein,insidethe<?phpbutbeforetheecholines

$minValue=1;

$maxValue=9;

$guesses=5;

Allofthesevariablesarenumbers,butyou'llbeworkingwithtextvariableslater.

3

Now,updateyourtwoecholinessotheylooklikethis:

echo"I'vepickedanumberbetween{$minValue}and{$maxValue}<br/>";

echo"Youwillhave{$guesses}chancestotrytoguessmynumber!";

Noticethecurlybraces({and})aroundthevariablenamestotellPHPnottotreat

themlikeregulartext!

4

Runyourprogramandseewhathappens.Thentrychangingthevaluesofsomeofthe

variablesandrunitagain.Justmakesuretoseteverythingbacktothewayyou'vegotit

herebeforemovingon!

5

WorkingwithtextI'mlearning:PHP

BEGINNERPHP

8

Ok,soyoucangetinformationfromavariableandshowittotheplayerwithecho,but

howdoyougetinformationfromtheplayer?Afterall,thisisaguessinggame,soyou

needsomewaytocollecttheirguesses!

1

You'regoingtouseacombinationofHTMLandPHPtodothis.TheHTMLyou'llbeusing

isgoingtobenew,evenifyou'vealreadydonetheHTMLSushiCards,sincetheydon't

usemanyformsandyourPHPprogramswillprobablyusealotofthem.Youcansee

themonalmosteverywebsiteyouusetheinternetandthecodeforthemisprettyeasy!

<formmethod="get">

Yourguess:<inputtype="text"name="guess"/>

</form>

AHTMLformisasimpleidea:controls—liketextboxes,drop-downmenus,checkboxes

orbuttons—areusedtocollectinformationfromusersandsendthatinformationtoyour

PHPprogram.Sometimes,responsesaresenttotheusers.You'llbesendingresponses

inyourgames.

2

Now,timetoaddaformtoyourpage!SoyoucanusePHPvariablesandothercodein

creatingyourform,you'regoingtouseechostatementstocreateit,insteadofjusttyping

theHTMLintothefile.So,addthefollowingbelowyourtwoexistingechostatements:

echo"<formmethod="get">";

echo"Yourguess:<inputtype="text"name="guess"/>";

echo"</form>";

Runthiscodeandseewhathappens!

3

TalkingtotheuserI'mlearning:PHP

BEGINNERPHP

9

Well,thatdidn'tquiteworkright,didit?Anyideawhy?It'sbecauseofthedoublequotesin

<formmethod="get">.PHPisn'tsmartenoughtorecognisethattheyarepartoftheHTML

tag;itreadsthemastheendofthestringoftextthatechoistryingtoinsertintothe

page.Afterthat,it'slookingforasemicolon(;)butinsteaditfindsgandgetsvery

confused!Thiskindofproblemcancomeupquiteofteneitherbecauseyou'veforgotten

whichkindofquotestouseoryou'recopyingfromanotherofyourprogramsandused

quotesdifferentlythere.Luckily,it'sveryeasytofix.Justputabackslash(\)infrontof

yourallyourdoublequotes(don'tforgettheonesintheinputtag!)likethis,toescapethe

normalruleofendingthestring!

echo"<formmethod=\"get\">";

4

Runthecodeagain!Nowyou'vegotsomewhereforyourusertoputtheirtext!Type

somethinginandpresstheenterkey.WatchthepageURLinthebrowserandnotice

whatchanges!

5

TalkingtotheuserI'mlearning:PHP

BEGINNERPHP

10

ThetextthatappearedontheendoftheURLiscalledaqueryparameterandyoucan

haveloadsofthemonthesameURL.Theformautomaticallyaddedone(becauseyou

setmethod="get"),butyoucouldjustaseasilytypethemin,separatedbysemicolons.

PHPreadstheendoftheURLforthepageit'sloadedonandturnsallthequery

parametersintosomethingcalledakey,valuearray.Youdon'tneedtoknowexactly

whatthatisrightnow,we'llgointoitinalaterSushiCardseries.Whatyoudoneedto

knowishowtogetvaluesoutofit.

1

Allyouneedtodotogetavalueoutofthearrayispassinthekeyofavaluethat'sin

there.Sinceyourformaddstheguessfield,that'stheoneyou'llbelookingfor.You'll

wanttoassignthatvaluetoaplayerGuessvariable,soaddthislinejustbeforeallyour

echolines:

$playerGuess=$_GET['guess'];

2

Now,remindtheplayerwhattheirlastguesswasbyaddinganotherechojustbeforethe

inputform:

echo"Yourlastguesswas{$playerGuess}.<br/>";

Runthecode.Nowyou'retakinginputfromyourplayerandgivingitbacktothem.Very

cool!

3

Comparison&IfstatementsI'mlearning:PHP

BEGINNERPHP

11

TryremovingallthequeryparametersfromtheURLandreloadingthepage.Noticethat

younowget"Yourlastguesswas."

That'snotideal.Whatyouwanttohappenis:

Checkifthere'savalue(maybetheyhaven'tmadeaguessyet)

ifso,showthemessageaboutthelastguess

4

PHPcanfigureallthisoutanddoitforyou!Youjustneedtouseanifstatement.

Anifstatementusesatest(inbrackets),thathasananswerthat'seithertrueorfalse

and,ifit'strue,apieceofcodetorun.Youcandothistocheckifyourvariablecontains

anythinglikethis:

if(!empty($playerGuess)){

echo"Yourlastguesswas{$playerGuess}.";

}

Hereempty()isaspecialpieceofPHPthatcheckswhetherthevariableinsideits

bracketshasavalueandanswerseithertrueifitdoesn'torfalseifitdoes.The!before

itreversesthisanswer,turningatrueintoafalseandafalseintoatrue.Sowhatthis

codesaysis:"Ifthereisnotnovaluein$playerGuess,thenprintoutYourlastguesswas

[thevalueofplayerguess]."

Replaceecho"Yourlastguesswas{$playerGuess}.";withthecodeaboveandtestit

withandwithoutanswerstoseeitworking.

5

Comparison&IfstatementsI'mlearning:PHP

BEGINNERPHP

12

Nowthatyouknowhowtouseifstatements,youcanstartwritingthecodetogetyour

gametorun!You'lldealwithusingarandomnumberinalatercard,butfornowjustadd

anothervariableupatthetopwithalltheotherstosetyour"secret"number,likethis:

$secretNumber=5;

1

Whatyouwanttodonowiscomparetheplayer'sguesswiththesecretnumber,andtell

themiftheyguessedcorrectly.Tocompareonevaluetoanotherandgetatrueorfalse

result,youusetwoequalssigns(==).Ifthevaluesoneithersidearethesame,thenthe

resultistrue;otherwise,it'sfalse.

Here'showyou'dchecktheplayer'sanswerinyourPHP:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

Addthiscodein(afterthosevariables'valuesareset!)andthenruntheprogram.Try

guessingcorrectly(i.e.5)andincorrectly.

2

If&ElseI'mlearning:PHP

BEGINNERPHP

13

Haveyounoticedafewissueswithwhat'shappeninghere?Foronething,theplayeris

stillaskedtopickanumberevenwhenthey'vewonthegame!Youcanfixthat,though,by

usingelsestatements,afteryourifstatements.Youcan'tuseelseonitsown,it

onlyrunsthecodeinsideitifthetestontheifstatementjustbeforeitwasfalse.

So,toonlyshowtheformforthenextguessiftheplayerhasnotyetguessedthesecret

number,youneedtoaddanelseontoyouriffromaboveandmovealltheformcode

intoit,likethis:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

else{

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"</form>";

}

3

If&ElseI'mlearning:PHP

BEGINNERPHP

14

Itdoesn'tmakesensetogivetheplayertheinstructionsonhowtoplayeverysingleturn.

However,itwouldbeusefultotellthemhowmanyguessestheyhaveleft.Todothis,

you'llneedtocreateanothervariable,guessesLeftandaddittoyourfile:

$guessesLeft=$guesses;

Notethatbecauseyouaresettingthisvariabletothevalueofanother,itmustbedeclared

afterthatvariable.

1

Next,taketherulesechocodeandstickitintoanifthatchecksifthenumberof

guessestheplayerhasleftisequaltothenumbertheystartedwith.Ifitis,thenyouknow

it'sthefirstturnandyoucanshowthemtherules.Ifit'snot,thentellthemhowmany

guessestheyhaveleft.

if($guessesLeft==$guesses){

echo"I'vepickedanumberbetween{$minValue}and{$maxValue}<br/>";

echo"Youwillhave{$guesses}chancestotrytoguessmynumber!<br/>";

}

else{

echo"Youhave{$guessesLeft}guessesleft.<br/>";

}

2

CleaningupthegameI'mlearning:PHP

BEGINNERPHP

15

Ifyourunthiscodeandplaythroughitafewtimes,you'llnoticethatthenumberof

guessesnevergoesdown!Therearetworeasonsofthat,andyou'llsolvethemoneata

time.ThefirstisthatyouneverdecreasethevalueofguessesLeft!Therearetwothings

youneedtodotomakethishappenandyou'llgothroughbothofthemonthiscard.First,

youneedtocheckiftheplayermadeaguessand,ifso,setguessesLefttoonelessthan

thecurrentvalue.

Youalreadyhavethetestformakingaguess,sinceyoucheckforaguessbefore

decidingwhethertoshow"Yourlastguesswas...".Youcanjustupdatethatcodeto

includeasecondlinethatdecreasesguessesLeft,likethis:

if(!empty($playerGuess)){

echo"Yourlastguesswas{$playerGuess}.";

$guessesLeft=$guessesLeft-1;

}

3

Nowit'simportanttokeepaneyeontheorderofyourcode.Ifyourunthiscodeas

written,you'llnoticethecountofguessesstilldoesn'tdrop!Thisisbecausetheecho

codethatprintsthevalueofguessesLeftrunsbeforethecodethatchangesthatvalue!All

youneedtodoismove(cutandpaste)thecodesoitcomesjustafterallyourvariable

declarationsatthestartandthingsshouldworkfine.Dothatnowandtryrunningitagain.

4

CleaningupthegameI'mlearning:PHP

BEGINNERPHP

16

You'llnoticethatnowthecountofguessesdoesgodownto4,butitnevergoesany

lower!Anyideawhy?It'sbecauseofthewayPHPworks:Everytimethepageloads,the

programrunsagainfromthestart,withnomemoryofthelasttimeitran!Thatmeansit

alwaysresetsthevalueofguessesLeftto5andthen,ifaguesswasmade,subtracts1.

So,whatyouneedtodohereisstorethatvaluesomewhereandpassitintotheprogram

thenexttimeitruns.Well,youalreadyhavesomethinglikethat:theformontheweb

page!YoucanwritethecurrentvalueofguessesLeftintotheformandreaditbackout

from$_GETlater.Startwiththewriting,byupdatingyourformcreationcodetolooklike

this:

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"<inputtype='hidden'name='guessesLeft'value='{$guessesLeft}'/>";

echo"</form>";

Thetypeofthefieldis"hidden",soitwon'tbevisible,butwillbesentinontheURL.The

valueissettothecurrentvalueof'guessesLeft'.

1

RememberingvaluesI'mlearning:PHP

BEGINNERPHP

17

Nowyouneedtopickupthevalueyou'vesavedandwriteitintoguessesLeft.Thisgetsa

littlecomplicated,sincetherewon'talwaysbeavalueintheURL(thefirsttimethegame

isrun,forexample).Soyouneedtoreplacethecurrentline$guessesLeft=$guesseswith

this:

$guessesLeft=$_GET['guessesLeft'];

if(!isset($guessesLeft)){

$guessesLeft=$guesses;

}

ThiscodetriestogetthevaluefromtheURLand,ifitdoesn'tfindit,leavesguessesLeft

empty,whichcausesthecodeintheifstatementtorun,fillingitwiththevalueof

guesses.Thereasonwedidn'tuseemptyhereisbecauseemptywillgiveafalseifthe

valueis0,whichisgoingtohappenhere,whentheplayerrunsoutofguesses.Try

runningtheprogramagainandyou'llseethatitallworksnow!

2

Youmayhavenoticedonelastproblem:Thegamedoesn'tendwhenyourunoutof

guesses!We'lllookathowtofixthat,andhowtouseasecretnumberthatactually

changes,onthenextcard!

3

RememberingvaluesI'mlearning:PHP

BEGINNERPHP

18

First,let'slookatmakingtheplayerlosethegame.Thisneedstohappenwhenthey've

usedtheirlastguessup,sowhen$guessesLeft==0.Whenthishappens,keepshowing

themtheirlastguess,andthattheyhavenoguessesleft,butnottheformortherules.To

makethathappen,you'llneedtouseanewbitofcode:elseif.

1

Asyoumighthaveguessedelseifisacombinationoftheelseandifstatements.

Likeelse,itonlyhappensiftheconditioninanifstatementisfalse,butlikeifit

hasitsowncondition.

Youcanuseasmanyelseifstatementsasyouwant,butonlythefirstonethathasa

trueconditionwillrun.Ifnoneofthemaretrue,theelsestatementwillrun,justlikewith

aregularif.

Togetyourgametotelltheplayerthey'velost,youjustwanttoaddanelseiftothe

codethatcheckstheiranswerandshowsthemtheforto,iftheyhavenowguessesleft,

showthemadifferentmessageinstead,likethis:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

elseif($guessesLeft==0){

echo("<br/>Gameover!Youlose!");

}

else{

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"<inputtype='hidden'name='guessesLeft'value='{$guessesLeft}'/>";

echo"</form>";

}

2

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

19

Ok,nowyouhaveagamewheretheplayercanguessanumber,getacertainnumberof

triesandbetoldiftheywinorlose.Verycool!However,rightnow,thatnumberisalways

5...whichislesscool.PHPisprettygoodatcomingupwithrandomnumbers,though.To

usearandomnumberinsteadyoujustneedtochangethecodeforsecretNumberlike

this:

$secretNumber=$_GET['secretNumber'];

if(!isset($secretNumber)){

$secretNumber=rand($minValue,$maxValue);

}

Therandisafunctionthattakestwonumbersandgivesyoubackarandomnumber

betweenthem.You'reusingminValueandmaxValueheresoyouonlyhavetochange

thosenumbersinoneplaceandthey'llchangeeverywhereinyourcode!

3

Nowyouneedtomakesurethatit'sthesamerandomnumberthroughoutthegame.It

wouldn'tbefairtokeepchangingitonyourplayer!Youalreadyknowhowtodothisone

though:ahiddenformfield.Justaddthistoyourechocodefortheguessingform(you

won'tneedtokeepstoringitiftheplayerwinsorloses!).

echo"<inputtype='hidden'name='secretNumber'value='{$secretNumber}'/>";

4

Now,trytoplayyourgame!5

Howelsecouldyouusethiscode?You'vegotallthepiecesheretomakeaquizoran

interactivestory,whereyoukeepscore,askdifferentquestionsoneachpageandeven

sendtheplayerindifferentdirectionsbasedontheiranswers!

6

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

20

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

21