Overview of Basic Features of PHP
In this section we give an overview of a few of the features of PHP that
are useful in creating interactive HTML pages. Section 14.3 will focus on how
PHP programs can access databases for querying and updating. We cannot give a
comprehensive dis cussion on PHP as there are whole books devoted to this subject.
Rather, we focus on illustrating certain features of PHP that are particularly
suited for creating dynamic Web pages that contain database access commands.
This section covers some PHP concepts and features that will be needed when we
discuss database access in Section 14.3.
1. PHP Variables, Data Types, and Programming Constructs
PHP variable names start with
the $ symbol and can include
characters, letters, and the underscore character (_). No other special characters are permitted. Variable names are case
sensitive, and the first character cannot be a number. Variables are not typed.
The values assigned to the variables determine their type. In fact, the same
variable can change its type once a new value is assigned to it. Assignment is
via the = operator.
Since PHP is directed toward text processing, there are several
different types of string values. There are also many functions available for
processing strings. We only discuss some basic properties of string values and
variables here. Figure 14.2 illustrates some string values. There are three
main ways to express strings and text:
Single-quoted strings. Enclose
the string between single quotes, as in lines 0, 1, and 2. If a single quote is needed within the string, use
the escape char-acter (\) (see line 2).
Double-quoted strings. Enclose strings between double quotes as in line 7. In this case, variable names
appearing within the string are replaced by the values that are currently
stored in these variables. The interpreter identifies variable names within
double-quoted strings by their initial character $ and replaces them with the value in the variable. This is known as interpolating variables within strings. Interpolation does not occur in
single-quoted strings.
Figure 14.2 Illustrating basic PHP string and text values.
print
'Welcome to my Web site.';
print
'I said to him, "Welcome Home"';
print
'We\'ll now visit the next Web site';
printf('The
cost is $%.2f and the tax is $%.2f', $cost, $tax) ;
print
strtolower('AbCdE');
print
ucwords(strtolower('JOHN smith'));
print
'abc' . 'efg'
print
"send your email reply to: $email_address"
print
<<<FORM_HTML
<FORM
method="post" action="$_SERVER['PHP_SELF']">
Enter
your name: <input type="text" name="user_name">
FORM_HTML
Here documents. Enclose a part of a document
between a <<<DOCNAME and end it with a single line
containing the document name DOCNAME. DOCNAME can be any string as long as it used both to start and end the here
document. This is illustrated in lines 8 through 11 in Figure 14.2. Variables
are also interpolated by replacing them with their string values if they appear
inside here documents. This feature is used in a similar way to double-quoted
strings, but it is more convenient for multiple-line text.
Single and double quotes. Single
and double quotes used by PHP to enclose
strings should be straight quotes
("") on both
sides of the string. The text editor that creates these quotes should not
produce curly opening and clos-ing
quotes (“”) around the string.
There is also a string concatenate operator specified by the period (.) symbol, as illustrated in line 6 of Figure 14.2. There are many string
functions. We only illustrate a couple of them here. The function strtolower changes the alphabetic characters in the string to all lowercase,
while the function ucwords
capitalizes all the words in a string. These are illustrated in lines 4 and 5
in Figure 14.2.
The general rule is to use single-quoted strings for literal strings
that contain no PHP program variables and the other two types (double-quoted
strings and here documents) when the values from variables need to be
interpolated into the string. For large blocks of multiline text, the program
should use the here documents style
for strings.
PHP also has numeric data types for integers and floating points and
generally follows the rules of the C programming language for processing these
types. Numbers can be formatted for printing into strings by specifying the
number of digits that follow the decimal point. A variation of the print function called printf (print
formatted) allows formatting of numbers within a string as illustrated in line
3 of Figure 14.2.
There are the standard programming language constructs of for-loops,
while-loops, and conditional if-statements. They are generally similar to their
C language counterparts. We will not discuss them here. Similarly, any value evaluates to true if used as a
Boolean expression except for numeric
zero (0) and blank string, which
evaluate to false. There are also literal true and false values that can be
assigned. The compar-ison operators also generally follow C language rules.
They are == (equal), != (not equal), > (greater
than), >= (greater
than or equal), < (less
than), and <= (less
than or equal).
2. PHP Arrays
Arrays are very important in PHP, since they allow lists of elements.
They are used frequently in forms that employ pull-down menus. A
single-dimensional array is used to hold the list of choices in the pull-down
menu. For database query results, two-dimensional arrays are used with the
first dimension representing rows of
a table and the second dimension representing columns (attributes) within a row.
There are two main types of arrays: numeric and associative. We discuss
each of these in the context of single-dimensional arrays next.
A numeric array associates a
numeric index (or position or sequence number) with each element in the array.
Indexes are integer numbers that start at zero and grow incrementally. An
element in the array is referenced through its index. An associative array provides pairs of (key => value) elements. The value of an
element is referenced through its
key, and all key values in a particular array must be unique. The element
values can be strings or integers, or they can be arrays themselves, thus
leading to higher dimensional arrays.
Figure 14.3 gives two examples of array variables: $teaching and $courses. The
first array $teaching is
associative (see line 0 in Figure 14.3), and each element associates a course
name (as key) with the name of the course instructor (as value). There are
three elements in this array. Line 1 shows how the array may be updated. The
first command in line 1 assigns a new instructor to the course ‘Graphics’ by
updating its value. Since the key value ‘Graphics’ already exists in the array,
no new element is created but the existing value is updated. The second command
creates a new element since the key value ‘Data Mining’ did not exist in the
array before. New elements are added at the end of the array.
If we only provide values (no keys) as array elements, the keys are
automatically numeric and numbered 0, 1, 2, .... This is illustrated in line 5
of Figure 14.3, by the $courses array.
Both associative and numeric arrays have no size limits. If some
value of another data type, say an integer, is
assigned to a PHP variable that was holding an array, the variable now holds
the integer value and the array contents are lost. Basically, most variables
can be assigned to values of any data type at any time.
There are several different techniques for looping through arrays in
PHP. We illustrate two of these techniques in Figure 14.3. Lines 3 and 4 show
one method of looping through all the elements in an array using the foreach construct, and Figure 14.3
Illustrating basic PHP
array processing.
0)
$teaching = array('Database' => 'Smith', 'OS' => 'Carrick', 'Graphics'
=> 'Kam');
$teaching['Graphics']
= 'Benson'; $teaching['Data Mining'] = 'Kam';
sort($teaching);
foreach
($teaching as $key => $value) {
print
" $key : $value\n";}
$courses
= array('Database', 'OS', 'Graphics', 'Data Mining');
$alt_row_color
= array('blue', 'yellow');
for
($i = 0, $num = count($courses); i < $num; $i++) {
print
'<TR bgcolor="' . $alt_row_color[$i % 2] . '">';
print
"<TD>Course $i is</TD><TD>$course[$i]</TD></TR>\n";
}
printing the key and value of each element on a separate line. Lines 7
through 10 show how a traditional for-loop construct can be used. A built-in
function count (line 7) returns the current number of elements in the array,
which is assigned to the variable $num and used to control ending the loop.
The example in lines 7 through 10 also illustrates how an HTML table can
be dis-played with alternating row colors, by setting the two colors in an
array $alt_row_color (line 8).
Each time through the loop, the remainder function
$i % 2 switches from one row (index 0)
to the next (index 1) (see line 8). The color is assigned to the HTML bgcolor
attribute of the <TR> (table
row) tag.
The count function (line 7) returns the current number of elements in
the array. The sort function (line 2) sorts the array based on the element
values in it (not the keys). For associative arrays, each key remains
associated with the same element value after sorting. This does not occur when
sorting numeric arrays. There are many other functions that can be applied to
PHP arrays, but a full discussion is out-side the scope of our presentation.
3. PHP Functions
As with other programming languages, functions can be defined in PHP to better structure a complex
program and to share common sections of code that can be reused by multiple
applications. The newer version of PHP, PHP5, also has object-oriented
features, but we will not discuss these here as we are focusing on the basics
of PHP. Basic PHP functions can have arguments that are passed by value. Global variables can be accessed within functions.
Standard scope rules apply to variables that appear within a function and
within the code that calls the function.
We now give two simple examples to illustrate basic PHP functions. In
Figure 14.4, we show how we could rewrite the code segment P1 from Figure
14.1(a) using functions. The code segment P1 in Figure 14.4 has two functions:
display_welcome() (lines 0
to 3) and display_empty_form() (lines 5
to 13). Neither of these functions has arguments nor do they have return
values. Lines 14 through 19 show how we can call these functions to produce the
same effect as the segment of code P1 in Figure 14.1(a). As we can see in this
example, functions can be used just to make the PHP code better structured and
easier to follow.
A second example is shown in Figure 14.5. Here we are using the $teaching array introduced in Figure 14.3. The function course_instructor() in lines 0 to 8 in Figure 14.5 has two arguments: $course (a string holding a course name) and $teaching_assignments
(an associative array holding course assignments,
similar to the $teaching array
shown in Figure 14.3). The function finds the name of the instructor who
teaches a particular course. Lines 9 to 14 in Figure 14.5 show how this
function may be used.
The function call in line 11 would return the string: Smith is teaching Database, because the
array entry with the key ‘Database’ has the value ‘Smith’ for instructor. On
the other hand, the function call on line 13 would return the string: there is no Computer Architecture course because there is no entry in the array
with the key
Figure 14.4
Rewriting program segment
P1 as P1 using functions.
//Program
Segment P1':
function
display_welcome() {
print("Welcome, ") ;
print($_POST['user_name']);
}
4)
function
display_empty_form(); {
print
<<<_HTML_
<FORM
method="post" action="$_SERVER['PHP_SELF']">
Enter
your name: <INPUT type="text" name="user_name">
<BR/>
<INPUT
type="submit" value="Submit name">
</FORM>
_HTML_;
}
if
($_POST['user_name']) {
display_welcome();
}
else
{
display_empty_form();
}
Figure 14.5
Illustrating a function
with arguments and return value.
function
course_instructor ($course, $teaching_assignments) {
if
(array_key_exists($course, $teaching_assignments)) {
$instructor
= $teaching_assignments[$course];
RETURN
"$instructor is teaching $course";
}
else
{
RETURN
"there is no $course course";
}
}
$teaching
= array('Database' => 'Smith', 'OS' => 'Carrick',
'Graphics'
=> 'Kam');
$teaching['Graphics']
= 'Benson'; $teaching['Data Mining'] = 'Kam';
$x
= course_instructor('Database', $teaching);
print($x);
$x
= course_instructor('Computer Architecture', $teaching);
print($x);
‘Computer Architecture’. A few comments about this example and about PHP
func-tions in general:
The built-in PHP array function array_key_exists($k,
$a) returns true if the value in variable $k exists as a key in the associative array in the variable $a. In our example, it checks whether the $course value provided exists as a key in the array $teaching_assignments (line 1
in Figure 14.5).
Function arguments are passed by
value. Hence, in this example, the calls in lines 11 and 13 could not change
the array $teaching provided
as argument for the call. The values provided in the arguments are passed
(copied) to the function arguments when the function is called.
Return values of a function are
placed after the RETURN keyword.
A function can return any type. In this example, it returns a string type. Two
different strings can be returned in our example, depending on whether the $course key value provided exists in the array or not.
Scope rules for variable names
apply as in other programming languages. Global variables outside of the
function cannot be used unless they are
referred to using the built-in PHP array $GLOBALS. Basically, $GLOBALS['abc'] will
access the value in a global variable $abc defined outside the function. Otherwise,
variables appearing inside a function are local even if there is a global
variable with the same name.
The previous discussion gives a brief overview of PHP functions. Many
details are not discussed since it is not our goal to present PHP in detail.
4. PHP Server Variables
and Forms
There are a number of built-in entries in a PHP auto-global built-in
array variable called $_SERVER that can
provide the programmer with useful information about the server where the PHP
interpreter is running, as well as other information. These may be needed when
constructing the text in an HTML document (for example, see line 7 in Figure
14.4). Here are some of these entries:
1. $_SERVER['SERVER_NAME']. This provides the Web site name of the server computer where the
PHP interpreter is running. For example, if the PHP interpreter is running on
the Web site http://www.uta.edu, then this string would be the value in $_SERVER['SERVER_NAME'].
2. $_SERVER['REMOTE_ADDRESS']. This is the IP (Internet Protocol) address of the client user
computer that is accessing the server, for example 129.107.61.8.
3. $_SERVER['REMOTE_HOST']. This is the Web site name of the client user computer, for example
abc.uta.edu. In this case, the server will need to trans-late the name into an
IP address to access the client.
4. $_SERVER['PATH_INFO']. This is the part of the URL address that comes after a backslash (/) at the end of the
URL.
5. $_SERVER['QUERY_STRING']. This provides the string that holds parameters in a URL after a
question mark (?) at the end of the URL. This can hold search parameters, for
example.
6. $_SERVER['DOCUMENT_ROOT']. This is the root directory that holds the files on the Web
server that are accessible to client users.
These and other entries in the $_SERVER array are usually needed when creating the HTML file to be sent for
display.
Another important PHP auto-global built-in array variable is called $_POST. This provides the programmer with input values submitted by the user
through HTML forms specified in the HTML <INPUT> tag and other similar tags. For example, in Figure 14.4 line 14, the
variable $_POST['user_name'] provides
the programmer with the value typed in by the user in the HTML form specified
via the <INPUT> tag on
line 8. The keys to this array are the names of the various input parameters
provided via the form, for example by using the name attribute of the HTML <INPUT> tag as
on line 8. When users enter data through forms, the data values can be stored
in this array.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.