0% found this document useful (0 votes)
22 views13 pages

Web App Prog CH2

Uploaded by

Mr. Shuaimi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views13 pages

Web App Prog CH2

Uploaded by

Mr. Shuaimi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

[Please insert any

relevant photo
around this box]
CHAPTER

2
Programming is the art of
algorithm design and the
craft of debugging errant
code

Learning PHP Basics


Subtopics:-
2.1 How PHP Work
2.2 Add PHP Code to a Web Page File
2.3 Using PHP Statement
2.4 Using PHP Variable
2.5 Work with Numbers, Character String and DateTime
2.6 Modify or Remove Variable
2.7 Using Variable
2.8 Add Comments to Script

2.1 How PHP Work

PHP works in partnership with your Web server to enable you to build interactive, dynamic
web pages. The web server is the software that delivers web pages to users. Every web site
requires a web server, the PHP software works in conjunction with the web server to add
functionality to your web site that is not available using HTML alone.

How the World Wide Web Works

The World Wide Web is a network of computers offering millions of web sites. Each web site
has an address, called a URL (uniform resource locator) which includes a domain name
and filename such www.mygolcompany.com/home.html. When user types a URL into a
browser address window or click a hyperlink the browser sends a message out onto the
10 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
Web requesting the specified Web page. The message is sent to the computer at the
address specified on the URL, where the web server on the address computer receives the
message and searches the web site for the requested web page file. The web server send
the requested it or if the file cannot be found send a message stating that it cannot find the
file. The browser displays the Web page based on the HTML code in the file that it receives.

Figure 2.1: Communication HTML Act as a Client

How the Web Server Process PHP File

The Web Server begins processing the requested file in HTML mode, meaning that it sends
the HTML code directly to the browser. When the Web server encounters a PHP section, it
switches into PHP mode, sometimes called escaping form HTML, and executes the PHP
statements, sending any output to the browser. The Web server continues in PHP mode until
it reaches the end of the PHP section where it returns to HTML mode. The Web server
processes the entire file, switching into PHP mode to process any PHP sections that it finds.
The browser renders and displays all the code it receives as HTML code. The PHP code is
never sent to the browser, the browser only receives the output from the PHP code. Any
formatting instructions sent to the browser must be HTML code. In other words, the output
from the PHP code must be HTML code if it is intended to format the Web page display.

Figure 2.2: Communication PHP Act as a Server

11 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
Adding PHP Code to a Web Site

PHP code is embedded into HTML files. You create and edit PHP files the same way that you
create and edit regular HTML files. Tags mark the beginning and end of the sections
obtaining PHP code. The Web server is configured to look for PHP code embedded in files
with specified extensions, usually .php but the Web server can be configured to specify any
extension or set of extensions that you want to use. When the web server receives a request
for a file with one of the specified extensions it scans the file to PHP sections. Hence, PHP is
a server-side programming language and PHP scripts must live on a server. Thus, PHP scripts
must be run on a web server (e.g. apache) or they won’t work because web server
understands and convert PHP to HTML web pages that browsers understand.

2.2 Add PHP Code to a Web Page File

To use PHP code to add interaction to your Web page, you add PHP sections to your Web
page source file. Each PHP sections in enclosed by PHP tags as follows:
<?php
echo PHP code;
?>

All PHP code must be enclosed in PHP tags. Any code not in PHP is not sent to PHP for
processing. Instead the code is sent directly to the browser, which handles it as HTML code,
displaying the code in the Web page. You can add as many PHP sections as needed. You
can start the script with HTML code. You can include a PHP section, containing PHP code
and closing with PHP tags. The result from the code execution in one PHP section is available
to PHP code in later sections. This means that if you set a variable in one PHP section, the
variable will retain is values in later PHP sections. Using variable is discussed later in next
chapter. You cannot nest PHP section. You must end one PHP section before starting
another PHP section.
Example:
1. Create or open a file containing HTML code only. In example one HTML code display
a line of text.
2. Type the opening tag for a PHP section.
3. Type one or more statements. In example, one PHP echo statement output one line
of text. Type the closing tad for a PHP section.
4. Add a PHP statement after the closing PHP tag.
5. Save the file extension with .php
12 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
6. Open the web page in a browser. The browser display the output form the HTML
section. The browser display the output from the PHP section and display the line after
the PHP section, showing the PHP code (because this was outside the PHP tag, it was
not processed by PHP).

