Sei sulla pagina 1di 18

What is PHP? PHP is a recursive acronym for Hypertext Preprocessor.

It is a server-
side scripting language whose main purpose is to generate the HTML code, which can
be viewed by the client. As such, the PHP code itself is not visible to the clients (i.e.,
if you do a "view source" in your web browser, you cannot see the PHP code. You can
only see the resulting HTML code). This contrasts with client-side languages such as
Javascript, which is visible to the client.

PHP was first created by Rasmus Lerdorf in 1995, and saw its first official release in
1997. Milestone releases included PHP 3 in 1998, PHP 4 in 2000, and PHP 5 in 2004.
Today, many large-scale websites run on PHP. The author was first introduced to PHP
in 2000, and have found the language to be pretty easy to work with.

Below is a simple "Hello World" program, PHP flavor:

<?php
print "Hello World.";
?>

Executing this program on a web server enabled with PHP produces the following
output:

Hello World.

PHP programs usually have an extension of .php.

By the end of this tutorial, you should have a good understanding of the basic
constructs of PHP, as well as how PHP can interact with MySQL to produce dynamic
web pages. Please bookmark this site now by pressing Control-D and start to learn
PHP now.

Next: PHP Variables

Variable Types

Variables play an important role in PHP, as they are places for holding values. In
PHP, there is no need to declare variables. Variable can hold eight different data
types: bloolean, integer, float, string, array, object, resource, or NULL.

PHP is a weakly typed language. This means that variable type varies depending on
what is stored in the variable at the time. For example, if we have a variable $a,
when $a = 0, $a is an integer type variable. If later we set $a = "New", then $a
becomes a string type variable.

Variable Name

A variable name always starts with a $, followed by a letter or an underscore. The


rest of the variable name can be a letter, a number or an underscore.
For example, $dog is a valid variable name, while @dog is not (@dog does not start
with a $).

Variables in PHP are case-sensitive. For example, $Employee and $employee are two
different variables.

Variable Scope

In most cases, variables are local in scope. This means that variables declared within
a function cannot be accessed outside of the function, and variables declared outside
of a function cannot be access within the function.

To make a variable global, it must either be declared as global specifically, or it must


be accessed using the $GLOBALS array.

Next: PHP Operators

The most common PHP operators are assignment operators, arithmetic operators,
combined operators, comparison operators, and logical operators. Each type is
discussed separately below.

Assignment Operators

The basic assignment operator in PHP is "=". This means that the operand to the left
of "=" gets set to the value to the right of "=".

Arithmetic Operators

Operator Example Result


+ 4+2 6
- 4-2 2
* 4*2 8
/ 4/2 2
% 4%2 0
++ x = 4; x++; x = 5
-- x = 4; x--; x=3

Combined Operators

You can combine an arithmetic operator with the assignment operator to form a
combined operator. Combined operators are shown below:

Operator Example Meaning


+= y += x y=y+x
-= y -= x y=y-x
*= y *= x y=y*x
/= y /= x y=y/x
%= y %= x y = y % x

Comparison Operators

Operator Meaning
== is equal to
!= is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to

Logical Operators

Operator Meaning
|| or
&& and
and and
or or
xor xor
! not
Next: PHP IF ELSE

IF..ELSE is used in PHP to provide conditional judgements. The basic syntax is as


follows:

IF (conditional statement) {
[code if condition is true]
}
ELSE {
[code if condition is false]
}

Let's see an example. Assuming we have the following piece of code:

$sample = 10;
IF ($sample > 5) {
print "Number is greater than 5";
}
ELSE {
print "Number is less than 5";
}

The output of the above code is:

Number is greater than 5

This is because the condition, ($sample > 5), is true. Therefore, the code in the
bracket after IF is executed.

Next: PHP ELSEIF

