This is a paragraph.
. When tags like , and color attributes were
added to the HTML 3.2 specification, it started a nightmare for web developers. Development
of large web sites, where fonts and color information were added to every single page,
became a long and expensive process. To solve this problem, the World Wide Web
Consortium (W3C) created CSS.
3.1 CSS SYNTAX
A CSS rule set consists of a selector and a declaration block:
Figure 1: CSS Syntax
Source: http://www.w3schools.com/css/css_syntax.asp
The selector points to the HTML element you want to style. The declaration block
contains one or more declarations separated by semicolons. Each declaration includes
a property name and a value, separated by a colon.
3.2 CSS SELECTORS
CSS selectors allow you to select and manipulate HTML element(s). CSS selectors are
used to "find" (or select) HTML elements based on their id, classes, types, attributes, values
of attributes and much more.
3.2.1 THE ELEMENT SELECTOR
The element selector selects elements based on the element name. You can select all
elements on a page like this: (all
elements will be center-aligned, with a red text
color).
EXAMPLE 59
p {
text-align: center;
color: red;
}
3.2.2 THE ID SELECTOR
The id selector uses the id attribute of an HTML tag to find the specific element. An id
should be unique within a page, so you should use the id selector when you want to find
a single, unique element. To find an element with a specific id, write a hash character,
3CSS (Cascading Style Sheets)
- 40 followed
by the id of the element. The style rule below will be applied to the HTML element
with id="para1":
EXAMPLE 60
#para1 {
text-align: center;
color: red;
}
3.2.3 THE CLASS SELECTOR
The class selector finds elements with the specific class. The class selector uses the
HTML class attribute. To find elements with a specific class, write a period character,
followed by the name of the class. In the example below, all HTML elements with
class="center" will be center-aligned:
EXAMPLE 61
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class. In
the example below, all p elements with class="center" will be center-aligned:
EXAMPLE 62
p.center {
text-align:center;
color:red;
}
3.2.4 GROUPING SELECTORS
In style sheets there are often elements with the same style:
EXAMPLE 63
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
Petr Suchánek, Jan Górecki; Portal and its Management
- 41 p
{
text-align: center;
color: red;
To minimize the code, you can group selectors. To group selectors, separate each
selector with a comma. In the example below we have grouped the selectors from the code
above:
EXAMPLE 64
h1, h2, p {
text-align: center;
color: red;
}
3.3 WAYS TO INSERT CSS
There are three ways of inserting a style sheet:
External style sheet;
Internal style sheet;
Inline style.
3.3.1 EXTERNAL STYLE SHEET
An external style sheet is ideal when the style is applied to many pages. With an
external style sheet, you can change the look of an entire Web site by changing just one file.
Each page must include a link to the style sheet with the tag. The tag goes
inside the head section:
EXAMPLE 65
An external style sheet can be written in any text editor. The file should not contain any
html tags. The style sheet file must be saved with a .css extension. An example of a style sheet
file is shown below:
EXAMPLE 66
"myStyle.css":
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/background.gif");}
3CSS (Cascading Style Sheets)
- 42 -
3.3.2 INTERNAL STYLE SHEET
An internal style sheet should be used when a single document has a unique style. You
define internal styles in the head section of an HTML page, inside the
3.3.3 INLINE STYLES
An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly! To use inline styles, add the style attribute to the
relevant tag. The style attribute can contain any CSS property. The example shows how to
change the color and the left margin of a paragraph:
EXAMPLE 68
This is a
paragraph.
3.3.4 MULTIPLE STYLE SHEETS
If some properties have been set for the same selector in different style sheets, the
values will be inherited from the more specific style sheet. For example, assume that an
external style sheet has the following properties for the h3 selector:
EXAMPLE 69
h3 {
color: red;
text-align: left;
font-size: 8pt;
}
then, assume that an internal style sheet also has the following properties for the h3
selector:
EXAMPLE 70
h3 {
text-align: right;
font-size: 20pt;
}
Petr Suchánek, Jan Górecki; Portal and its Management
- 43 If
the page with the internal style sheet also links to the external style sheet the
properties for the h3 element will be:
EXAMPLE 71
color: red;
text-align: right;
font-size: 20pt;
The color is inherited from the external style sheet and the text-alignment and the fontsize
is replaced by the internal style sheet.
3.4 CSS BACKGROUND
CSS background properties are used to define the background effects of an element.
CSS properties used for background effects:
background-color;
background-image;
background-repeat;
background-attachment;
background-position.
3.4.1 BACKGROUND COLOR
The background-color property specifies the background color of an element. The
background color of a page is defined in the body selector:
EXAMPLE 72
body {
background-color: #b0c4de;
}
With CSS, a color is most often specified by:
a HEX value - like "#ff0000";
an RGB value - like "rgb(255,0,0)";
a color name - like "red".
In the example below, the h1, p, and div elements have different background colors:
EXAMPLE 73
h1 {
background-color: #6495ed;
}
p {
background-color: #e0ffff;
}
div {
3CSS (Cascading Style Sheets)
- 44 background-color:
#b0c4de;
}
3.4.2 BACKGROUND IMAGE
The background-image property specifies an image to use as the background of an
element. By default, the image is repeated so it covers the entire element. The background
image for a page can be set like this:
EXAMPLE 74
body {
background-image: url("paper.gif");
}
Below is an example of a bad combination of text and background image. The text is
almost not readable:
EXAMPLE 75
body {
background-image: url("bgdesert.jpg");
}
By default, the background-image property repeats an image both horizontally and
vertically. Some images should be repeated only horizontally or vertically, or they will look
strange. If the image is repeated only horizontally (repeat-x), the background will look better:
EXAMPLE 76
body {
background-image: url("gradient.png");
background-repeat: repeat-x;
}
Showing the image only once is specified by the background-repeat property:
EXAMPLE 77
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
In the example above, the background image is shown in the same place as the text. We
want to change the position of the image, so that it does not disturb the text too much. The
position of the image is specified by the background-position property:
EXAMPLE 78
body {
Petr Suchánek, Jan Górecki; Portal and its Management
- 45 background-image:
url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
As you can see from the examples above, there are many properties to consider when
dealing with backgrounds. To shorten the code, it is also possible to specify all the properties
in one single property. This is called a shorthand property. The shorthand property for
background is simply "background":
EXAMPLE 79
body {
background: #ffffff url("img_tree.png") no-repeat right
top;
}
3.5 CSS TEXT
3.5.1 TEXT COLOR
The color property is used to set the color of the text. With CSS, a color is most often
specified by:
a HEX value - like "#ff0000";
an RGB value - like "rgb(255,0,0)";
a color name - like "red".
The default color for a page is defined in the body selector.
EXAMPLE 80
body {
color: blue;
}
h1 {
color: #00ff00;
}
h2 {
color: rgb(255,0,0);
}
3.5.2 TEXT ALIGNMENT
The text-align property is used to set the horizontal alignment of a text. Text can be
centered, or aligned to the left or right, or justified. When text-align is set to "justify", each
3CSS (Cascading Style Sheets)
- 46 line
is stretched so that every line has equal width, and the left and right margins are straight
(like in magazines and newspapers).
EXAMPLE 81
h1 {
text-align: center;
}
p.date {
text-align: right;
}
p.main {
text-align: justify;
}
3.5.3 TEXT DECORATION
The text-decoration property is used to set or remove decorations from text. The textdecoration
property is mostly used to remove underlines from links for design purposes:
EXAMPLE 82
a {
text-decoration: none;
}
It can also be used to decorate text:
EXAMPLE 83
h1 {
text-decoration: overline;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}
3.5.4 TEXT TRANSFORMATION
The text-transform property is used to specify uppercase and lowercase letters in a text.
It can be used to turn everything into uppercase or lowercase letters, or capitalize the first
letter of each word.
Petr Suchánek, Jan Górecki; Portal and its Management
- 47 EXAMPLE
84
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
3.5.5 TEXT INDENTATION
The text-indent property is used to specify the indentation of the first line of a text.
EXAMPLE 85
p {
text-indent: 50px;
}
3.6 CSS FONT
3.6.1 FONT FAMILY
The font family of a text is set with the font-family property. The font-family property
should hold several font names as a "fallback" system. If the browser does not support the
first font, it tries the next font. Start with the font you want, and end with a generic family, to
let the browser pick a similar font in the generic family, if no other fonts are available. If the
name of a font family is more than one word, it must be in quotation marks, like: "Times New
Roman". More than one font family is specified in a comma-separated list:
EXAMPLE 86
p {
font-family: "Times New Roman", Times, serif;
}
3.6.2 FONT STYLE
The font-style property is mostly used to specify italic text. This property has three
values:
normal - The text is shown normally;
italic - The text is shown in italics;
oblique - The text is "leaning" (oblique is very similar to italic, but less supported).
3CSS (Cascading Style Sheets)
- 48 EXAMPLE
87
p.normal {
font-style: normal;
}
p.italic {
font-style: italic;
}
p.oblique {
font-style: oblique;
}
3.6.3 FONT SIZE
The font-size property sets the size of the text. Being able to manage the text size is
important in web design. However, you should not use font size adjustments to make
paragraphs look like headings, or headings look like paragraphs. Always use the proper
HTML tags, like - for headings and
for paragraphs. The font-size value can
be an absolute, or relative size.
Absolute size:
Sets the text to a specified size;
Does not allow a user to change the text size in all browsers (bad for accessibility reasons);
Absolute size is useful when the physical size of the output is known.
Relative size:
Sets the size relative to surrounding elements;
Allows a user to change the text size in browsers
If you do not specify a font size, the default size for normal text, like paragraphs, is
16px (16px=1em).
Setting the text size with pixels gives you full control over the text size:
EXAMPLE 88
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p {
font-size: 14px;
}
The example above allows Internet Explorer 9, Firefox, Chrome, Opera, and Safari to
resize the text. The example above does not work in IE, prior version 9. The text can be
Petr Suchánek, Jan Górecki; Portal and its Management
- 49 resized
in all browsers using the zoom tool (however, this resizes the entire page, not just the
text).
3.7 CSS LINKS
Links can be styled with any CSS property (e.g. color, font-family, background, etc.). In
addition, links can be styled differently depending on what state they are in. The four links
states are:
a:link - a normal, unvisited link;
a:visited - a link the user has visited;
a:hover - a link when the user mouses over it;
a:active - a link the moment it is clicked.
EXAMPLE 89
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
When setting the style for several link states, there are some order rules:
a:hover MUST come after a:link and a:visited;
a:active MUST come after a:hover.
3.8 CSS LISTS
In HTML, there are two types of lists:
unordered lists - the list items are marked with bullets;
ordered lists - the list items are marked with numbers or letters.
With CSS, lists can be styled further, and images can be used as the list item marker.
3.8.1 DIFFERENT LIST ITEM MARKERS
The type of list item marker is specified with the list-style-type property (some of the
values are for unordered lists, and some for ordered lists):
3CSS (Cascading Style Sheets)
- 50 EXAMPLE
90
ul.a {
list-style-type: circle;
}
ul.b {
list-style-type: square;
}
ol.c {
list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}
3.8.2 AN IMAGE AS THE LIST ITEM MARKER
To specify an image as the list item marker, use the list-style-image property:
EXAMPLE 91
ul {
list-style-image: url('sqpurple.gif');
}
The example above does not display equally in all browsers. IE and Opera will display
the image-marker a little bit higher than Firefox, Chrome, and Safari.
3.8.3 CROSSBROWSER SOLUTION
The following example displays the image-marker equally in all browsers:
EXAMPLE 92
ul {
list-style-type: none;
padding: 0px;
margin: 0px;
}
ul li {
background-image: url(sqpurple.gif);
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
}
Example explained:
Petr Suchánek, Jan Górecki; Portal and its Management
- 51
For ul:
o Set the list-style-type to none to remove the list item marker;
o Set both padding and margin to 0px (for cross-browser compatibility).
For all li in ul:
o Set the URL of the image, and show it only once (no-repeat);
o Position the image where you want it (left 0px and down 5px);
o Position the text in the list with padding-left.
3.8.4 LIST - SHORTHAND PROPERTY
It is also possible to specify all the list properties in one, single property. This is called
a shorthand property. The shorthand property used for lists, is the list-style property:
EXAMPLE 93
ul {
list-style: square url("sqpurple.gif");
}
When using the shorthand property, the order of the values are:
list-style-type;
list-style-position (for a description, see the CSS properties table below);
list-style-image.
It does not matter if one of the values above are missing, as long as the rest are in the
specified order.
3.9 CSS TABLES
To specify table borders in CSS, use the border property. The example below specifies a black
border for table, th, and td elements:
EXAMPLE 94
table, th, td {
border: 1px solid black;
}
Notice that the table in the example above has double borders. This is because both the
table and the th/td elements have separate borders. To display a single border for the table,
use the border-collapse property.
3.9.1 COLLAPSE BORDERS
The border-collapse property sets whether the table borders are collapsed into a single
border or separated:
EXAMPLE 95
table {
border-collapse: collapse;
3CSS (Cascading Style Sheets)
- 52 -
}
table, th, td {
border: 1px solid black;
}
3.9.2 TABLE WIDTH AND HEIGHT
Width and height of a table is defined by the width and height properties. The example
below sets the width of the table to 100%, and the height of the th elements to 50px:
EXAMPLE 96
table {
width: 100%;
}
th {
height: 50px;
}
3.9.3 TABLE TEXT ALIGNMENT
The text in a table is aligned with the text-align and vertical-align properties. The textalign
property sets the horizontal alignment, like left, right, or center:
EXAMPLE 97
td {
text-align: right;
}
The vertical-align property sets the vertical alignment, like top, bottom, or middle:
EXAMPLE 98
td {
height: 50px;
vertical-align: bottom;
}
3.9.4 TABLE PADDING
To control the space between the border and content in a table, use the padding property
on td and th elements:
EXAMPLE 99
td {
Petr Suchánek, Jan Górecki; Portal and its Management
- 53 padding:
15px;
}
3.9.5 TABLE COLOR
The example below specifies the color of the borders, and the text and background color
of th elements:
EXAMPLE 100
table, td, th {
border: 1px solid green;
}
th {
background-color: green;
color: white;
}
4PHP
- 54 -
4 PHP
PHP is a server-side scripting language designed for web development but also used as
a general-purpose programming language. PHP code can be simply mixed with HTML code,
or it can be used in combination with various templating engines and web frameworks. PHP
code is usually processed by a PHP interpreter, which is usually implemented as a web
server's native module or a Common Gateway Interface (CGI) executable. After the PHP code
is interpreted and executed, the web server sends resulting output to its client, usually in form
of a part of the generated web page – for example, PHP code can generate a web page's
HTML code, an image, or some other data. PHP has also evolved to include a command-line
interface (CLI) capability and can be used in standalone graphical applications.
4.1 INSTALLATION OF A LOCAL SERVER
Download EasyPHP from the website www.easyphp.org;
double-click on the downloaded executable;
select an installation directory and follow the instructions.
Before doing anything, verify that easyphp.exe is launched and servers are running. When
EasyPHP is launched, an icon appears in the systray (beside the clock). If this icon looks like
this or like this or like this , that means that servers are not running properly. If this is
the case, double-click the icon to bring up the window below. Start the server(s) that didn't
start (Figure 2) and wait until ...
Figure 2: Start of MySQL.
... the window looks like (Figure 3):
Figure 3: Apache and MySQL is running.
When everything is fine, the systray icon looks like :
Petr Suchánek, Jan Górecki; Portal and its Management
- 55 Now
you can open the administration page. Right-click on and select "Administration".
The administration page allows you to manage PHP / Apache / MySQL, aliases, modules and
to use the code tester.
Other menu options:
Help: help on EasyPHP;
Log Files: record errors generated by Apache, MySQL and EasyPHP;
Configuration: gives access to various configuration tools;
Explorer: open the directory "localweb" in Windows Explorer;
Administration : opens the administration page;
Web local : opens local web;
Restart : restarts Apache and MySQL;
Start/Stop : Starts/Stops Apache and MySQL;
Quit : closes EasyPHP.
You must place your files either in the "localweb" directory, in an alias folder or
a virtual host folder (module "Virtual Hosts Manager" needed). So that PHP can interpret
your PHP pages.
4.2 YOUR FIRST PHP PAGE
There are many ways to program in PHP and there are many suitable text editors (eg.
specialized for HTML or PHP with syntax highlighting etc). For this example, you can use
a simple text editor.
1) Open a new file;
2) Type the structure (Example 101) of an HTML page
EXAMPLE 101
My first page in PHP.
The Example 102 is designed to display the current date. The PHP Code is integrated
directly into the HTML:
EXAMPLE 102
My first page in PHP.
Current date :
4PHP
- 56 -
3) Create a new directory in the "localweb" directory (or in an alias folder, or in
a virtual host folder). Save your first PHP page there with the following extension:
.php. Name it "date.php".Make sure, in the Windows Folder Options, that the
extensions of the files whose type is known are visible.
4) If you want to see the result you need to use a browser. From the administration page
select your folder (localweb, alias or virtual host) and click on your file "date.php".
Your browser will display a page with the current date; for example: "current Date:
Wednesday March 22, 2013".
4.3 PHP BASICS
PHP is an easy-to-understand language and it is enough to be familiar with the basics of
the language in many situations. With PHP, data can be stored, updated or deleted. Everything
happens on a web server, where all code sources are stored. Firstly, a PHP script is proceeded
on web server and its result is sent to the client browser. It means that, for example, 300/30 is
computed and then only the resulting number 10 is sent to a browser. This is why you find in
the source code of a web page only "10" (this is the difference between PHP and JavaScript,
where code is processed directly in the browser). Thus, a PHP source code cannon be
displayed in the browser.
With PHP, it is possible to create a website discussion forum, a guestbook, a counter,
a poll or a chart. You also have an option to link your site with a database such as MySQL.
There exists at least one PHP function that is common perhaps for each site. Each web
page on the site usually consists from several parts, like the header, links, menu or the footer,
which are the same on most of the pages. In this case, it is better to implement those parts in
separate files, which are later included to the webpages using special PHP statement (see
Section PHP Include Files for details). In this manner, when something changes in, for
example, left menu, only the left menu file is updated, and the change is propagated to all the
webpages that includes the left menu.
Any PHP script must be enclosed in special tags used for this purpose. The first option
is to enclose all the script between and ?>. The following script displays the text in
quotation marks.
EXAMPLE 103
echo "My first PHP script."; ?>
The second option little bit longer. If one wants to use PHP to generate XMLdocuments,
use the opening tag
The most important expression in PHP is semicolon (;). Each function, line, declaration
must be separated by the semicolon. It can be compared to the CSS (when properties omit the
semicolon, the browser does not understand them). Whenever a script is not working, try to
check, where semicolon has been forgotten.
Petr Suchánek, Jan Górecki; Portal and its Management
- 57 It
is useful to write comments in source code. Comments are the text that is omitted by a
browser. Example:
EXAMPLE 105
The most common command used for output is echo(), or, its less common
alternative print():
EXAMPLE 106
");
echo ("display text
");
echo "without the brackets
";
print ("the same");
echo ("you can also use HTML tags");
echo 'you can use single quotation marks';
?>
Multiline text should be split and merged by the dot character. The previous script in the
browser outputs:
this is text on two lines
display text
without the brackets
the same
you can also use HTML tags
you can use single quotation marks
Whenever we output HTML tags with special characters like, e.g., <, >, etc., we must
substitute them by their convenient alternatives. For example, when we output , we must put in PHP echo:
EXAMPLE 107
echo ("<bodybgcolor=\"red\">");
Other example:
EXAMPLE 108
echo "This \" is quotation mark";
4PHP
- 58 -
4.4 VARIABLES
It is hard to imagine a sophisticated PHP script without variables. In PHP, we declare
the variables starting with the dollar sign $. Example:
EXAMPLE 109
$dollar = "1$";
$day="wednesday";
The name of a variable is given right after the $ (without any spaces). We have
introduced two variables: the dollar and the day. Their values are written after the equal sign.
The name of a variable in PHP is case sensitive. Thus, this does not work:
$vari = "abc";
echo $Vari;
Variables are displayed using echo():
EXAMPLE 110
$dollar="1$";
echo($dollar);
echo("$dollar");
echo("I have just " . $dolar . "
");
Variables can be changed using PHP operators.
Table 1: The operators in PHP
Arithmetic operators
$a+$b adds $a to $b
$a-$b subtracts $b from $a
$a/$b divide $a by $b
$a*$b multiplies $a by $b
Assignment operators
$a++ $a = $a + 1
$a-- $a = $a - 1
$a += $b $a = $a + $b
$a -= $b $a = $a - $b
$a *= $b $a = $a * $b
$a /= $b $a = $a / $b
Comparison operators
$a == $b $a is equal to $b
$a != $b $a is not equal to $b
$a > $b $a is higher than $b
$a < $b $a is lower than $b
Logical operators
$a || $b logical, or; returns 1 if at least one of the variables is true
$a && $b logical and; returns 1 if both of the variables are true
Petr Suchánek, Jan Górecki; Portal and its Management
- 59 !$a
negation of $a
In logical comparison, true has the value 1 and false has the value 0.
Variables in PHP are of different types:
Table 2: Variables types
Type Meaning
String E.g. $mystring= "plain text";
Integer Integer, e.g.,$myint = 2;
Float, real or
double
Float number, e.g, 3.14, 0.9, 2.78
Boolean Logical variable, values TRUE, FALSE (1, 0), written as TRUE or
FALSE
Different types of variables are differently introduced:
EXAMPLE 111
$mystring = "plain text";
$myint = 2;
$myfloat = 0.2;
$mylogical = TRUE;
4.5 CONDITIONAL STATEMENTS
Conditional statements manage the flow of the script. Those statements are if,
elseif and switch.
4.5.1 IF
Statement if checks if the given condition is true.
EXAMPLE 112
$a=1;
$b=2;
if($a == $b){
echo ("Variables a and b are equal.");
}
If the variables $a and $b were be equal, the script would display: Variables a
and b are equal. However, it would not happen as the given condition ($a==$b) is
not valid (true).
4.5.2 IF… ELSE
Use the if....else statement to execute some code if a condition is true and
another code if the condition is false. Syntax:
4PHP
- 60 EXAMPLE
113
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20,
and "Have a good night!" otherwise:
EXAMPLE 114
4.5.3 IF...ELSEIF....ELSE
Use the if....else if...else statement to select one of several blocks of code
to be executed. Syntax:
EXAMPLE 115
if (condition1)
{
code to be executed if condition1 is true;
}
else if (condition2)
{
code to be executed if condition1 is false and condition2
is true;
}
else
{
code to be executed if the both conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than
10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have
a good night!":
Petr Suchánek, Jan Górecki; Portal and its Management
- 61 EXAMPLE
116
4.5.4 SWITCH STATEMENT
Use the switch statement to select one of many blocks of code to be executed. Syntax:
EXAMPLE 117
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and
label2;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically. The default
statement is used if no match is found.
EXAMPLE 118
4.6 LOOPS
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal lines in a script we can use loops to perform a
task like this.
In PHP, we have the following looping statements:
while - loops through a block of code while a specified condition is true
do...while - loops through a block of code once, and then repeats the loop
as long as a specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
4.6.1 THE WHILE LOOP
The while loop executes a block of code while a condition is true. Syntax:
EXAMPLE 119
while (condition)
{
code to be executed;
}
The example below first sets a variable i to 1 ($i=1;).Then, the while loop will
continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop
runs:
EXAMPLE 120
";
$i++;
}
?>
Output is:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
4.6.2 THE DO...WHILE STATEMENT
The do...while statement will always execute the block of code once, it will then check
the condition, and repeat the loop while the condition is true. Syntax:
EXAMPLE 121
do
{
code to be executed;
}
while (condition);
The example below first sets a variable i to 1 ($i=1;).
Then, it starts the do...while loop. The loop will increment the variable i with 1, and
then write some output. Then the condition is checked (is i less than, or equal to 5), and the
loop will continue to run as long as i is less than, or equal to 5:
EXAMPLE 122
";
}
while ($i<=5);
?>
4PHP
- 64 -
Output is:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
4.6.3 THE FOR LOOP
The for loop is used when you know in advance how many times the script should run.
Syntax:
EXAMPLE 123
for (init; condition; increment)
{
code to be executed;
}
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the iteration)
Note: The init and increment parameters above can be empty or have multiple
expressions (separated by commas).
The example below defines a loop that starts with i=1. The loop will continue to run as
long as the variable i is less than, or equal to 5. The variable i will increase by 1 each time
the loop runs:
EXAMPLE 124
";
}
?>
Petr Suchánek, Jan Górecki; Portal and its Management
- 65 -
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
4.6.4 THE FOREACH LOOP
The foreach loop is used to loop through arrays. Syntax:
EXAMPLE 125
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value
(and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the
next array value.
The following example demonstrates a loop that will print the values of the given array:
EXAMPLE 126
";
}
?>
Output is:
one
two
three
4PHP
- 66 -
4.7 PHP FUNCTIONS
The real power of PHP comes from its functions. In PHP, there are more than 700
built-in functions.
4.7.1 PHP FUNCTIONS
In this chapter we will show you how to create your own functions. To keep the script
from being executed when the page loads, you can put it into a function. A function will be
executed by a call to the function. You may call a function from anywhere within a page.
4.7.2 CREATE A PHP FUNCTION
A function will be executed by a call to the function. Syntax:
EXAMPLE 127
function functionName()
{
code to be executed;
}
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
A simple function that writes my name when it is called:
EXAMPLE 128
Output:
Petr Suchánek, Jan Górecki; Portal and its Management
- 67 My
name is Kai Jim Refsnes
4.7.3 PHP FU NCTIONS – ADDING PARAMETERS
To add more functionality to a function, we can add parameters. A parameter is just like
a variable. Parameters are specified after the function name, inside the parentheses.
The following example will write different first names, but equal last name:
EXAMPLE 129
";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
Output:
My name is Kai Jim Refsnes.
My sister's name is HegeRefsnes.
My brother's name is Stale Refsnes.
The following function has two parameters:
EXAMPLE 130
";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
4PHP
- 68 -
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
Output:
My name is Kai Jim Refsnes.
My sister's name is HegeRefsnes!
My brother's name is StåleRefsnes?
4.7.4 PHP FUNCTIONS - RETURN VALUES
To let a function return a value, use the return statement.
EXAMPLE 131
Output:
1 + 16 = 17
4.8 ARRAYS
An array stores multiple values in one single variable. Example:
EXAMPLE 132
What is an Array? An array is a special variable, which can hold more than one value at
a time. If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300? The solution is to create an array! An array can hold many values
under a single name, and you can access the values by referring to an index number.
In PHP, the array() function is used to create an array:
EXAMPLE 133
$myarray = array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
4.8.1 INDEXED ARRAYS
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
EXAMPLE 134
$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
EXAMPLE 135
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements
to it, and then prints a text containing the array values:
4PHP
- 70 EXAMPLE
136
4.8.2 GET THE LENGTH OF AN ARRAY - THE COUNT() FUNCTION
The count() function is used to return the length (the number of elements) of an
array:
EXAMPLE 137
4.8.3 LOOP THROUGH AN INDEXED ARRAY
To loop through and print all the values of an indexed array, you could use a for loop,
like this:
EXAMPLE 138
";
}
?>
4.8.4 ASSOCIATIVE ARRAYS
Associative arrays are arrays that use named keys that you assign to them. There are two
ways to create an associative array:
EXAMPLE 139
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
Petr Suchánek, Jan Górecki; Portal and its Management
- 71 EXAMPLE
140
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:
EXAMPLE 141
"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
4.8.5 LOOP THROUGH AN ASSOCIATIVE ARRAY
To loop through and print all the values of an associative array, you could use a foreach
loop, like this:
EXAMPLE 142
"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "
";
}
?>
4.9 PHP INCLUDE FILES
In PHP, you can insert the content of one PHP file into another PHP file before the
server executes it. Include and require statements are used to insert useful codes written in
other files, in the flow of execution.
Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will
continue
So, if you want the execution to go on and show users the output, even if the include file
is missing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP
application coding, always use require to include a key file to the flow of execution. This will
help avoid compromising your application's security and integrity, just in-case one key file is
accidentally missing.
4PHP
- 72 Including
files saves a lot of work. This means that you can create a standard header,
footer, or menu file for all your web pages. Then, when the header needs to be updated, you
can only update the header include file. Syntax:
EXAMPLE 143
include 'filename';
or
require 'filename';
4.9.1 PHP INCLUDE AND REQUIRE STATEMENT
Let see a basic example. Assume that you have a standard header file, called
"header.php". To include the header file in a page, use include/require:
EXAMPLE 144
Welcome to my home page!
Some text.
In another example, assume we have a standard menu file that should be used on all
pages, e.g., "menu.php".
EXAMPLE 145
echo 'Home
Tutorials
References
Examples
About Us
Contact Us';
All pages in the Web site should include this menu file. Here is how it can be done:
EXAMPLE 146
Petr Suchánek, Jan Górecki; Portal and its Management
- 73 Welcome
to my home page.
Some text.
In the third example, assume we have an include file with some variables defined
("vars.php"):
EXAMPLE 147
Then the variables can be used in the calling file:
EXAMPLE 148
Welcome to my home page.
5Form handling using php
- 74 -
5 FORM HANDLING USING PHP
The most important thing to notice when dealing with HTML forms and PHP is that any
form element in an HTML page will automatically be available to your PHP scripts.The
example below contains an HTML form with two input fields and a submit button:
EXAMPLE 149
When a user fills out the form above and clicks on the submit button, the form data is
sent to a PHP file, called "welcome.php":
"welcome.php" looks like this:
EXAMPLE 150
Welcome !
You are years old.
Output could be something like this:
Welcome John!
You are 28 years old.
5.1 PHP $_GET VARIABLE
The predefined $_GET variable is used to collect values in a form with
method="get".Information sent from a form with the GET method is visible to everyone
(it will be displayed in the browser's address bar) and has limits on the amount of information
to send.
EXAMPLE 151
When the user clicks the "Submit" button, the URL sent to the server could look
something like this:
EXAMPLE 152
http://www.domain.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET variable to collect form data (the
names of the form fields will automatically be the keys in the $_GET array):
EXAMPLE 153
Welcome .
You are years old!
When using method="get" in HTML forms, all variable names and values are displayed
in the URL. Thus, this method should not be used when sending passwords or other sensitive
information! However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
Note: The get method is not suitable for very large variable values. It should not be used
with values exceeding 2000 characters.
5.2 PHP $_POST FUNCTION
The predefined $_POST variable is used to collect values from a form sent with
method="post". Information sent from a form with the POST method is invisible to others
and has no limits on the amount of information to send.However, there is an 8 MB max size
for the POST method, by default (can be changed by setting the post_max_size in the
php.ini file).
EXAMPLE 154
When the user clicks the "Submit" button, the URL will look like this:
EXAMPLE 155
http://www.domain.com/welcome.php
5Form handling using php
- 76 The
"welcome.php" file can now use the $_POST variable to collect form data (the
names of the form fields will automatically be the keys in the $_POST array):
EXAMPLE 156
Welcome !
You are years old.
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send. However, because the variables are not displayed
in the URL, it is not possible to bookmark the page.
5.3 PHP $_REQUEST FUNCTION
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST,
and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both
the GET and POST methods.
EXAMPLE 157
Welcome !
You are years old.
Petr Suchánek, Jan Górecki; Portal and its Management
- 77 -
6 MYSQL
6.1 CREATE DATABASE
A database is a way to store lots of information. You might want to store the names and
addresses of all your contacts, or save usernames and passwords for your online forum or
maybe customer information.
In a database, you save the information in a Table. A single database can contain many
tables, and they can be linked together. When the tables are linked together, it's said to be
a relational database. If you just have a single table in your database, then it's called a flat-file
database. Flat-file database are easier to create and understand, so we'll start by creating one
of these using phpMyAdmin.
So bring up phpMyAdmin, if you haven't already done so.
Although it looks a bit muddled, the part to concentrate on is the textbox under the
words create new database, as in the next image (Figure 4):
Figure 4: Editing a name of the new database.
After you have typed a name for your new database, click the "Create" button. You will
be taken to a new area (Figure 5):
Figure 5: Editing name and fields of a table.
In this new area, you can create a Table to go in your database. At the moment, as it
says, there are No tables found in the database. But the database itself has been created.
To create a new table, type a name for it in the box at the bottom. You can also type
a number for the Fields textbox. You can insert for example (Figure 6):
6Mysql
- 78 Figure
6: Example of filling the name and number of fields.
When you've finished, click the Go button. Another, more complex, area will appear
(Figure 7):
Figure 7: Editing the fields in database.
In this new area, you set up the fields in your database. You can specify whether a field
is for text, for numbers, for yes/no values, etc.
Although they are set out in rows in the images, the rows are actually the Columns you
saw earlier – the Fields. Each Field needs a name. So go ahead and type the following for
your Field names:
Figure 8: Editing of the Fields names and Types.
So we have given each column in our table a name: ID, First_Name, Surname, and
Address. The next thing to set is what type of data will be going in to each field - do you
want to store text in this field, numbers, Yes/No value, etc?
To set the type of data going into a field, you select an item from the Type drop down
list. Click the down arrow to see the following list you can choose from (Figure 9):
Petr Suchánek, Jan Górecki; Portal and its Management
- 79 Figure
9: A List of the Field Types.
As you can see from the image above, there's quite a lot! But you won't use most them.
For the values we have in our four fields, we want to hold these Types:
ID – A number, used just to identify each record. This needs to be unique for each record;
First_Name – Text;
Surname – Text;
Address – Text.
If you look at the list, there is an INT but no Number; and there are four different Text
Types to choose from. We can use INT (meaning integer) for the numbers, but again, there
are a few Integer Types to choose from. And that's leaving out things like float and double.
Here's the difference between them, though.
6.1.1 INTEGER VALUES
TINYINT Signed: -128 to 127. Unsigned: 0 to 255;
SMALLINT Signed: -32768 to 32767. Unsigned: 0 to 65535;
MEDIUMINT Signed: -8388608 to 8388607. Unsigned: 0 to 16777215;
INT Signed: -2147483648 to 2147483647. Unsigned: 0 to 4294967295;
BIGINT Signed: -9223372036854775808. Unsigned: 0 to 18446744073709551615.
The signed and unsigned are for minus and non minus values. So if you need to store
negative values, you need to be aware of the signed ranges. If you were using a TINYINT
value, for example, you can go from minus 128 to positive 127. If you didn't need the minus
value, you can go from 0 to positive 255.
For our address book, we have an ID field. We're using this just to identify a record
(row). Each record will be unique, so it will need a different number for each. We can set it to
one of the INT values. But which one?
If we set ID to TINYINT, then you'd run in to problem if you tried to store more than
255 records. If you used SMALLINT, you'd have problems if you tried to stored the details of
6Mysql
- 80 friend
number 65536. IF you have more than 65 and half thousand friends, then you need
a different INT type. We'll assume that you don't, so we'll use SMALLINT.
We've only set Lengths for the VARCHAR TYPES. If you leave it blank for
VARCHAR, you'll get a default value of 1 character.
6.1.2 TEXT TYPES
The length for the text types can be quite confusing. The MySQL manual says this
about the various lengths that each text type can hold:
TINYTEXT L+1 byte, where L < 2^8;
TEXT L+2 bytes, where L < 2^16;
MEDIUMTEXT L+3 bytes, where L < 2^24;
LONGTEXT L+4 bytes, where L < 2^32.
This in not terribly helpful for beginners! So what does it mean. Well, the L + 1 part
means, "The length of the string, plus 1 byte to store the value." The translated values for each
are approximately:
TINYTEXT 256 bytes;
TEXT 64 KiloBytes;
MEDIUMTEXT 16 MegaBytes;
LONGTEXT 4 GigaBytes.
To confuse the issue even more, you can also use CHAR and VARCHAR to store your
text. These are quite useful, if you know how many characters you want to store. For
example, for a UK postcode you don't need more than 9 characters, and one of those will be a
blank space. So there's no sense in setting a postcode field to hold 4 gigabytes! Instead, use
CHAR or VARCHAR.
6.1.3 CHAR
You specify how many characters you want the field to hold. The maximum value is
255. For example:
CHAR(10)
This field can then hold a maximum of ten characters. But if you only use 4 of them, the
rest of the 10 characters will be blank spaces. The blank spaces get added to the right of your
text:
"TEXT "
"TENLETTERS"
VARCHAR
Like CHAR, but the rest of the characters are not padded with blank spaces. The
maximum value before MySQL 5.0.3 was 255. After this it's jumped to 65, 535. With
VARCHAR, there is also an extra byte that records how long your text is.
Petr Suchánek, Jan Górecki; Portal and its Management
- 81 For
our fields, then, we'll use the following Types:
ID SMALLINT;
First_Name VARCHAR;
Surname VARCHAR;
Address TINYTEXT.
So select these from your Types drop down list:
Figure 10: Editing of the Tapes and Lenght / Values.
We've only set Lengths for the VARCHAR TYPES. If you leave it blank for
VARCHAR, you'll get a default value of 1 character.
The other Fields are Null, Default and Extra.
Null - This is an important field in database terminology. It essentially means, "Should the
field contain anything?" If you set a field to NOT NULL, then you can't leave it blank
when you come to adding records to your database. Otherwise you'll get errors.
Default - Do you want to add anything to the field, just in case it's left blank when adding
a record? If so, type it in here.
Extra - This is where you can set an auto increment value. This means adding one to the
previous record number. This is ideal for us, as we have an ID field. Then we don't have to
worry about this field. MySQL will take care of updating it for us.
Figure 11: Icons Primary Key, Index, and Unique.
The three icons are Primary Key, Index, and Unique (Figure 11). Primary keys are not
terribly important for flat-file databases like ours. But they are important when you have more
than one table, and want to link information. They are set to unique values, like our ID field.
An index is useful for sorting information in your tables, as they speed things up. Unique is
useful for those fields when there can't be any duplicate values.
So, set a primary key for the ID field by selecting the radio button, and choose Auto
Increment. Your field screen then, minus the parts we've ignored, should look like this:
6Mysql
- 82 Figure
12: Editing of the Fields, Types and Extra.
Bear in mind what we've done here: we've just set up the fields for our table, and
specified the kind of information that will be going into each field (the columns). We haven't
yet added any information to the table.
Click the Save button on the fields screen. You'll be taken back to the Structure screen.
There should be a lot more information there now. Don't worry if it looks a bit confusing. All
we want to do is to add one record to the table. We'll then use PHP code to add some more.
6.2 CONNECT TO THEMYSQL SERVER
6.2.1 OPEN A CONNECTION TO THE MYSQL SERVER
Before we can access data in a database, we must open a connection to the MySQL
server. In PHP, this is done with the mysqli_connect() function. Syntax:
EXAMPLE 158
mysqli_connect(host,username,password,dbname);
Table 2: The connection parameters
Parameter
Description
host Optional. Either a host name or an IP address
username Optional. The MySQL user name
password Optional. The password to log in with
dbname Optional. The default database to be used
when performing queries
Note: There are more available parameters, but the ones listed above are the most
important.
In the following example we store the connection in a variable ($con) for later use in the
script:
EXAMPLE 159
6.2.2 CLOSE A CONNECTION
The connection will be closed automatically when the script ends. To close the
connection before, use the mysqli_close() function:
EXAMPLE 160
6.3 CREATE DATABASE AND TABLES
6.3.1 CREATE A DATABASE
The CREATE DATABASE statement is used to create a database table in MySQL. We
must add the CREATE DATABASE statement to the mysqli_query() function to execute
the command. The following example creates a database named "my_db":
EXAMPLE 161
6.3.2 CREATE A TABLE
The CREATE TABLE statement is used to create a table in MySQL. We must add the
CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns. The column
names will be "FirstName", "LastName" and "Age":
EXAMPLE 162
Note: When you create a database field of type CHAR, you must specify the maximum length
of the field, e.g. CHAR(50).
Petr Suchánek, Jan Górecki; Portal and its Management
- 85 The
data type specifies what type of data the field can hold. We describe only 2 data types,
which are needed for our purposes in this text.
Table 3: Data types
Data type
Description
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED
(The integer types have an extra option called UNSIGNED. Normally,
the integer goes from an negative to positive value. Adding the
UNSIGNED attribute will move that range up so it starts at zero
instead of a negative number). The maximum number of digits may be
specified in parenthesis
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up
to 255 characters. Note: If you put a greater value than 255 it will be
converted to a TEXT type
6.3.3 PRIMARY KEYS AND AUTO INCREMENT FIELDS
Each table in a database should have a primary key field. A primary key is used to
uniquely identify the rows in a table. Each primary key value must be unique within the table.
Furthermore, the primary key field cannot be null because the database engine requires a
value to locate the record.
The following example sets the PID field as the primary key field. The primary key
field is often an ID number, and is often used with the AUTO_INCREMENT setting.
AUTO_INCREMENT automatically increases the value of the field by 1 each time a new
record is added. To ensure that the primary key field cannot be null, we must add the NOT
NULL setting to the field:
EXAMPLE 163
$sql = "CREATE TABLE Persons
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
FirstNameCHAR(15),
LastNameCHAR(15),
Age INT
)";
6.4 INSERT INTO
The SQL statement INSERT INTO is used to insert new records in a table.
6.4.1 INSERT DATA INTO A DATABASE TABLE
The INSERT INTO statement is used to add new records to a database table. It is
possible to write the INSERT INTO statement in two forms. The first form doesn't specify
the column names where the data will be inserted, only their values:
6Mysql
- 86 EXAMPLE
164
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
EXAMPLE 165
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
To get PHP to execute the statements above we must use the mysqli_query()
function. This function is used to send a query or command to a MySQL connection.
In the previous chapter we created a table named "Persons", with three columns;
"FirstName", "LastName" and "Age". We will use the same table in this example. The
following example adds two new records to the "Persons" table:
EXAMPLE 166
6.4.2 INSERT DATA FROM A FORMINTO A DATABASE
Now we will create an HTML form that can be used to add new records to the
"Persons" table. Here is the HTML form:
EXAMPLE 167
Petr Suchánek, Jan Górecki; Portal and its Management
- 87
When a user clicks the submit button in the HTML form in the example above, the form
data is sent to "insert.php".The "insert.php" file connects to a database, and retrieves the
values from the form with the PHP $_POST variables.Then, the mysqli_query()
function executes the INSERT INTO statement, and a new record will be added to the
"Persons" table.
Here is the "insert.php" page:
EXAMPLE 168
6.5 SELECT
6.5.1 SELECT DATA FROM A DATABASE TABLE
The SELECT statement is used to select data from a database. Syntax:
6Mysql
- 88 EXAMPLE
169
SELECT column_name(s)
FROM table_name
To get PHP to execute the statement above we must use the mysqli_query()
function. This function is used to send a query or command to a MySQL connection.
The following example selects all the data stored in the "Persons" table (The * character
selects all the data in the table):
EXAMPLE 170
";
}
mysqli_close($con);
?>
The example above stores the data returned by the mysqli_query() function in the
$result variable.Next, we use the mysqli_fetch_array() function to return the first
row from the recordset as an array. Each call to mysqli_fetch_array() returns the next
row in the recordset. The while loop loops through all the records in the recordset. To print
the value of each row, we use the PHP $row variable ($row['FirstName'] and
$row['LastName']).The output of the code above will be:
Peter Griffin
Glenn Quagmire
6.5.2 DISPLAY THE RESULT IN AN HTML TABLE
The following example selects the same data as the example above, but will display the
data in an HTML table:
Petr Suchánek, Jan Górecki; Portal and its Management
- 89 EXAMPLE
171
Firstname |
Lastname |
";
while($row = mysqli_fetch_array($result))
{
echo "";
echo "" . $row['FirstName'] . " | ";
echo "" . $row['LastName'] . " | ";
echo "
";
}
echo "