Figure 2.3: PHP code Figure 2.4: Display code

2.3 Using PHP Statements

The PHP section that you add to your HTML file consists of a series of PHP statement. Each
PHP statement instructs PHP to perform an action. Each statement executes in order from
top to bottom or source code file. PHP code consists of simple statement and complex
statement. A simple statement in a single PHP instruction, ending with semicolon (;). When
reading simple statements, PHP ignore white space and the ends of lines continuing to read
the simple statement until it encounters a semicolon or a closing tag (?>). A missing
semicolon is a common error, resulting in an error message.

Complex statements are statements that contain more than one instruction, usually
including more than one simple statement. For example, consider the following complex
statement:
if ($x < 1)
echo 1;
else
echo 2;
This statement echoes 1 if the variable x contains a value less than 1. If the value of x is 1 or
greater the statement echoes 2. Simple statement can be combining into a block, causing
the statement to execute together. Block of statement is often used in complex statement.
In example removing semicolon (;) in line 9 then error message displayed.

13 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
Understanding PHP Output Statement

PHP provides two output statements that output a text string, the echo statement and the
print statement. PHP also provides some built in function such as printf and sprint that
output formatted text string. The general syntax for echo and print is as follows:

echo output1, output2, ……;


$var = print output1;

As shown, echo can output more than one string, whereas print can output only one string.
The print statement, however behaves more like a function than the echo statement. The
print statements always return the value 1, whereas the echo statement does not return a
value.

An output can be a number, string or variable. A string must be enclosed in quotes. A string
can include special formatting characters such as \n, which starts new line. PHP send the
output string from the output statement to the web server, which send it as is to the browser.
The browser interprets the output string as HTML code. And display it accordingly. If an
output string contains HTML tags, the HTML tags the browser interprets the tag when
displaying the web page. If and output string has no HTML tag, the browser just display the
string has ignoring white space and line breaks.
Example:
1. Type an echo statement with one or more output string. You can include a blank a
blank space in the string as shown in line of this example.
2. Type a second echo statement with a new line character in the string.
3. Save and run the browser. The output is displayed on one line because it contains no
HTML tags to format the string in browser window.

14 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
1. View the source code in the browser. The source starts a new line where the new line
special character is inserted. The browser does not display text as it appears in the
source code. The browser fits the text to the browser windows regardless of extra whit
space and line breaks.

2. Edit the echo statement by inserting HTML tags o format the output for the browser.
The output displays differently because of the HTML tags in the strings.

You can use the echo statement with several different formats. You can echo multiples word
by echoing more than one item or by echoing a single string containing words and spaces.

ECHO STATEMENT OUTPUT


echo “Hello”; Hello
echo 100 100
echo “Hello”, “World”; HelloWorld
echo Hello World Not Valid; result in an error message
echo “Hello”, “ World”; Hello World
echo “Hello World”; Hello World

15 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
2.4 Using PHP Variable

Variable are containers that hold information. You can use the information wherever it is
needed in the script. A variable has a name and stores information that a user types into a
form or data retrieved from a database. PHP variable names have a dollar sign ($) in front
of them. Names can be any length and can include letters, numbers or underscores. They
cannot begin with a numbers. PHP distinguishes between upper and lowercase letters.
Consequently NAME and Name are two different variables. Names should represent the value
stored in the variable, so the script is easy to understand. Word connected by underscore
or with the second word capitalized such as $first_name or $firstName are common
variable names.