In IF ELSE, PHP provides a way to do an either/or selection. What if you need more
than two options? This is where ELSEIF comes in. ELSEIF is built on top of the IF
ELSE construct to provide additional options. The basic syntax is as follows:

IF (conditional statement 1) {
[code if condition statement 1 is true]
}
ELSEIF (conditional statement 2) {
[code if condition statement 2 is true]
}
...
ELSE {
[code if none of the above is true]
}

ELSEIF can be repeated as many times as needed prior to the ELSE statement.

Let's use an example. Assuming we have the following piece of code:

$sample = 10;
IF ($sample > 15) {
print "Level 1";
}
ELSEIF ($sample > 5) {
print "Level 2";
}
ELSE {
print "Level 3";
}

The output of the above code is:

Level 2
This is because the first condition is false, and the second condition is true.
Therefore, the code in the bracket after ELSEIF is executed.

Next: PHP SWITCH

SWITCH is used in PHP to replace nested IF..ELSE loops, and is similar to the CASE
command in other computer languages. The basic syntax of SWITCH is as follows:

SWITCH ($variable) {
CASE 'value 1':
[code to execute when $variable = 'value 1']
break;
CASE 'value 2':
[code to execute when $variable = 'value 2']
break;
CASE 'value 3':
...
DEFAULT:
[code to execute when none of the CASE values matches $variable]
}

There can be an unlimited number of CASE conditions. In addition, DEFAULT is


optional.

Let's view an example. Assuming we have the following piece of code:

$sample = 10;
SWITCH ($sample) {
CASE 30:
print "Value is 30";
break;
CASE 25:
print "Value is 25";
break;
CASE 20:
print "Value is 20";
break;
DEFAULT:
print "Value is outside the range";
}

The output of the above code is:

Value is outside the range

This is because none of the CASE conditions was matched, so the code following
DEFAULT is executed.

Next: PHP WHILE Loop


WHILE is used in PHP to provide a control condition. The basic syntax of WHILE is as
follows:

WHILE (expression)
{
[code to execute]
}

WHILE tells PHP to execute the [code to execute] as long as the (expression) is true.

Let's look at an example. Assuming we have the following piece of code:

$counter = 8;
WHILE ($counter < 10)
{
print "counter is now " . $counter . "<br>";
$counter++;
}

The output of the above code is:

counter is now 8
counter is now 9

During the first iteration, $counter = 8, which means the expression, ($counter <
10), is true. Therefore, the print statement is executed, and $counter gets
incremented by 1 and becomes 9.

During the second iteration, $counter = 9, which means the expression, ($counter <
10), is true. Therefore, the print statement is executed, and $counter gets
incremented by 1 and becomes 10.

During the third iteration, $counter = 10, which means the expression, ($counter <
10), is false. Therefore, the WHILE condition no longer is true, and the code in the
bracket is no longer executed.

Next: PHP FOR Loop

FOR is used in PHP to execute the same code a set number of times. The basic
syntax of FOR is as follows:

FOR (expression 1, expression 2, expression 3)


{
[code to execute]
}

FOR tells PHP to first execute "expression 1", then evaluate "expression 2". If
"expression 2" is true, then [code to execute] is executed. After this, expression 3 is
executed, and then "expression 2" is evaluated again. If "expression 2" is true, then
[code to execute] is executed for a second time. The cycle continues until
"expression 2" is no longer true.

Let's look at an example. Assuming we have the following piece of code:

FOR ($i = 0; $i <= 2; $i++)


{
print "value is now " . $i . "<br>";
}

The output of the above code is:

value is now 0
value is now 1
value is now 2

During the 1st iteration, $i = 0, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 1.

During the 2nd iteration, $i = 1, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 2.

During the 3rd iteration, $i = 2, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 3.

During the 4th iteration, $i = 3, which means the expression, ($i <= 2), is false.
Therefore, PHP exits out of the FOR loop, and does not execute the print statement.

Next: PHP DO WHILE Loop

