Tutorial Parham's php tutorial

Status
Not open for further replies.
A

Ardenn

Parham's PHP Tutorial 01 - installing a server

The reason I want to have people set up their own local servers (in windows) is because it makes testing your scripts so much easier.  With a local server, there is no need to upload anything anywhere, your script can be edited and tested on the spot.  To keep with the flow of simplicity with these tutorials, I've decided not to make everyone download every single component to make their own server.  Instead I've decided to get everyone to download an all-in-one package that will install the server for you , no fuss.

You will all need to download and install the file located at:
http://www.easyphp.org/telechargements/dn.php?F=easyphp1-6.php3

EasyPHP will install apache, php, mySQL, and phpMyAdmin all for you with a few simple clicks.  The program itself is originally in French, and the installation is all in French, but it's just a matter of clicking "yes", "Suivant", "Oui", "Suivant", "Suivant", "Installer", and let it install.

You should now have installed the EasyPHP server on your computer.

To begin testing it you can do the following:
Click on Start > Programs > EasyPHP > click on the easy shortcut EasyPHP

You should see a big E in your system tray and a blinking red dot.  If the red dot isn't blinking, right-click on the E and click on "start".  The red dot should NOW be blinking if it wasn't earlier.  Right-click on the E again and click on "configuration".  The textbox at the bottom where it says "mySQL arguments" should be changed to "--skip-name-resolve --language=english" (replaced "french" with "english").

All the files you want to test should be placed in the following directory:
C:\Program Files\EasyPHP\www

