BEGINNER PHP Table of Contents

Similar documents
Linked Lists. What is a Linked List?

Slide 1 CS 170 Java Programming 1 Testing Karel

Client Side JavaScript and AJAX

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

MITOCW watch?v=0jljzrnhwoi

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Django urls Django Girls Tutorial

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

The Stack, Free Store, and Global Namespace

MITOCW watch?v=kz7jjltq9r4

MITOCW watch?v=rvrkt-jxvko

Post Experiment Interview Questions

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.


Lesson 4: Who Goes There?

Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1

Chapter 4 Lab. Loops and Files. Objectives. Introduction

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

1 Getting used to Python

NetLogo Lab 3 Tutorial: Finding Peaks

PHP. Introduction. PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server

WP EBOOKS Creating A WordPress Network

Class #7 Guidebook Page Expansion. By Ryan Stevenson

MITOCW watch?v=flgjisf3l78

MITOCW watch?v=w_-sx4vr53m

CS103 Spring 2018 Mathematical Vocabulary

We are assuming you have node installed!

Creating a Network. WordPress 3.1 (and up)

If you re serious about Cookie Stuffing, take a look at Cookie Stuffing Script.

Popcorn's ini Tutorial

MITOCW ocw apr k

PROFESSOR: Well, yesterday we learned a bit about symbolic manipulation, and we wrote a rather stylized

What's the Slope of a Line?

Module 6. Campaign Layering

MITOCW ocw f99-lec07_300k

Basic Fiction Formatting for Smashwords in OpenOffice L. Leona Davis. Copyright 2012 L. Leona Davis All Rights Reserved

Developing Online Databases and Serving Biological Research Data

Blitz2D Newbies: Definitive Guide to Types by MutteringGoblin

TourMaker Reference Manual. Intro

HELPLINE. Dilwyn Jones

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

System Guide

BEGINNERS GUIDE TO DESIGNING YOUR ONLINE SHOP

MITOCW watch?v=9h6muyzjms0

Smart formatting for better compatibility between OpenOffice.org and Microsoft Office

PROFESSOR: So far in this course we've been talking a lot about data abstraction. And remember the idea is that

MITOCW watch?v=zm5mw5nkzjg

MITOCW watch?v=se4p7ivcune

B - Broken Track Page 1 of 8

Fruit Snake SECTION 1

Chris' Makefile Tutorial

An attribute used in HTML that is used for web browsers screen reading devices to indicate the presence and description of an image Module 4

Troubleshooting Maple Worksheets: Common Problems

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Google Docs Website (Sign in or create an account):

Slide 1 Java Programming 1 Lecture 2D Java Mechanics Duration: 00:01:06 Advance mode: Auto

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

USING DRUPAL. Hampshire College Website Editors Guide

Lesson 3 Transcript: Part 1 of 2 - Tools & Scripting

PHP & MySQL For Dummies, 4th Edition PDF

Intro. Classes & Inheritance

Contents Release Notes System Requirements Using Jive for Office

Interactive Web Application

Java Programming Constructs Java Programming 2 Lesson 1

Introduction to JavaScript and the Web

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

MITOCW watch?v=4dj1oguwtem

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

D - Tic Tac Toe. Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9

15-110: Principles of Computing, Spring 2018

JAVASCRIPT - CREATING A TOC

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

The following content is provided under a Creative Commons license. Your support

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Programming with Haiku

CaseComplete Roadmap

The following content is provided under a Creative Commons license. Your support

Azon Master Class. By Ryan Stevenson Guidebook #11 Squidoo Marketing

Azon Master Class. By Ryan Stevenson Guidebook #5 WordPress Usage

--APOPHYSIS INSTALLATION AND BASIC USE TUTORIAL--

Lab 2: Conservation of Momentum

Assignment 1: Evil Hangman

PHP. Interactive Web Systems

Contents. What's New. Version released. Newsletter #31 (May 24, 2008) What's New New version released, version 4.3.3