DO .. WHILE is used in PHP to provide a control condition. The idea is to execute a


piece of code while a condition is true. The basic syntax of DO .. WHILE is as follows:

DO {
[code to execute]
} WHILE (conditional statement)

The difference between DO .. WHILE and WHILE is that DO .. WHILE will always
execute the [code to execute] at least once, and in a WHILE construct, it is possible
for the [code to execute] to never execute.

Let's look at an example. Assuming we have the following piece of code:


$i = 5
DO {
print "value is now " . $i . "<br>";
$i--;
} WHILE ($i > 3);

The output of the above code is:

value is now 5
value is now 4

During the 1st iteration, $i = 5, the print statement is executed, $i gets decreased
by 1 and becomes 4, then PHP checks the expression, ($i > 3), which turns out to be
true. Therefore, the loop continues.

During the 2nd iteration, $i = 4, the print statement is executed, $i gets decreased
by 1 and becomes 3, then PHP checks the expression, ($i > 3), which is no longer
true. Therefore, PHP exits the loop.

If we change the above code to:

$i = 0
DO {
print "value is now " . $i . "<br>";
$i--;
} WHILE ($i > 3);

The output would then be:

value is now 0

Even though the expression ($i > 3) is false from the very beginning, one line is still
printed out because in DO .. WHILE, the code in the bracket following DO is always
executed at least once.

Next: PHP FOREACH Loop

FOREACH is used in PHP to loop over all elements of an array. The basic syntax of
FOREACH is as follows:

FOREACH ($array_variable as $value)


{
[code to execute]
}

or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}

In both cases, the number of times [code to execute] will be executed is equal to the
number of elements in the $array_variable array.

Let's look at an example. Assuming we have the following piece of code:

$array1 = array(1,2,3,4,5);
FOREACH ($array1 as $abc)
{
print "new value is " . $abc*10 . "<br>";
}

The output of the above code is:

new value is 10
new value is 20
new value is 30
new value is 40
new value is 50

The FOREACH loop above went through all 5 elements of array $array1, and each
time prints out a statement containing 10x the array element value.

Next: PHP INCLUDE

INCLUDE is used in PHP to append the code from an external file into the current file.
The syntax for INCLUDE is

INCLUDE ("external_file_name");

This is a convenient feature for a large website. Often, we may want to change an
element of the website that is consistent across the entire site, yet we don't want to
go through the trouble of updating every single file. In this case, we can simply use
INCLUDE in every file to call the same external file, and then all we need to change
is the content in that one external file.

Let's look at a simple example. Assuming we have the following two files:

index.php

<?php
print "This is the original content<br>";
include ("external_file");
?>

external_file

<?php
print "This is the external content";
?>

Upon executing index.php, we'll get the following output:

This is the original content


This is the external content

This is because, to the web server, it sees the following content:

<?php
print "This is the original content<br>";
print "This is the external content";
?>
Next: PHP Functions

Similar to other programming languages, PHP provides a way for programmers to


define functions, which can then be called elsewhere in the program. The syntax for
a function is:

function "function_name" (arg1, arg2...)


{
[code to execute]
return [final_result];
}

where [final_result] is typically the variable holding the final value to be returned
from the function.

Let's take a look at an example:

function double_this_number($input_number)
{
return $input_number*2;
}

Elsewhere in the PHP code, we have


$x = 10;
$y = double_this_number($x);
print $y;

The output will be

20
Next: PHP Array

An array is a way of holding multiple closely-related values, such as the test scores
of all students in a class. An array is made up of a key and a value, and the key
points to the value.

There are two types of arrays: Indexed array and Associative array. Their difference
is in the way the key is specified. Let's look at both of them:

Indexed Array

In an indexed array, the keys are numeric and starts with 0, and the values can be
any data type. The following shows two ways of assigning values to an indexed
array:

$friends = array("Sophie","Stella","Alice");

This is equivalent to the following:

$friends[0] = "Sophie";
$friends[1] = "Stella";
$friends[2] = "Alice";

Associative Array

In an associative array, the keys are not necessarily numeric, and even when they
are numeric, not necessarily in any order. So, when you are putting data into an
associative array, you'll need to make sure you specify both the key and the value:

$student_score = array("John"=>80, "Matt"=>90, "May"=>85);

This is equivalent to the following:

$student_score["John"] = 80;
$student_score["Matt"] = 90;
$student_score["May"] = 85;
Multidimensional Array

The arrays in the examples above are 1-dimensional. However, there will be times
when multidimensional arrays are desired. What's a multidimensional array? That's
when you have arrays of arrays. Let's look at an example below:

$array1 = array (10,15,20);


$array2 = array (110,115,120);
$array3 = array (210,215,220);
$big_array = array ($array1, $array2, $array3);

$big_array is now a 2-dimensional array. For example, if you have the following
output code:

print {$big_array[1,2]};

The output would be

120

Remember to use { } when you are accessing the value of a multidimensional array.

Next: PHP Forms

One of the main features in PHP is the ability to take user input and generate
subsequent pages based on the input. In this page, we will introduce the mechanism
by which data is passed in PHP.

Let's consider the following two files:

query.php

<form action=result.php type=post>


<input type=text name=employee>
<input type=submit value=Submit>
</form>

result.php

<?php
$employee_name = $_POST["employee"];
print $employee_name;
?>
After the user types in a value in the text box and click on the Submit button in
query.php, the result.php page will display the value that the user has just typed in.

How is this done? The $_POST function captures the value associated with the key
"employee", which was specified in the input name attribute in query.php. The
variable $employee_name is then set to the value for this key.

$_GET is $_POST's closely related cousin. The usage is exactly the same, except
you'll need to use $_GET if the form action type is GET. When the form action type is
GET, the parameters you submitted will be visible in the URL as the query string. In
a POST method, no query string is visible in the URL.

Usually when using $_POST or $_GET, you'll want to first check to see if PHP has
indeed received values for the key of interest. If not, you may want to assign the
receiving variable some type of default value. To do this, we leverage the isset()
function:

$result_variable = isset($_POST["key_value"],0,$_POST["key_value"]);

In the above example, if "key_value" is not set, $result_variable is set to 0.

Common input methods include text input, radio button, checkbox, and drop down
menu.

Next: PHP Cookies

If you have a website, you may wish to set a cookie on the client computer so that
your site will remember that user when she returns. PHP provides ways to create,
retrieve, and delete cookies.

Create cookies

Cookies are set using the setcookie() function. The syntax is as follows:

Setcookie (name, value, expire, path, domain, secure)

name = name of the cookie.


value = value of the cookie.
expire = time when this cookie will expire. Unix time is used here.
path = the path on the server on which the cookie is available.
domain = the domain that the cookie is available.
secure = TRUE means the cookie should be trasmitted over a secure connection
(https), FALSE otherwise. FALSE is the default.

All arguments except name are optional. Unix time is the number of seconds that
have elapsed since January 1, 1970.

You must make sure that the setcookie() function is called before any HTML output is
printed.
Let's take a look at a couple of examples:

<?php
setcookie('cookie1','lisa');
?>

This sets up a cookie with name = "cookie1" and value = "lisa". As expire time is not
specified, this cookie will expire when the browser is closed.

<?php
setcookie('cookie2','electric1',time()+3600);
?>

This sets up a cookie with name = "cookie2" and value="electric1", and this cookies
expires in 1 hour (3600 second).

Retrieve cookies

Cookies can be retrieved via the $_COOKIE or the $_HTTP_COOKIE_VARS arrays.


Assuming that the name of the cookie is "cookie1", the value of the cookie is
retrieved by $_COOKIE['cookie1'].

Delete cookies