Start by placing the following file in there (you don't need to know what this does right now):
phpinfo.php
Copy to clipboardCode:
<? echo phpinfo(); ?>

If your server is running (the little red dot on the E should be flashing), then you can open up the browser of your choice and go to this URL:
http://127.0.0.1/phpinfo.php

If you see HTML, and information pertaining to PHP, then congratulations, you've got a local server running on your computer.

Let's test something else, phpMyAdmin.  phpMyAdmin, if you don't already know, is a frontend for mySQL in PHP which allows you to work with tables and databases.  Try going to the following URL and see whether you see HTML or not:
http://127.0.0.1/mysql/

If you saw HTML and not some error, then this test has also passed and you've got yourself a little server to test your scripts on.  A few notes:

All scripts you create will go in the "C:\Program Files\EasyPHP\www" directory.  To see your scripts you have to go to the following URL: "http://127.0.0.1/(your filename here)".

A few examples:
To edit: C:\Program Files\EasyPHP\www\file.php
To test: http://127.0.0.1/file.php

To edit: C:\Program Files\EasyPHP\www\new directory\file.php
To test: http://127.0.0.1/new directory/file.php (the %20 should be added automatically by your browser, a space is sufficient)

Other side notes:
You can create your PHP scripts in any simple text editor which won't add formatting like notepad or wordpad.  Your PHP files MUST have a "php" extension.
 
A

Ardenn

Parham's PHP Tutorial 02 - php basics

The greatest thing about PHP is the fact that it's a web-specific language.  The language is specifically intended to be used for internet development which means you get many features which makes it easier for you to work with the language on the internet.  One of the greatest things about PHP is how you can mix and match PHP code with HTML code.

If you're familiar with HTML, you know what all HTML tags (special words that format an HTML webpage) are encased in <s and >s.  For example, to bold a string, you would sandwich it between the <b> and </b> tags.  PHP doesn't quite work this way.  Instead, all PHP code goes right inside a huge single tag - the PHP tag.

The PHP tag can look one of two standard ways (there are other alternatives which are rarely used):
<?php ?> - the long version of the tag
or
<? ?> - the short version of the tag

Anything inside these tags will be recognized as PHP code, anything outside these PHP tags will be recognized as plain HTML.  A simple example is the following (again, you don't need to know exactly what the following does right now).  Save the following file into your "www" directory and run it by going to "http://127.0.0.1/basic.php".

basic.php
Copy to clipboardCode:
Code:
<html>
<head>
<title></title>
</head>
<body>

<? print 'php code here'; ?>

</body>
</html>
Some people don't like this method and will instead encase the entire file's contents inside PHP tags and use functions inside the PHP language to output their HTML code.

The other basic thing I want to cover in this lesson is how to "comment" in PHP.  A comment is a way for you to insert explanations of code in plain English which will in NO way affect your program.  Comments help other programmers understand code you've written.  Comments can be written in several ways (save and test the following file):

comments.php
Copy to clipboardCode:
Code:
<?
print 'hello<br>'; //this is a comment, this line prints "hello"

print 'how are you?<br>'; #this is also a comment, this line prints "how are you?"

print 'I am good thank you<br>'; /* this is a multi-line comment
                                    and can span several lines */
?>
Anything after "//" or "#" on a line is interpreted as a comment and will not be used.  Anything between the "/* */" characters will also be interpreted as comments.  Comments can be stuck anywhere in between lines of code or after code on a line, but not before except the "/* and */" comment because then all code after the comment will be interpreted as comments too.

For example:

Copy to clipboardCode:
Code:
<?
print 'hello<br>'; //this is a comment, this line prints "hello"
//here is another comment tag
print 'how are you?<br>'; #this is also a comment, this line prints "how are you?"
#more comments inbetween
/* a comment before with this type of comment tag */ print 'I am good thank you<br>';
/* this is a multi-line comment and can span several lines */
?>
As you've already guessed by now "print" outputs text to the browser, something we'll be going over in our next lesson anyway.
 
A

Ardenn

Parham's PHP Lesson 03 - variable/array/function definitions

This lesson I thought I would get a little technical (without getting TOO technical) with definitions of a few words you'll coming across regularly in these lessons.

What is a variable?
A variable is something that can hold a dynamic value.  You can think of a variable as a box and its contents as the variables value.  The stuff inside the box can be changed; stuff taken out and replaced by other stuff.  This is exactly how you should think of a variable, as something which can always change to your needs.  A variable has two parts, a name and a value.

What is an array?
An array is something that can hold several dynamic values.  Very much like a variable, think of an array as a BIG box which can hold several similar objects.  The stuff inside this big box can be changed; stuff taken out and replaced with other stuff or more stuff can be added to this big box.  If that's a little hard to picture, think of an array as simply a list of values where more values can be added or existing values can be modified or removed.  An array has two parts, a name and a value.

What is a function?
A function is exactly what its dictionary definition says: The action for which a person or thing is particularly fitted or employed.  A function is a set of code which does a particular task.  A function has three parts, a name, information you give it, and information it returns.

Those of you who are very eager to explore the PHP language should get yourselves familiar with the PHP documentation and API located at http://www.php.net/manual/en/.  This is the website where you can find all of PHP's built-in functions and features.  The site will also help you with basic syntax.  The great thing about using the online documentation at PHP's website is that there is a wealth of user comments for everything to help clear up misunderstandings you might have.

A few things you might want to read up on for the next lesson would be the following two sites:
http://www.php.net/manual/en/function.print.php
and
http://www.php.net/manual/en/function.echo.php
 
A

Ardenn

Parham's PHP Lesson 04 - setting and printing variables

I've explained to you what a variable is; now let me show you how to create a variable.  A variable, as stated in the previous lesson, is something which can hold a dynamic value.  A variable is distinguished from other things because it starts with a dollar sign.  For example, "$name" could be a variable which would most likely hold the name of something, someone, or someplace.  Variable declaration requires the use of the "assignment operator" ("=") which will assign a value to our variable.

What you assign to a variable also requires a little thought.  If you're assigning a number to a variable, then quotes are not required.  If you're assigning a string to a variable, then quotes are required.  The two basic types a variable can be are "string" and "number" and PHP understands which one you want with the presence/absence of quotes.


Code:
$name = 'Parham'; //this will assign 'Parham' to the variable $name, note the quotes

$number = 12; //this will assign 12 to the variable $number, note the absence of quotes

$othernumber = '12'; //this will assign '12' to the variable $number, not the presence of quotes, the variable is now interpreted as a string, not as a number
If you literally want to use quotes in your strings then they will have to be "escaped" so PHP will not get confused:



Code:
$phrase = 'hi my name\'s Parham'; //by placing a \ in front of the single quote, the variable will now be set properly and you will not receive errors
Here is how PHP will read the above, step by step:
-Interpret right side of assignment operator first
-see a single quote, recognize this as a string, continue until you find another quote
-found a quote, but it's escaped, continue looking for another quote
-found another quote
-assign everything from first quote to last quote ('hi my name\'s Parham') to the variable $phrase
-found semi-colon, this line is done with, can now move onto the next line (the semicolon tells PHP when to move onto the next command (usually on the next line).

Hopefully you're following everything well, I've tried to keep everything as simple and clear as possible.  Please don't hesitate to post questions.

The next thing we'll discuss is variable interpolation.  The word "interpolation" means to insert or introduce between other elements or parts.  Variable interpolation therefore means to use one variable inside another.  Let us for example declare two variables:


Code:
$name = 'Parham';
$age = '19';
To use these two variables and declare a whole new third variable I'd do this:


Code:
$phrase = "$name is $age years old";
Note the use of double quotes.  Doubles quotes and single quotes have very different meanings when it comes to declaring variables.  Single quotes take everything literally, meaning no variables are ever interpolated whereas double quotes interpolate variables:


Code:
$phrase1 = '$name is $age years old'; //this would literally be assigned to $phrase

$phrase2 = "$name is $age years old"; //this would find the values of $name and $phrase and stick them in
print() and echo() are two PHP language constructs which allow you to output information to the user.  It is best to demonstrate these two functions without giving too much explanation.  Here is an example that will not only show you everything we've learned about variables above, but it will also show you examples of the print() and echo() functions:


Code:
<?

$name = 'John';
$age = '19';
$location = 'Canada';

//print examples
print('Hello'); //outputs "Hello" to the user
print 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
print 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                               //this will print "Hello how are you?"

//-----------------------------------------------

//echo examples
echo('Hello'); //outputs "Hello" to the user
echo 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
echo 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                              //this will print "Hello how are you?"
echo 'Hello',' how are you?'; //the "," can also be used with echo() to output a string
                              //this will print "Hello how are you?"

//-----------------------------------------------

//print with variables
print $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//echo with variables
echo $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

echo $name , ' is ' , $age , ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//print and echo with variable interpolation
print "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

echo "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

?>
It is also worth mentioning that you only need to escape characters that you use to surround the entire variable's value with.  For example:

Code:
print "I said \"hi\""; //need to escape the double quotes around "hi"
print 'I said "hi"'; //don't need to escape the double quotes around "hi"
print "I said 'hi'"; //don't need to escape the single quotes around 'hi'
print 'I said \'hi\''; //need to escape the single quotes around 'hi'
There are speed differences between single quotes and double quotes and also between the echo() function and the print() option.  First you should know that using concatenation operators (".") with print() and (",") with echo() is MUCH faster than interpolating and letting PHP figure out where the variables are.  You should also note that echo() is slightly faster than print() because print returns a "true" value (in the form of "1") to tell you it has printed.

For more information, please read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
 
A

Ardenn

Parham's PHP Tutorial 05 - arrays

As stated earlier, an array is something that can hold several dynamic values.  This is a case when an array would do more justice than a set of variables:


Code:
$person1 = 'Parham';
$person2 = 'Jeff';
$person3 = 'Joseph';
$person4 = 'Unknown';
$person5 = 'David';
$person6 = 'Alex';
Why should we have to keep track of all these variables when they all hold the same type of information?  An array can be set using the array() function.  Much like a variable, an array name also starts with a dollar sign.  A simple recode of the above will produce this code (and give you an example of how to declare an array):


Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');
Notice instead of declaring a new variable for each name, I've created an array called $people (note the plural word also) and put all the names inside that one array.  Here is how PHP interprets the above array:

Code:
$people
[0] => 'Parham';
[1] => 'Jeff';
[2] => 'Joseph';
[3] => 'Unknown';
[4] => 'David';
[5] => 'Alex';
The numbers on the left are known as the "keys" of the array and help keep track of the "values" on the right, inside the array.  The "=>" operator is used to associate the "keys" with the "values" inside the array.  Arrays by convention begin with the 0 "key".  If you have 200 values inside an array, the first "key" will be 0 and the last "key" will be 199.

If you're a programmer that has some OOP language background like Java or C or you don't like using the array() function, you might be more comfortable declaring your arrays like this:


Code:
$people[] = 'Parham';
$people[] = 'Jeff';
$people[] = 'Joseph';
$people[] = 'Unknown';
$people[] = 'David';
$people[] = 'Alex';
Declaring your arrays like this or with the array() function makes absolutely no difference, this is purely a matter of what you're comfortable with.  If you actually look at the above array() function example, you might realize how similar the above and this example actually are.  This method of declaring an array also exists because PHP uses it internally for HTML form parsing (we'll learn about this in a later lesson).

We [now] know that keys start from 0, this is very important.  We'll now talk about how to retrieve particular values inside these arrays.  Again, I'll show by example rather than try to explain in too much detail:


Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex'); //declare the array
print $people[0]; //prints "Parham", the first value in the array
print $people[4]; //prints "David"...
print $people[5]; //prints "Alex"...
Easy enough?  I want to take a quick sidestep then and give a quick lesson on printing again.  To print "newlines" (when you press "enter" on your keyboard, the cursor goes to a new line and creates a new hidden character called the "newline" character), you have to use "\n" in your strings.  If you wish to use the "\n" character to skip to the next line, you have to use double quotes.  Example:


Code:
print "Parham\nteaches\nPHP"; //remember to use double quotes when using the \n characters
That will print:
"Parham
teaches
PHP"

Let's go back to arrays now (sorry about that, the last lesson should have covered the "newline" character as well).  If you want your arrays to be a little more in depth, you can assign your own keys to the array values (This creates associated-arrays because you associate keys with values yourself).  For example:


Code:
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
This would produce:
$people
['person1'] => 'Parham';
['person2'] => 'Jeff';
['person3'] => 'Joseph';
['person4'] => 'Unknown';
['person5'] => 'David';
['person6'] => 'Alex';

REMEMBER that the keys have to be unique; any values that have the same key will be replaced by the most recent value added.  To access specific elements inside our array, we can do this (again by example):


Code:
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
print $people['person1']; //prints "Parham"
print $people['person5']; //prints "David";
print $people['person6']; //prints "Alex";
And that's about it for declaring arrays (sorry about the sidetrack to printing "newlines").
 
A

Ardenn

Parham's PHP Tutorial 06 - operators

We've already discussed two operators in our lessons up to this point.  The first one and probably the most important operator we discussed was the assignment operator ("=").  This operator allowed us to assign values to variables and arrays (which we recently learned about).  The other operator we discussed was the array operator ("=>") which allowed us to match array "keys" to array "values".  There are also the "concatenation" operators which combine strings.  Here are examples of them all:


Code:
$variable = 'name'; //assign "name" to the variable $variable using the assignment operator
echo "$variable\n"; //remember the "newline" character I taught last lesson...

Code:
$array = array('first' => 'something','second' => 'something else'); //assign array keys and values
print $array['first'] . "\n"; //print the array value with key "first"; concatenation operator used
/* there is also a lesson to be learned here, you can't print arrays inside double quotes like you would variables.
You either have to assign the specific array element to a variable and print that or use the concatenation method
which we learned in lesson 4 */
Pay particular attention to the above comments as some of them were not discussed in previous lessons.  In this lesson I'll go over some other common operators you might want to use.

The arithmetic operators are used to do simple mathematical operations such as addition, subtraction, multiplication, and division.  Here are examples of each:


Code:
$number1 = 12;
$number2 = 3;

$answer = $number1 + $number2;
echo "$answer\n"; //prints 15
$answer = $number1 - $number2;
echo "$answer\n"; //prints 9
$answer = $number1 * $number2;
echo "$answer\n"; //prints 36
$answer = $number1 / $number2;
echo "$answer\n"; //prints 4
A few other common operators you will find yourself using often are the following:

Here is a combination operator, concatenation and assignment in one.  This operator takes the original string and adds a new string onto it.


Code:
$string = 'hello'; //assign our original string
$string .= ' there'; //concatenate a new string onto it using the ".=" operator
echo "$string\n"; //prints "hello there";
Here is a combination operator, addition and assignment in one.  This operator takes the original number and adds a new number to it.


Code:
$number = 12; //assign our original number
$number += 3; //add a new number to it using the "+=" operator
echo "$number\n"; //prints "15"
That's about it for this lesson.  There really isn't much to teach about operators, you use them as you need them.  And if you don't know if what you want exists, you just check the PHP documentation.

Check out PHP's documentation for explanations of all the operators:
http://www.php.net/manual/en/language.operators.php
 
A

Ardenn

Parham's PHP Lesson 07 - control structure, if statement

In this lesson I'll be discussing control structures.  What is a control structure you might ask?  Well let's begin with how PHP reads your code.  PHP reads code linearly, meaning it'll start from the first line in the program and move on as each line is successfully executed.  PHP knows to move onto the next line when it sees the semi-colon.  Control structures help you break out of this linear motion, they let you control what line PHP should process next.  To give you a basic example if you've been programming for a while, in older languages for example, the "GOTO" command was and example of a control structure.

The first control structure you need to get very acquainted with is the "if" statement.

The syntax of the "if" statement goes as follows:


Code:
if (first expression) {
//if the first expression is true
} elseif (second expression) {
//if the second expression is true
} else {
//if none of the above expressions are true
}
Control structures usually involve some sort of comparison as the expression.  This is where the comparison operators come in handy.  If you didn't already read the comparison operator's documentation located at http://www.php.net/manual/en/language.operators.comparison.php, please take a moment to read it.

Comparison operators compare values (or types) in two (or more) variables and return either "true" or "false".  Some of the common control statements you need to know about are:

"==" - equal in value
"!=" - not equal in value
">" - greater than
"<" - less than
">=" - greater than or equal to
"<=" - less than or equal to


Code:
$number1 = 12;
$number2 = 3;
$number3 = 36;
$number4 = 50;
$number5 = 3;

"$number1 == $number2" will return false
"$number1 != $number2" will return true
"$number1 == $number3" will return false
"$number2 == $number5" will return true
"$number1 > $number3" will return false
"$number3 < $number4" will return true

Code:
$name1 = 'Parham';
$name2 = 'Joe';
$name3 = 'Parham';

"$name1 == $name2" will return false
"$name1 != $name2" will return true
"$name1 == $name3" will return true
Using the above information now, we can construct our "if" statements.  "if" statements are read very much like how you'd speak regular English when asking yourself a question.  For example, "if the color of the ball is red, put the ball in the first box, otherwise put it in the second box", would be coded in the following way:


Code:
$ball = 'red';
if ($ball == 'red') {
  $box1 = $ball;
} else {
  $box2 = $ball;
}
That's a simple enough example.  Let me give you a play-by-play of it.  We declare our variable on the first line, a simple string.  The second line is where all the work is done.  If you want to read it out it'll come out like this: "if the ball is red in value".  That line returns true because the value of $ball is "red", therefore it'll execute the first block and put the $ball variable in the $box1 variable.  Now if the ball wasn't red, the $ball variable would be assigned to the $box2 variable.  Another same type of example:


Code:
<?
$ball = 'purple'; //try changing it to "yellow", "blue", "green", "purple", or any other color
if ($ball == 'red') { //if this expression returns true, run the block
  $redbox = $ball;
} elseif ($ball == 'yellow') { //if this statement returns true, run the block
  $yellowbox = $ball;
} elseif ($ball == 'blue') { //ditto
  $bluebox = $ball;
} elseif ($ball == 'green') { //ditto
  $greenbox = $ball;
} elseif ($ball == 'purple') { //ditto
  $purplebox = $ball;
} else { //run this if none of the following were run
  $colorlessbox = $ball;
}
echo "red box: $redbox\n";
echo "yellow box: $yellowbox\n";
echo "blue box: $bluebox\n";
echo "green box: $greenbox\n";
echo "purple box: $purplebox\n";
echo "colorless box: $colorlessbox\n";
?>
You can have endless amounts of "elseif" blocks in your "if" statements.  You can even combine them (something we won't really get to because it usually isn't as important).  Remember this was a very basic introduction to the "if" control structure statement, PLEASE ask questions if you have any.  I'm aware that this lesson might not have been clear.
 

James_Smith

White Belt
Hi Ardenn,

You are really great, awesome tutorial about PHP with relevant example whenever necessary. I like the most important part i.e, the way you are covered all the(near about) php basics within it, it's an very interesting.
 
Status
Not open for further replies.
Top