Using X-Particles with Team Render

Everything you always wanted to know about Fonts*

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

C# Programming Tutorial Lesson 1: Introduction to Programming

Math Modeling in Java: An S-I Compartment Model

Fortunately, you only need to know 10% of what's in the main page to get 90% of the benefit. This page will show you that 10%.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Skill 1: Multiplying Polynomials

JQuery and Javascript

My Favorite bash Tips and Tricks

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

Microsoft's latest OS is a lot better than its predecessor, but it still has some annoying quirks. We help you solve them.

Transcription:

Table of Contents 4 5 6 7 8 9 0 Introduction Getting Setup Your first PHP webpage Working with text Talking to the user Comparison & If statements If & Else Cleaning up the game Remembering values Finishing your game....4.5.6.7.8.9.0

Introduction

Getting Setup These Sushi Cards will help you learn to build webpages using PHP, a very popular programming language that's used to build websites like Facebook and Wikipedia. You can combine it with HTML (and check out the HTML Sushi Cards if you don't know how to code HTML yet!). First, you're going to need somewhere to code! PHP needs a few different pieces in place to make it work and, if you're going to release a website later, you'll eventually need to learn how to set that up. For now, though, let's just get going quickly by using Cloud 9, an online editor that will do all the setup for you! Check it out at dojo.soy/php-edit. You can use your GitHub or Bitbucket account to sign in if you have one. Otherwise, sign up with your email address. 4 Choose "Create a new workspace" and fill it in as follows: Workspace name: beginner-php Description: My first PHP website Make sure that Hosted workspace is selected Choose a Private workspace Skip over the Clone from Git or Mercurial URL you don't need to clone anything Choose the PHP, Apache template

Getting Setup 5 Now just click on Create workspace and you're all set! 6 Once your workspace is up and running, you'll notice you've been given a few files, which you can see in the sidebar. 7 You're going to need to create a new file to put all your code in. You can do this by choosing File > New File in the menu. 8 Once the file is opened, you can save it by choosing File > Save As and giving it a name. Save this one now as index.php 9 You're ready to make your first PHP webpage! 4

Your first PHP webpage Time to start coding your first real PHP webpage! You're going to start with one of the classics, saying "Hello!" to your user and, by the end of these cards, you'll be making a number guessing game for the user to play! So, to begin with, every PHP webpage will have at least a little bit of HTML in it. Start by making a really basic one by typing this code into your index.php and saving it. <!DOCTYPE html> <html> <head> <title>my PHP webpage</title> </head> <body> This is just HTML text, it is not clever like your PHP text will be! </body> </html> The things in the angle brackets ( < > ) are called HTML tags and you'll be coming across a few of them in these cards. There are lots more, though, and you can learn about them in the HTML Sushi Cards and in loads of other places online! 5

Your first PHP webpage Run that page and you'll see a basic HTML page. To begin with, your PHP page is going to look pretty similar, but very quickly you'll be using the power of PHP to do things that HTML never could alone! To get started, replace that HTML text with some special PHP code. <body> <?php echo "Hello everyone! This is my first PHP program!";?> </body> Notice that PHP code always appears inside <?php and?>. This is so the computer can tell which parts are PHP and which parts are HTML. Using these, you can put PHP code anywhere inside the HTML. Also, notice that the PHP code always ends each line with a semicolon ( ; ). This is so PHP knows to end this command and start another. If you forget to do this, PHP can get very confused. 4 Now save and run your PHP file. Congratulations! If it all worked, you've just written your first PHP webpage! 6