To delete a cookie from a client computer, simply use the setcookie() function and
set the expiration time as a time in the past. For example, the following code,

<?php
setcookie('cookie1','lisa',1);
?>

will get rid of the cookie with name = "cookie1" and value = "lisa".

Next: PHP Redirect

If you have moved your pages, you can use PHP to perform a redirect to your new
page.

The search engine friendly way of redirecting is the 301 redirect. In PHP, this is
implemented as follows:

<?
Header("HTTP/1.1 301 Moved Permanently");
Header("Location:http://www.new-site.com");
?>
Make sure the above code is included before any HTML is produced. Otherwise, the
redirect will not work.

A 301 redirect directs the search engine spiders to the new page, and ensures that
all link juices to your old page are all passed to the new page.

Please note that if you do not include the first Header line above, the redirect still
works. But, instead of a 301 redirect, now it becomes a 302 (temporary) redirect.
302 redirects are not search engine friendly, as it has become a common spam
technique. So, if you want to ensure your search engine ranking is not affected by
moving your file elsewhere or changing your file name, make sure you set up a 301
redirect.

Next: PHP MySQL

Here we give an example of the PHP code that will read data out of a MySQL
database and present it in a nice tabular format in HTML.

Assuming we have the following MySQL table:

Table Employee

Name Salary
Lisa 40000
Alice 45000
Janine 60000

The PHP code needed is as follows (assuming the MySQL Server sits in localhost and
has a userid = 'cat' and a password of 'dog', the database name is 'myinfo') :

$link = @mysql_pconnect("localhost","cat","dog") or exit();


mysql_select_db("myinfo") or exit();

print "<p>Employee Information";


print "<p><table border=1><tr><td>Employee
Name</td><td>Salary
Amount</td></tr>";

$result = mysql_query("select name, salary from Employee");

while ($row=mysql_fetch_row($result))
{
print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";

print "</table>";
Output is

Employee Information

Employee Name Salary Amount


Lisa 40000
Alice 45000
Janine 60000

Below is a quick explanation of the code:

$link = @mysql_pconnect("localhost","cat","dog") or exit();


mysql_select_db("myinfo") or exit();

These two lines tell PHP how to connect to the MySQL server.

$result = mysql_query("select name, salary from Employee");

This specifies up the query to be executed.

while ($row=mysql_fetch_row($result))
{
print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";

$row[0] denotes the first column of the query result, namely the "name" field, and
$row[1] denotes the second column of the query result, namely the "salary" field.
The . in the print statement is the concatenation operator, and acts to combine the
string before and string after together. The print statement continuess until all 3
rows have been fetched.

Next: PHP Commands

This pages lists common PHP commands and their respective syntax. To view details
on each command, please click on the link; to learn PHP from the beginning, please
go to the PHP Tutorial homepage.

DO ... WHILE

DO {
[code to execute]
} WHILE (conditional statement)
ELSEIF

IF (conditional statement 1) {
[code if condition statement 1 is true]
}
ELSEIF (conditional statement 2) {
[code if condition statement 2 is true]
}
ELSE {
[code if neither statement is true]
}

FOR Loop

FOR (expression 1, expression 2, expression 3)


{
[code to execute]
}

FOREACH Loop

FOREACH ($array_variable as $value)


{
[code to execute]
}
or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}

IF ELSE

IF (conditional statement) {
[code if condition is true]
}
ELSE {
[code if condition is false]
}

Include

INCLUDE ("external_file_name");

<B.SWITCH< b>

SWITCH ($variable) {
CASE 'value 1':
[code to execute when $variable = 'value 1']
break;
CASE 'value 2':
[code to execute when $variable = 'value 2']
break;
CASE 'value 3':
...
DEFAULT:
[code to execute when none of the CASE values matches $variable']
}

WHILE Loop

WHILE (expression)
{
[code to execute]
}

Next: Resources

Potrebbero piacerti anche