You assign a value to a variable with an assignment statement. If the variable does not
already exist, the assignment statement creates it. You can assign a number or a character
string to a variable. A character string is enclosed by single or double quotes. You can
display the content of a variable by echoing or printing it. In addition, PHP provides two
functions to display the contents of a variable: var_dump and print_r. The print_r function
displays the variable content. The var_dump function displays the variable content plus the
data type and if the variable value is string. If you attempt to display a variable that does
not exist an error message is displayed.
Example:
1. Add an assignment statement to create a variable. Repeat step 1 for the entire
variable that you want to create.
2. Add and echo statement to display the variable. You need HTML tags to format the
output in the browser.
3. Add one or more print_r statement to display the variable. You need to echo HTML
tags to format the output in the browser.

16 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
4. Add a var_dump statement that displays several variables.
5. View the script in a Web browser. The values of the variable are displayed from the
echo statement and the two functions. The output of the var_dump statement is
displayed on one line because no HTML tags were included in the var_dump
statement.

2.5 Work with Numbers, Character String and DateTime

Number can be either integers or floating point numbers or number with decimal places.
You can do arithmetic operations on numbers. You can add, subtract, multiply or divide
numbers and variable that contains numbers. The following are valid expressions:
2 + 2.5
$price - $discount
$hours * 60
52 / $weeks

PHP provides another operator, % called modulus which finds the reminder when one
number is divided by another number. For example, 9 % 4 evaluates to 1 - the reminder
when 9 is divided by 4. You can combine arithmetic operations as follows:
$result = 1 + 2 * 4 + 1;

When you combine operations, the order in which the individual operations are performed
can affect the result. PHP performs multiplication and division first, followed by addition and
subtraction. If other considerations are equal, PHP goes from left to right. You can change
the other in which the operations are performed by using parentheses. The arithmetic inside
the parentheses is performed first. For example, you can write the preceding assignment
statement as follows:
$result = (1 + 2) * 4 + 1;

17 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
Example:
1. Create some variable that contain numbers.
2. Add an assignment statement using two variable
3. Add an echo statement that displays the result.
4. Add an assignment statement without parentheses that combines operation. Add
an echo statement and display result.
5. View the script in browser. In most cases, the result with and without parentheses are
different.

Character Strings

Character string can include letters, numbers and punctuation. When you store a character
string in a variable, you specify the beginning and end of the string with quotes. A string of
numbers enclosed by quotes is stored as a character string, instead of a number. Number
that you do not plan to use in arithmetical operation such as phone number or zip codes,
should be stored as character strings. When you need to use a quote character inside a
string, you must insert a backslash (\) in front of it, called escaping the quote, so that PHP
handles the embedded quote as part of the string not as the closing quote.

Character strings can be enclosed in single or double quotes, which are handled differently.
Single quoted strings are stored literally with the exception of \’ which is stored as an
apostrophe. In double quoted string, variable and some special character are evaluated
before the string is stored. The quotes that enclose the entire string determine the treatment
of variable and special character even if there are other set of quotes inside the string.

The character \n and \t are the most widely used special character. The \n special
character starts a new line when used in double quoted strings. The \t insert a tab when
used in a double quoted string.
$string = “Welcome to Web Application Programming” . “ ” . $name;
18 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
You can append a string to the end of variable value using the .= operator as follows:
$string = “Welcome to Web Application Programming”;
$string = $name;

Example:
1. Create a variable that contains a string.
2. Create a variable that contain a double quoted string that include the variable from
step 1.
3. Create a variable that contain a single quoted string that include the variable from
step 1.
4. Create a variable that contain a double quoted string with single quotes enclosing a
variable.
5. Add a statement that echoes all three strings. View the script in browser.

Dates and Times