Working with text Now it's time to start working on your game! The first thing you're going to need is to teach the player the rules. You might want to change things like the smallest and biggest numbers, or the number of guesses you're going to give the player. If you wrote out the rules with plain HTML, you'd have to go back and re-write them every time you changed any of those things. You don't need to do that, though. You can use PHP and variables to include the numbers as part of your text! First, you're going to need to to update your text, so change the PHP code on your page to this: echo "I've picked a number between and 9<br />"; echo "You will have 5 chances to try to guess my number!"; The <br /> is a piece of HTML that tells the browser to start a new line after it. You can put any HTML inside your PHP and it will be treated exactly as if it had been written as HTML. Notice that you're using double quotes ( " ) around your text instead of single quotes ( ' ), for two reasons: PHP will get confused if you use an apostrophe inside of single quotes. Try it and see! What happens, and why? PHP will do something special inside of double quotes that it won't inside of single quotes, which you'll see below. 7

Working with text Now it's time for you to start adding variables! These are labels that you can use to store values, like a string of text or a number. PHP remembers those values and lets you use the values later by using their label. This lets you set a value once and use it loads of times in your program. In PHP, all variable names start with a dollar sign ( $ ) and are usually written in camelcase, where the first word starts with a small (lowercase) letter, there are no spaces, and any later words start with capital (uppercase) letter. Put this line in, inside the <?php but before the echo lines $minvalue = ; $maxvalue = 9; $guesses = 5; All of these variables are numbers, but you'll be working with text variables later. 4 Now, update your two echo lines so they look like this: echo "I've picked a number between {$minvalue and {$maxvalue<br />"; echo "You will have {$guesses chances to try to guess my number!"; Notice the curly braces ( { and ) around the variable names to tell PHP not to treat them like regular text! 5 Run your program and see what happens. Then try changing the values of some of the variables and run it again. Just make sure to set everything back to the way you've got it here before moving on! 8

Talking to the user Ok, so you can get information from a variable and show it to the player with echo, but how do you get information from the player? After all, this is a guessing game, so you need some way to collect their guesses! You're going to use a combination of HTML and PHP to do this. The HTML you'll be using is going to be new, even if you've already done the HTML Sushi Cards, since they don't use many forms and your PHP programs will probably use a lot of them. You can see them on almost every website you use the internet and the code for them is pretty easy! <form method="get"> Your guess: <input type="text" name="guess"/> </form> A HTML form is a simple idea: controls like text boxes, drop-down menus, check boxes or buttons are used to collect information from users and send that information to your PHP program. Sometimes, responses are sent to the users. You'll be sending responses in your games. Now, time to add a form to your page! So you can use PHP variables and other code in creating your form, you're going to use echo statements to create it, instead of just typing the HTML into the file. So, add the following below your two existing echo statements: echo "<form method="get">"; echo "Your guess: <input type="text" name="guess"/>"; echo "</form>"; Run this code and see what happens! 9

Talking to the user 4 Well, that didn't quite work right, did it? Any idea why? It's because of the double quotes in <form method="get">. PHP isn't smart enough to recognise that they are part of the HTML tag; it reads them as the end of the string of text that echo is trying to insert into the page. After that, it's looking for a semicolon ( ; ) but instead it finds g and gets very confused! This kind of problem can come up quite often either because you've forgotten which kind of quotes to use or you're copying from another of your programs and used quotes differently there. Luckily, it's very easy to fix. Just put a backslash ( \ ) in front of your all your double quotes (don't forget the ones in the input tag!) like this, to escape the normal rule of ending the string! echo "<form method=\"get\">"; 5 Run the code again! Now you've got somewhere for your user to put their text! Type something in and press the enter key. Watch the page URL in the browser and notice what changes! 0

Comparison & If statements The text that appeared on the end of the URL is called a query parameter and you can have loads of them on the same URL. The form automatically added one (because you set method="get" ), but you could just as easily type them in, separated by semicolons. PHP reads the end of the URL for the page it's loaded on and turns all the query parameters into something called a key, value array. You don't need to know exactly what that is right now, we'll go into it in a later Sushi Card series. What you do need to know is how to get values out of it. All you need to do to get a value out of the array is pass in the key of a value that's in there. Since your form adds the guess field, that's the one you'll be looking for. You'll want to assign that value to a playerguess variable, so add this line just before all your echo lines: $playerguess = $_GET['guess']; Now, remind the player what their last guess was by adding another echo just before the input form: echo "Your last guess was {$playerguess.<br />"; Run the code. Now you're taking input from your player and giving it back to them. Very cool!

