CPAP.com Introduction To Coding: Part 2

320 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
320
On SlideShare
0
From Embeds
0
Number of Embeds
30
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

CPAP.com Introduction To Coding: Part 2

  1. 1. Introduction To CodingPart DeuceJeremy Montoya
  2. 2. What Will Be Covered?●General overview of last session(variables, if statements, etc..) but from thePHP aspect● Understand how logic and concepts canbe learned – and easily applied using anylanguage.● A high level overview of querying adatabase using PHP
  3. 3. No SQL again today..●That concept is a completelydifferent monster in the world ofprogramming.
  4. 4. Todays Language - PHPPHP Hypertext Processor● One of the most widely used serverscripting languages● Ideal to use when a web page needsto be dynamic or when communicationwith databases is needed● Static pages can be generated as well– but not needed
  5. 5. Where Is This PHP?● Windowshttp://windows.php.net/download/● Unixhttp://www.php.net/manual/en/install.unix.php● Mac OS Xhttp://www.php.net/manual/en/install.macosx.php
  6. 6. Not Everyone Likes PHP..(11:39:56 AM) Myself: do you like PHP(11:40:04 AM) Paimoe: eh(11:40:17 AM) Myself: congrats(11:40:20 AM) Myself: you just made my presentation(11:40:24 AM) Paimoe: lol
  7. 7. Some People Do!(11:44:09 AM) Myself: do you like PHP(11:44:15 AM) Ben: I do(11:44:18 AM) Myself: whys that(11:44:18 AM) Ben: It works well enough(11:44:24 AM) Ben: Some useful features(11:44:28 AM) Ben: Stellar documents(11:44:33 AM) Myself: congrats, you just made mypresentation(11:44:41 AM) Ben: lol
  8. 8. Todays Learning ProcessPHP Edition● Variables● Storage● Comments● Running Code● Review and Run● If/Else Statement● Loops● Exercises● Database Interaction●“The Knockout” Recipe
  9. 9. PHP SyntaxInstruction separationPHP requires semicolons to be used to separateinstructions (Ruby does not)Ex:$a = “test”; $b = “another test”;CommentingWhile Ruby uses the pound sign to tell the computerto ignore lines of code, PHP uses slashes andasterisks for comments.For Single Line Comments (Double Slash)//This is a commented line$testvar = “hello”;
  10. 10. PHP Syntax (cont.)There may be instances where one may want tocomment out a whole section of code, rather than asingle line. This normally happens when testingdifferent sections or describing a function (multiplesentences needed). To do this, start the commentedarea with “/*” and close it off with “*/”./*This next line will assign the value 7 to a variablebecause 7 is my favorite number. If anyone wants toknow why, they can come and ask me.*/$var = 7;
  11. 11. PHP VariablesSyntax: $<variable name>● Must start with a dollar signEx: $firstname = “Jeremy”;Variable Name● Variable name must begin with a letter or “_”(underscore)Ex:$_fruit = “pear”; //Good$8mile = “slimshady”; //Bad● Variable can only contain alphanumeric charactersand “_”, no spaces allowed, case sensitive ($test !=$Test)
  12. 12. PHP Variables (Cont.)● Same method of assigning strings, integers asRuby has – only slightly different syntax.RubyA = “apple”B = 10PHP$A = “apple”;$B = 10;Remember, PHP requires semicolons to be used toseparate out instructions
  13. 13. PHP Variables (Cont.)● As with Ruby, storage actions are done the sameway, with just a few syntax differences.RubyThree = one + twoFullname = “Jeremy Montoya”PHP$three = $one + $two;$fullname = “Jeremy Montoya”;
  14. 14. Running a PHP script● Without performing the full installation and just learningthe syntax. Simply type in your script and submit to seethe output.http://sandbox.onlinephpfunctions.com/● For full implementation / ability to see graphical output,a .php file will need to be created, with the code writteninside the file. (Ruby = .rb, PHP = .php)● With your .PHP file saved (assuming you haveperformed the steps needed to have PHP installed,alongside a web server (apache, IIS, etc..), simply placethe file in your web directory and access through thebrowser.Ex: http://www.cpap.com/index.php
  15. 15. Review and Run!http://sandbox.onlinephpfunctions.com/
  16. 16. If/Else StatementsReview● There may be scenarios where we want to performcertain actions depending on the value of a variable.This is where If/Else statements come into place.Ex:if( $pet == “cat” ){echo “How unfortunate!”;}else{echo “Good choice”;}
  17. 17. If/Else Statements● Once again, logic is the same, only with syntaxdifferences.RubyIf one == 2puts “equals 2”elseputs “does not equal 2”endPHPif( $one == 2 ){echo “equals 2”;}else{echo “does not equal 2”;}
  18. 18. Loops● Used in programming to execute a block of code agiven number of times, or while a condition is true.● There are a number of different types of loops touse, all which have advantages depending on thetask at hand.● These would include for and while loops
  19. 19. Loop ScenarioLet us imagine we would want to write a piece ofcode that is to be used during the final moments of2013. We would like a countdown to be displayed tothe crowd starting at 10 seconds until midnight. Oncemidnight is reached, a large “HAPPY NEW YEAR!”message will be displayed.
  20. 20. For LoopsFor our “Happy New Year” task...it would look likethis in PHP:for( $i=10; $i > 0; $i=$i-1 ){echo $i;}echo “HAPPY NEW YEAR!”;For loops are constructed different parts, which wewill go over in the next several slides.
  21. 21. For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;}echo “HAPPY NEW YEAR!”;The first part of the loop is the first instruction to berun, before the loop even starts.Typically, it assigns the starting value to the variableinvolved in the loop. In the New Years scenario, itsstarting the counter of at 10 (since we going to becounting down until 0.
  22. 22. For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;}echo “HAPPY NEW YEAR!”;The second part of the loop is the condition that ischecked on every iteration through the loop. It is thedeciding factor in terms of knowing when to stoplooping and when to keep going.In the New Years scenario, the condition is tocontinue the loop while the variable $i is greater than0. Once that condition is violated ($i is equal to 0),then the loop stops.
  23. 23. For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;}The third part of the loop is the instruction to be doneafter each iteration of loop. Its the most importantpart due to the fact it controls the variable finallygetting to an end condition ($i reaching 0).In the New Years scenario, the instruction is todeduct 1 from $i after each iteration since we arecounting down.
  24. 24. For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;}echo “HAPPY NEW YEAR”;The section that lies within the open and closebrackets is the block of code that is to be executedon each iteration.In this scenario, we wanted to display a countdown,so we will simply be displaying out the value of $i tothe screen to emulate this.
  25. 25. Cat Break:what what what what, scratch scratch scratch, meow meow meow
  26. 26. For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;}echo “HAPPY NEW YEAR”;As soon as the value of $i reaches 0, the condition“$i > 0” will be violated, thus exiting out of loop. Now,we will see our final message which is set to showafter the loop has completed.
  27. 27. DANGER: For Loopsfor( $i=10; $i > 0; $i=$i-1 ){echo $i;$i = $i + 5;}echo “HAPPY NEW YEAR!”;101514As with any loops, one must be sure to carefully set up their loop parameterscorrectly, as well as not manipulating the loop variable within the block of code.In this case, everything is setup properly, except for a single line that will add 5to $i during each iteration. This now causes $i to just get bigger and bigger,rather than closer to 0. This will result in what we call an “infinite loop”.
  28. 28. While LoopSimilar to for loops, but with a different structuralsetup. In many cases, this will be used when thenumber of iterations is not known. Generally, therewill be a condition that must be met to terminate theloop. In this example, well play the guessing game.$numberInHead=8;$guess=0;while( $guess != $numberInHead ){//ask the user for a number}echo “ABOUT TIME!”;As you can notice, it took a couple more lines ofcode to achieve what the for loop did, but in manycases, its easier to read for someone else.
  29. 29. While Loop$numberInHead=8;$guess=0;while( $guess != $numberInHead ){//ask the user for a number}echo “ABOUT TIME!”;This acts just like the first parameter in a for loop.We want to start the variable off at its start value, sowe set it to 0 since no guess has been made.
  30. 30. While Loop$numberInHead=8;$guess=0;while( $guess != $numberInHead ){//ask the user for a number....$guess = whateverweaskthemfor;}echo “ABOUT TIME!”;The core of a while loop. One can pretty much saywhat they see out loud to understand whatshappening. “While variable guess is not equal to thevariable $numberInHead”, we will perform whateveris in between the brackets.
  31. 31. While Loop$numberInHead=8;$guess=0;while( $guess != $numberInHead ){//ask the user for a number}echo “ABOUT TIME!”;Just like the for loop, any code within the bracketswill be executed on each iteration. In this case, wewill prompt the user for a number to guess.
  32. 32. While Loop$numberInHead=8;$guess=0;while( $guess != $numberInHead ){//ask the user for a number}echo “ABOUT TIME!”;Alas, the user will finally make the correct guess, andget out of the loop. We can then congratulate themaccordingly.
  33. 33. Exercises
  34. 34. What Will Be Output To TheScreen?for($x=0;$x<=10;$x=$x+1){if( $x < 5 ){echo $x;}else{echo “$x is too high”;}}echo “Done!”;
  35. 35. What Will Be Output To TheScreen?for($x=0;$x<=10;$x=$x+1){if( $x < 5 ){echo $x;}else{echo “$x is too high”;}}echo “Done!”;012345 is too high6 is too high7 is too high8 is too high9 is too high10 is too high
  36. 36. Whats Wrong With This Loop?for( $i=0; $i<5; $i=$i-1 ){echo “Hooray for coding”;}
  37. 37. Whats Wrong With This Loop?for( $i=0; $i<5; $i=$i-1 ){echo “Hooray for coding”;}$i will start at 0 and decrementby 1 each time, thus neversatisfying the condition to exitthe loop, which is for $i toexceed or equal 5.INFINITE LOOP!
  38. 38. Whats Wrong With This Loop?x = 5;while( x > 0 ){x = x – 1;}
  39. 39. Whats Wrong With This Loop?x = 5;while( x > 0 ){x = x - 1;}Shame on you if you didnt get it. This is PHP, whereare all the dollar signs?!!
  40. 40. Database InteractionNow that we have gotten basic conditionchecking and loops out of the way in PHP, wecan now go over how we use this when talking todatabases.
  41. 41. Database InteractionAs a starting example, lets say we have a table named“PlacesTbl” of restaurants in the local area that a groupenjoys going to for lunch. It consists of 3 fields - a uniqueid given to each one, the name of the restaurant and aflag implying if they have gluten free options or not.
  42. 42. Database RequestA page needs to be set up to display to users all the restaurants in the area - in order ofthe restaurants name, and stating whether or not they are gluten free. The SQL statement isthe first thing to set up.SELECT *FROM PlacesTblORDER BY DescriptionRunning this SQL manually before using in your PHP scriptshould always be done so you know its working correctly.
  43. 43. PHP ImplementationNow that we have our SQL statement set up, its now time to add it into a PHPscript and perform the logic to read through the results, and output accordingly.$getPlaces =“SELECT *FROM PlacesTblORDER BY Description”;$resultPlaces = ConnectToDatabase( $getPlaces );This first part of the script assigned the SQL statement to a variable, and thenissue a call to the function which expects an SQL query to be passed over, andin turn - makes the call to the database with it and returns the result. In thiscase, the result is placed in a variable called $resultPlaces.Note: ConnectToDatabase should just be viewed as a function that exists thatsimply will expect an SQL query and will return the results upon calling thedatabase. There is a more in depth topic to go into to explain this.
  44. 44. PHP ImplementationWith $resultPlaces containing the result of our query, its now time to readthrough it and output the information.$rowPlaces = mysql_fetch_array( $resultPlaces );while( $rowPlaces != false ){if( $rowPlaces[FlagGF] == 1 ){echo $rowPlaces[Description] . “ - Gluten Free<br>”;}else{echo $rowPlaces[Description] . “ - Gluten Everywhere<br>”;}//Get next row$rowPlaces = mysql_fetch_array( $resultPlaces );}Ok, first lets explain the mysql_fetch_array function call. This is a function builtinto the MySQL library in PHP. It receives in the variable that is holding theresult, and returns the next row in the results. If there are no rows left to read in,it returns false.Given that we will set our loop variable to the first row and begin the loop.
  45. 45. PHP Implementation$rowPlaces = mysql_fetch_array( $resultPlaces );while( $rowPlaces != false ){if( $rowPlaces[FlagGF] == 1 ){echo $rowPlaces[Description] . “ - Gluten Free<br>”;}else{echo $rowPlaces[Description] . “ - Gluten Everywhere<br>”;}//Get next row$rowPlaces = mysql_fetch_array( $resultPlaces );}We will set the condition to get out of our loop to be once $rowPlaces is set tofalse. This is because once we run out of rows to read, mysql_fetch_array willreturn false.
  46. 46. PHP Implementation$rowPlaces = mysql_fetch_array( $resultPlaces );while( $rowPlaces != false ){if( $rowPlaces[FlagGF] == 1 ){echo $rowPlaces[Description] . “ - Gluten Free<br>”;}else{echo $rowPlaces[Description] . “ - GlutenEverywhere<br>”;}//Get next row$rowPlaces = mysql_fetch_array( $resultPlaces );}In the meat of our loop, we will perform a comparison to see if the gluten freeflag (“FlagGF”) is set to 1. If it is, the restaurants name will be output, alongsidetext stating it is gluten free. If it is not equal to 1, we will perform the sameoutput - but stating its full of gluten.After the output is displayed, we will give our loop variable $rowPlaces its newvalue, by assigning it what mysql_fetch_array now returns. This will prepare itfor the condition check at the beginning of the loop!
  47. 47. PHP ImplementationThe resulting page will look something like this!
  48. 48. The KnockoutPerfect for inducing an idyllic summer nap, The Knockout offers a sweet blend of fruitwith a sharp kick of tequila:2 parts lime juice1 part tequila1 part Midorisplash of simple syrup8 blueberriesCrush blueberries in a bowl with a spoon. Set aside.Combine lime juice, tequila, midori and simple syrup in a tumbler with ice. Shake.Salt serving glass, fill with ice, garnish with blueberries, then pour the strained mixtureon top.Garnish with a blueberries and a sprig of mint.And what do you get...?
  49. 49. Fin

×