Chapter 2
Chapter 2
Introduction
Today’s Web users expect exciting pages that are updated frequently and provide a customized experience. For them, Web sites are more like
communities, to which they’ll return time and again. At the same time, Web-site administrators want sites that are easier to update and maintain,
understanding that’s the only reasonable way to keep up with visitors’ expectations. For these reasons and more, PHP and MySQL have become
the de facto standards for creating dynamic, database driven Web sites.
Dynamic Web sites are flexible and potent creatures, more accurately described as applications than merely sites. DynamicWeb sites
Respond to different parameters (for example, the time of day or the version of the visitor’s Web browser)
Have a “memory,” allowing for user registration and login, e-commerce, and similar processes
Almost always integrate HTML forms, allowing visitors to perform searches, provide feedback, and so forth
Often have interfaces where administrators can manage the site’s content
Are easier to maintain, upgrade, and build upon than statically made sites
There are many technologies available for creating dynamic Web sites. The most common are ASP.NET (Active Server Pages, a Microsoft
construct), JSP (Java Server Pages), ColdFusion, Ruby on Rails (a Web development framework for the Ruby programming language), and PHP.
Dynamic Web sites don’t always rely on a database, but more and more of them do, particularly as excellent database applications like MySQL are
available at little to no cost.
What is PHP?
PHP originally stood for “Personal Home Page” as it was created in 1994 by Rasmus Lerdorf to track the visitors to his online résumé. As its
usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean “PHP: Hypertext Preprocessor.”
According to the official PHP Web site, found at www.php.net A, PHP is a “widely used general-purpose scripting language that is especially
suited for Web development and can be embedded into HTML.”
1
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP is a server-side, cross-platform technology, both descriptions being important. Server side refers to the fact that everything PHP does occurs
on the server. A Web server application, like Apache or Microsoft’s IIS (Internet Information Services), is required and all PHP scripts must be
accessed through a URL (http://something). Its cross-platform nature means that PHP runs on most operating systems, including Windows, UNIX
(and its many variants), and Macintosh. More important, the PHP scripts written on one server will normally work on another with little or no
modification.
PHP has seen an exponential growth in use since its inception, and is the server-side technology of choice on over 76 percent of all Web sites. In
terms of all programming languages, PHP is the fifth most popular after Java, C, C++ and C#.
As previously stated, PHP is a server-side language. This means that the code you write in PHP sits on a host computer called a server. The server
sends Web pages to the requesting visitors (you, the client, with your Web browser).When a visitor goes to a Web site written in PHP, the server
reads the PHP code and then processes it according to its scripted directions. In the example shown in below, the PHP code tells the server to send
the appropriate data—HTML code—to the Web browser, which treats the received code as it would a standard HTML page. This differs from a
static HTML site where, when a request is made, the server merely sends the HTML data to the Web browser and there is no server-side
interpretation occurring. Because no server-side action is required, you can run HTML pages in your Web browser without using a server at all. To
the end user and the Web browser there is no perceptible difference between what home.html and home.php may look like, but how that page’s
content was created will be significantly different.
2
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
What is MySQL?
MySQL (www.mysql.com) is the world’s most popular open-source database. In fact, today MySQL is a viable competitor to the pricey goliaths
such as Oracle and Microsoft’s SQL Server (and, ironically, MySQL is owned by Oracle). Like PHP, MySQL offers excellent performance,
portability, and reliability, with a moderate learning curve and little to no cost.
MySQL is a database management system (DBMS) for relational databases (therefore, MySQL is an RDBMS). A database, in the simplest terms,
is a collection of data, be it text, numbers, or binary files, stored and kept organized by the DBMS.
By incorporating a database into a Web application, some of the data generated by PHP can be retrieved from MySQL . This further moves the
site’s content from a static (hard-coded) basis to a flexible one, flexibility being the key to a dynamic Web site.
3
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
MySQL has been known to handle databases as large as 60,000 tables with more than 5 billion rows. MySQL can work with tables as large as 8
million terabytes on some operating systems, generally a healthy 4 GB otherwise. MySQL is used by NASA and the United States Census Bureau,
among many others.
PHP is an HTML-embedded scripting language, meaning that you can intermingle PHP and HTML code within the same file. So to begin
programming with PHP, start with a simple Web page. Script 1.1 is an example of a no-frills, no-content XHTML Transitional document, which
will be used as the foundation for most Web pages. Please also note that the template uses UTF-8 encoding, a topic discussed in the sidebar. To
add PHP code to a page, place it with in PHP tags:
<?php
?>
used to create content displayed in the Web browser, the PHP tags are normally put somewhere within the page’s body.)
4
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Along with placing PHP code within PHP tags, your PHP files must have a proper extension. The extension tells the server to treat the script in a
special way, namely, as a PHP page. Most Web servers use .html for standard HTML pages and .php for PHP files.
To create dynamic website with PHP, you must know how to send data to the Web browser. PHP has a number of built-in functions for this
purpose, the most common being echo and print. I personally tend to favor echo: You could use print instead, if you prefer (the name more
obviously indicates what it does):
5
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
With PHP we are not limited to output HTML. We can output images, PDF files, and even flash movies. We can also output any text, such as
XHTML and XML.
Why PHP?
PHP runs on different platforms (Windows, Linux, UNIX, Mac OSX, etc.)
PHP is compatible with almost all servers used today (Apache,IIS, etc.)
PHP has support for a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
<?php <?php
/* $y=6;
*/ ?>
</html> From the expression z=x+y above, we can calculate the value of z to be 11
6
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must begin with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
A variable name should not contain spaces Variable names are case sensitive ($y and $Y are two different variables)
PHP has no command for declaring a variable. A variable is created the moment you first assign a value to it:
After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value 5.
Note: When we assign a text value to a variable, put quotes around the value.
In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically converts the variable to the
correct data type, depending on its value. In a strongly typed programming language, we will have to declare (define) the type and name of the
variable before using it.
The scope of a variable is the part of the script where the variable can be referenced/used.
1. Local
2. global
3. static
4. parameter
1. Local Scope
7
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php The script above will not produce any output because the echo statement refers to the
local scope variable $x, which has not been assigned a value within this scope.
$x=5; // global scope
We can have local variables with the same name in different functions, because local
function myTest()
variables are only recognized by the function in which they are declared.
{
Local variables are deleted as soon as the function is completed.
echo $x; // local scope
myTest();
?>
2. Global Scope
A variable that is defined outside of any function, has a global scope. Global variables can be accessed from any part of the script, EXCEPT from
within a function.
To access a global variable from within a function, use the global keyword:
Example PHP also stores all global variables in an array called $GLOBALS[index].
<?php The index holds the name of the variable. This array is also accessible from
within functions and can be used to update global variables directly.
$x=5; // global scope
The example above can be rewritten like this:
$y=10; // global scope
<?php
function myTest()
$x=5;
$y=10;
8
function
By: Berihun. M (Lecturer (MSc IT), myTest()
(BSc CS))
{
{
global $x,$y;
$y=$x+$y;
myTest();
3. Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted. To do
this, use the static keyword when you first declare the variable:
Then, each time the function is called, that variable will still have the information it
Example
contained from the last time the function was called.
<?php
Note: The variable is still local to the function.
function myTest()
4. Parameter Scope
{
A parameter is a local variable whose value is passed to the function by the calling code.
static $x=0;
Parameters are declared in a parameter list as part of the function declaration:
echo $x;
<?php
$x++;
function myTest($x) * Note: Parameters are also called arguments
}
{
myTest();
echo $x;
}
9
myTest(5);
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
?>
myTest();
myTest();
?>
String variables are used for values that contain characters. After we have created a string variable we can manipulate it. A string can be used
directly in a function or it can be stored in a variable. In the example below, we create a string variable called txt, then we assign the text "Hello
world!" to it. Then we write the value of the txt variable to the output:
Example
<?php Note: When we assign a text value to a variable, remember to put single or
double quotes around the value.
$txt="Hello world!";
echo $txt;
?>
The following are some commonly used functions and operators to manipulate strings.
The concatenation operator (.) is used to join two string values together. The example below shows how to concatenate two string variables
together:
Example
The output of the code above will be:
$txt1="Hello world!";
?>
The strlen( ) function returns the length of a string, in characters. The example below returns the length of the string "Hello world!":
Example
The output of the code above will be: 12
<?php
Tip: strlen( ) is often used in loops or other functions, when it is important to know when
echo strlen("Hello world!");
a string ends. (i.e. in a loop, we might want to stop the loop after the last character in a
?>
string).
The PHP strpos ( ) function
The strpos( ) function is used to search for a character or a specific text within a string. If a match is found, it will return the character position of
the first match. If no match is found, it will return FALSE. The example below searches for the text "world" in the string "Hello world!":
Example
echo strpos("Hello world!","world");Tip: The position of the string "world" in the example above is 6. The reason
that it is 6 (and not 7), is that the first character position in the string is 0, and
?> not 1.
11
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Operators
-x Negation Opposite of x -2 2
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on the right. That is, the value of
"$x = 5" is 5.
x=y x=y the left operand gets set to the value of the expression on the right
x += y x=x+y Addition
12
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
x === y Identical True if x is equal to y, they are of same type 5==="5" returns false
x !== y Not identical True if x is not equal to y,or they are not of same type 5!=="5" returns true
13
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
x>y Greater than True if x is greater than y 5>8 returns false
x >= y Greater or equal True if x is greater than or equal to y 5>=8 returns false
x <= y less than or equal True if x is less than or equal to y 5<=8 returns true
x and y And True if both x and y are true x=6,y=3 (x < 10 and y > 1) returns true
x or y Or True if either or both x and y are true x=6,y=3, (x==6 or y==5) returns true
x xor y Xor True if either x or y is true, but not both x=6,y=3, (x==6 xor y==3) returns false
x && y And True if both x and y are true x=6,y=3, (x < 10 && y > 1) returns true
x || y Or True if either or both x and y are true x=6,y=3, (x==5 || y==5) returns false
Very often when we write code, we want to perform different actions for different decisions. We can use conditional statements in our code to do
this.
14
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
Syntax
if (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
If more than one line should be executed if a condition is true/false, the lines
<html> should be enclosed within curly braces:
<body> <?php
<?php $d=date("D");
$d=date("D"); if ($d=="Fri")
if ($d=="Fri") {
?> }
</body> ?>
15
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
</html>
If you want to execute some code if one of several conditions are true use the elseif statement
Syntax
if (condition)
elseif (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<?php
** Note: no space between else and if.
$d=date("D");
So in this we actually have 3 option to go based on the day today.
if ($d=="Fri")
elseif ($d=="Sun")
16
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
else
?>
The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. If you want to select
one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..else code.
Syntax
switch (expression)
case label1:
break;
case label2:
17
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
}
Example
<?php
switch ($x)
case 2:
break;
case 3:
break;
default:
?>
Looping
18
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Bounded loops versus unbounded loops
A bounded loop executes a fixed number of times —you can tell by looking at the code how many times the loop will iterate, and the language
guarantees that it won’t loop more times than that. An unbounded loop repeats until some condition becomes true (or false), and that condition is
dependent on the action of the code within the loop. Bounded loops are predictable, whereas unbounded loops can be as tricky as you like.
PHP doesn’t actually have any constructs specifically for bounded loops —while, do-while, and for are all unbounded constructs —but an
unbounded loop can do anything a bounded loop can do.
While
The simplest PHP looping construct is while, which has the following syntax:
while (condition)
statement
The while loop evaluates the condition expression as a Boolean —if it is true, it executes statement and then starts again by evaluating condition.
If the condition is false, the while loop terminates. Of course, just as with if, statement may be a single statement or it may be a brace-enclosed
block. The body of a while loop may not execute even once, as in:
while (FALSE)
while (TRUE)
$count = 1;
19
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
{
print(“count is $count<BR>”);
$count = $count + 1;
Do-while
The do-while construct is similar to while, except that the test happens at the end of the loop. The syntax is:
do statement
while (expression);
The statement is executed once, and then the expression is evaluated. If the expression is true, the statement is repeated until the expression
becomes false. The only practical difference between whileand do-whileis that the latter will always execute its statement at least once.For
example:
$count = 45;
do
print(“count is $count<BR>”);
$count = $count + 1;
20
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Output will be 45.
For Loop
The most complicated looping construct is for, which has the following syntax:
statement;
It is also legal to include more than one of each kind of for clause, separated by commas.
The termination-check will be considered to be true if any of its sub clauses are true; it is like an ‘or’ test. For example, the following statement:
Looping examples
create a Division Table using for loop.
<HTML>
<BODY>
<TABLE BORDER=1>
<?php
$start_num = 1;
21
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
$end_num = 10;
print("<TR>");
print("<TH> </TH>");
$count_1++)
print("<TH>$count_1</TH>");
print("</TR>");
$count_1++)
print("<TR><TH>$count_1</TH>");
$count_2++)
printf("<TD>%.3f</TD>", $result);
22
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
}
print("</TR>\n");
?>
</TABLE>
</BODY> </HTML>
PHP Arrays
What is an array?
When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store
the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays:
Numeric Arrays
A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array.
Example 1
$names = array("Tsegaye","Abebe","Joe");
Example 2
23
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
In this example we assign the ID key manually:
$names[0] = "Tsegaye";
$names[1] = "Abebe";
$names[2] = "Joe";
<?php
$names[0] = "Tsegaye";
$names[1] = "Abebe";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>
Associative Arrays
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
Example 2
24
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
?>
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
Example
$families = array
The array above would look like this if written to the output:
Array
25
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
([Griffin] => Array([0] => Peter[1] => Lois[2] => Megan) [Quagmire] => Array([0] => Glenn) [Brown] => Array([0] => Cleveland[1] =>
Loretta[2] => Junior) )
For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be
looking at the next element.
Syntax
code to be executed;
Example
The following example demonstrates a loop that will print the values of the given array:
<?php
?>
26
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Functions
The real power of PHP comes from its functions. In PHP - there are more than 700 built-in functions available.
For a reference and examples of the built-in functions, please visit our PHP Reference.
Example
<?php
function writeMyName()
writeMyName();
?>
27
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Functions - Adding parameters
Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:
<?php
function writeMyName($fname)
} My name is Tsegaye
writeMyName("Tsegaye");
writeMyName("Andargie");
?>
Example 2
<?php
28
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
function writeMyName($fname,$punctuation)
echo "My name is "; The output of the code above will be:
writeMyName("Ståle","...");
?>
Example
<?php
The output of the code above will be:
function add($x,$y)
1 + 16 = 17
{ $total = $x + $y;
return $total;
?>
29
By: Berihun. M (Lecturer (MSc IT), (BSc CS))