Comparison & If statements 4 Try removing all the query parameters from the URL and reloading the page. Notice that you now get "Your last guess was." That's not ideal. What you want to happen is: Check if there's a value (maybe they haven't made a guess yet) if so, show the message about the last guess 5 PHP can figure all this out and do it for you! You just need to use an if statement. An if statement uses a test (in brackets), that has an answer that's either true or false and, if it's true, a piece of code to run. You can do this to check if your variable contains anything like this: if(!empty($playerguess)){ echo "Your last guess was {$playerguess."; Here empty() is a special piece of PHP that checks whether the variable inside its brackets has a value and answers either true if it doesn't or false if it does. The! before it reverses this answer, turning a true into a false and a false into a true. So what this code says is: "If there is not no value in $playerguess, then print out Your last guess was [the value of player guess]." Replace echo "Your last guess was {$playerguess."; with the code above and test it with and without answers to see it working.

If & Else Now that you know how to use if statements, you can start writing the code to get your game to run! You'll deal with using a random number in a later card, but for now just add another variable up at the top with all the others to set your "secret" number, like this: $secretnumber = 5; What you want to do now is compare the player's guess with the secret number, and tell them if they guessed correctly. To compare one value to another and get a true or false result, you use two equals signs ( == ). If the values on either side are the same, then the result is true; otherwise, it's false. Here's how you'd check the player's answer in your PHP: if($secretnumber==$playerguess){ echo("<br />That's right! I was thinking of {$secretnumber!"); Add this code in (after those variables' values are set!) and then run the program. Try guessing correctly (i.e. 5) and incorrectly.

If & Else Have you noticed a few issues with what's happening here? For one thing, the player is still asked to pick a number even when they've won the game! You can fix that, though, by using else statements, after your if statements. You can't use else on its own, it only runs the code inside it if the test on the if statement just before it was false. So, to only show the form for the next guess if the player has not yet guessed the secret number, you need to add an else on to your if from above and move all the form code into it, like this: if($secretnumber==$playerguess){ echo("<br />That's right! I was thinking of {$secretnumber!"); else{ echo "<form method='get'>"; echo "Your guess: <input type='text' name='guess'/>"; echo "</form>"; 4

Cleaning up the game It doesn't make sense to give the player the instructions on how to play every single turn. However, it would be useful to tell them how many guesses they have left. To do this, you'll need to create another variable, guessesleft and add it to your file: $guessesleft = $guesses; Note that because you are setting this variable to the value of another, it must be declared after that variable. Next, take the rules echo code and stick it into an if that checks if the number of guesses the player has left is equal to the number they started with. If it is, then you know it's the first turn and you can show them the rules. If it's not, then tell them how many guesses they have left. if($guessesleft==$guesses){ echo "I've picked a number between {$minvalue and {$maxvalue<br />"; echo "You will have {$guesses chances to try to guess my number!<br />"; else{ echo "You have {$guessesleft guesses left.<br />"; 5

Cleaning up the game If you run this code and play through it a few times, you'll notice that the number of guesses never goes down! There are two reasons of that, and you'll solve them one at a time. The first is that you never decrease the value of guessesleft! There are two things you need to do to make this happen and you'll go through both of them on this card. First, you need to check if the player made a guess and, if so, set guessesleft to one less than the current value. You already have the test for making a guess, since you check for a guess before deciding whether to show "Your last guess was...". You can just update that code to include a second line that decreases guessesleft, like this: if(!empty($playerguess)){ echo "Your last guess was {$playerguess."; $guessesleft = $guessesleft - ; 4 Now it's important to keep an eye on the order of your code. If you run this code as written, you'll notice the count of guesses still doesn't drop! This is because the echo code that prints the value of guessesleft runs before the code that changes that value! All you need to do is move (cut and paste) the code so it comes just after all your variable declarations at the start and things should work fine. Do that now and try running it again. 6

Remembering values You'll notice that now the count of guesses does go down to 4, but it never goes any lower! Any idea why? It's because of the way PHP works: Every time the page loads, the program runs again from the start, with no memory of the last time it ran! That means it always resets the value of guessesleft to 5 and then, if a guess was made, subtracts. So, what you need to do here is store that value somewhere and pass it into the program the next time it runs. Well, you already have something like that: the form on the web page! You can write the current value of guessesleft into the form and read it back out from $_GET later. Start with the writing, by updating your form creation code to look like this: echo "<form method='get'>"; echo "Your guess: <input type='text' name='guess'/>"; echo "<input type='hidden' name='guessesleft' value='{$guessesleft'/>"; echo "</form>"; The type of the field is "hidden", so it won't be visible, but will be sent in on the URL. The value is set to the current value of 'guessesleft'. 7

Remembering values Now you need to pick up the value you've saved and write it into guessesleft. This gets a little complicated, since there won't always be a value in the URL (the first time the game is run, for example). So you need to replace the current line $guessesleft = $guesses with this: $guessesleft = $_GET['guessesLeft']; if(!isset($guessesleft)){ $guessesleft = $guesses; This code tries to get the value from the URL and, if it doesn't find it, leaves guessesleft empty, which causes the code in the if statement to run, filling it with the value of guesses. The reason we didn't use empty here is because empty will give a false if the value is 0, which is going to happen here, when the player runs out of guesses. Try running the program again and you'll see that it all works now! You may have noticed one last problem: The game doesn't end when you run out of guesses! We'll look at how to fix that, and how to use a secret number that actually changes, on the next card! 8

Finishing your game First, let's look at making the player lose the game. This needs to happen when they've used their last guess up, so when $guessesleft == 0. When this happens, keep showing them their last guess, and that they have no guesses left, but not the form or the rules. To make that happen, you'll need to use a new bit of code: elseif. As you might have guessed elseif is a combination of the else and if statements. Like else, it only happens if the condition in an if statement is false, but like if it has its own condition. You can use as many elseif statements as you want, but only the first one that has a true condition will run. If none of them are true, the else statement will run, just like with a regular if. To get your game to tell the player they've lost, you just want to add an elseif to the code that checks their answer and shows them the for to, if they have now guesses left, show them a different message instead, like this: if($secretnumber==$playerguess){ echo("<br />That's right! I was thinking of {$secretnumber!"); elseif($guessesleft==0){ echo("<br />Game over! You lose!"); else{ echo "<form method='get'>"; echo "Your guess: <input type='text' name='guess'/>"; echo "<input type='hidden' name='guessesleft' value='{$guessesleft'/>"; echo "</form>"; 9

Finishing your game Ok, now you have a game where the player can guess a number, get a certain number of tries and be told if they win or lose. Very cool! However, right now, that number is always 5... which is less cool. PHP is pretty good at coming up with random numbers, though. To use a random number instead you just need to change the code for secretnumber like this: $secretnumber = $_GET['secretNumber']; if(!isset($secretnumber)){ $secretnumber = rand($minvalue, $maxvalue); The rand is a function that takes two numbers and gives you back a random number between them. You're using minvalue and maxvalue here so you only have to change those numbers in one place and they'll change everywhere in your code! 4 Now you need to make sure that it's the same random number throughout the game. It wouldn't be fair to keep changing it on your player! You already know how to do this one though: a hidden form field. Just add this to your echo code for the guessing form (you won't need to keep storing it if the player wins or loses!). echo "<input type='hidden' name='secretnumber' value='{$secretnumber'/>"; 5 Now, try to play your game! 6 How else could you use this code? You've got all the pieces here to make a quiz or an interactive story, where you keep score, ask different questions on each page and even send the player in different directions based on their answers! 0

Finishing your game