PHP can recognize dates and times and handle them differently than plain character
strings. You can create a variable that contains a specific date and time or the current
data and time. You can display and stored dates in your preferred format. The computer
stores a date/time in a format called a timestamp, which is the number of second from
January 1, 2017 00:00:00 GMT to stored time. This format is convenient for calculating time
spans but is not a desirable format to display on a Web page. PHP can convert dates from
a timestamp into conventional date/time format and vice versa. You can store a
timestamp with the strtotime function, in the following format:
$varname = strtotime (“keywords”);

The strtotime function recognizes the following keyword month, names, the days of week,
all numbers, + or – time units – year, month, week and so on and some useful English word -

19 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
ago, now, last, next this today, tomorrow, and yesterday. You can convert a timestamp to
date/time format with the date function, in the following format:
$varname = date (“format”, $timestamp);

If you do not include $timestamp, the current date/ time is stored. The format is a string that
specifies the format to use when storing the date in the variable. For example, the format
“yy-m-d” stores 06-08-17 and “M.d.y” stores Aug.10.2017.

2.6 Modify or Remove Variable

You can modify a variable value with an assignment statement. The value assigned in the
new assignment statement replaces the current value of the variable. You can also use. =
in an assignment statement to append a value to the end of the current value, rather than
replace the current value. PHP provides some shortcut assignment operator for frequently
used mathematical operation. The ++ operator ($num++) adds 1 to a variable and - -
subtract 1 from a variable. In addition, you can add, subtract, multiply or divide by a
specified number using the following shortcut assignment operator: +=n, -=n, *=n and /=n.
For example, $num+=2 add 2 to $num and $num /=3 divides $num by 3. You can remove the
value from a variable by assigning NULL to the variable. You can also assign a string of zero
length to a variable as follows:
$string = “ ”;

The variable continues to exist but is empty. If you echo the variable, nothing is displayed
on the Web page. No error message is displayed because the variable exists, but no value
is displayed because the variable contains no value. You can destroy a variable so that it
no longer exists at all with the unset statement as follows:
Unset ($varname); If you echo a variable that has been unset, an “undefined variable”
notice is displayed because the variable no longer exists.

2.7 Using variable

PHP lets you use dynamic variable names, called variable variables. You can name a
variable with a value stored in another variable. In other words, one variable contains the
name of another variable. The format for creating variable variables is as follows:
$variable1 = “age”;
$$variable1 = 21;

20 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
The second statement has two dollar sign ($$) in front of the variable name. The second
statement creates a new variable with the name that is the value $variable. The result of
the two assignment statement is a variable named $age that contains the value 21. If you
use variable variables in an echo statement you need to specify the variable name clearly.
You can use one of the following syntax:
echo $$variable1;
echo “${variable1}”;

The following statement will not produce the correct output:


$variable1 = “age”;
$age = 21;
echo “$$variable1”;

In this case, the echo statement reads $variable1 as the variable name and reads the first
$ as a text character. Consequently the output is $age, not 21.

2.8 Add Comment to a Script

Comments are notes that are embedded in the script itself. PHP ignores comments. The
comments provide information to assist the person, whose job it is to understand and revise
the script in the future. Comments are the best to label sections and to explain code that is
unusual or complicated not code that is obvious. You can embed comment anywhere in
your script. Your comment can be as long or short as you need. When PHP encounters code
that indicates the start of comments, it ignores everything until it encounters the code that
indicates the end of a comment. PHP comments are not included in the output that is sent
to the browser, so the user does not see the comments.
21 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s
You can designate a comment block. The character /* signal the start of a comment and
the characters */ signal the end of a comment. The block can span as many lines of text as
necessary. The format for a comment block is
/* …..comment here ……. */

You can also designate a single line comment. The character // and # signal the start of
comment line. PHP ignores the text from the // or the # to the end of the line. The line
following the line containing // or # is not a comment. You can put line comment
characters anywhere in a line, not just at the beginning of the line. The following are valid
comments:
# …..comment here …….
//…..comment here …….
$age = 21; //…..comment here …….

22 | P a g e C h a p t e r 2 : L e a r n i n g P H P B a s i c s

You might also like