You are on page 1of 23

Course Handout Student Notebook

Course Contents
Unit 1: P HP Ba sics 2
Learning Objectives 2
Introduction to PHP 3
Support for Database 3
PHP Installation 3
Working with PHP 4
Why PHP? 6
Basic Syntax of PHP 7
Php Statement terminator and Case insensitivity 7
Embedding P HP in HTML 8
Comments 8
Variables 9
Assigning value to a variable 9
Constants 11
Managing Variables 11
Data Types 13
Summary 20
Self-Assessment Quiz 21
Answers to Self-Assessment Quiz 23

Copyright IBM Corp. 2011 Course Contents 1


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
PHP Core Student Notebook

Unit 1: PHP Basics


Learning Objectives

At the end of this unit, you will be able to:

Understand what is PHP


Install the PHP software and learn how to use the same
Understand the basic syntax and data types supported in PHP
Create a Sample PHP page and execute it on the Server

Copyright IBM Corp. 2011 Unit 1 PHP Basics 2


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Introduction to PHP
What is PHP?
PHP:
stands for Hypertext Preprocessor
is a server-side scripting language
supports many different databases
is an open source software

PHP is a powerful tool to create interactive web application.


Apart from the normal text and HTML tags placed in a web page, a PHP file cont ains commands that are
executed on the server side. The server executes these commands before it renders the response page to the
user.
When a URL is typed on the browser for a PHP page, the following occurs
A request is sent to the browser requesting for that page
The server executes the PHP scripts on that file if any and sends the response to the browser
The browser executes the HTML tags in that page and renders the response to the end user
Support for Database
A Web Application normally requires data to be made persistent for accessing and manipulating it in the future.
A typical web application scenario would be an Online Shopping Cart application, which maintains its customers
information and allows them to shop products online.
PHP supports many databases like MYSQL, Oracle, Sybase, Informix, etc.

PHP Installation
The most preferred method to install PHP is by using the WAMP (Windows, Apache, MySQL, and PHP) server
since it provides an all-in-one solution.
WampServer 2.0i for Windows Platform includes
Apache 2.2.11
MySQL 5.1.36
PHP 5.3.0
To download the WAMP server http://www.wampserver.com/en/#download-wrapper
To download Lamp (Linux, Apache, MySQL, PHP) server for Linux Platform http://lamphowto.com/
Have a Web Server already?
If you already have a Web Server that supports PHP
Install PHP
Download PHP for free here: http://www.php.net/downloads.php
Install any database supported by PHP, for example MySQL
Download MySQL for free here:http://www.mysql.com/downloads/

3 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Download Apache for free here:http://httpd.apache.org/download.cgi

Working with PHP


http://www.homeandlearn.co.uk/php/php1p3.html
We will be referring the wamp server for working with PHP throughout this book

1. Download the WAMP server

2. Run the installation wizard and follow the instructions to install the WAMP server

3. By default the WAMP server will be installed in the C:/ drive, i.e. C:/wamp. , If we have not mentioned
any other folder during installation
After Installing the Wamp Server, the following icon appears in the bottom right corner of the task bar

The wamp server icon can be


Partially red
Partially yellow
White

Initially the icon will be partially red. This means no service is currently running. If we click on the wamp server
icon a pop up menu will appear as follows. Select the Start all services option.

The color of the icon should now change to white, which means all services are currently running.
If the color of the icon is partially yellow, then not all services are running which means that either the Apache or
MYSQL service hasnt started. To start them
Click on the wamp server icon, select Apache Service Start/Resume service
Click on the wamp server icon, select MySQL Service Start/Resume service

Copyright IBM Corp. 2011 Unit 1 PHP Basics 4


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

To ensure that the server is running, click on the wamp server icon and select Localhost.The homepage of the
wamp server should be displayed on the web browser as follows

To run a Sample PHP Program


Create a folder called PHP Programs in c:\wamp\www folder
Create a file called MyFirstPhp.php file and type the following code
<?php
print "PHP is a Server-side HTML embedded scripting language";
?>
To execute the PHP program;
Click on the Wamp server icon and select Localhost. We will now have the folder called PHP displayed on the
wamp servers home page.

5 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Click on the PHP folder under Your Projects. The PHP files available in that folder will be displayed. Click on t he
MyFirstPHP.php file. We can see the following output on the web browser.

Why PHP?
PHP:

runs on many different operating system platforms (Windows, Linux, Unix, etc.)

is compatible with almost all servers available and used today (Apache, IIS, etc.)

is free of cost and can be downloaded from the official PHP resource: www.php.net

Copyright IBM Corp. 2011 Unit 1 PHP Basics 6


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

is an open source software where we are free to add or modify the features of the s oftware

syntax is based on programming languages like C and PERL.

is easy to learn and it runs efficiently on the server side

Basic Syntax of PHP


PHP file normally contains HTML tags and PHP Scripting tags
PHP Scripting Elements should be enclosed within
<?php

?>
Example1.1: Display a Message in the Web Browser
<?php
echo "Welcome to PHP Programming!!!!"
?>
Output on the Web Browser

Php Statement terminator and Case insensitivity


Every Statement in PHP has to be terminated by a semicolon
<?php
echo "PHP Learning time";
echo "All statements have to be terminated by a semicolon(;)";
?>
PHP keywords and function names are case insensitive
The following statements convey the same meaning to the PHP interpreter
echo strlen("hello");
echo STRLEN("hello");
ECHO strLEN("hello");

7 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Embedding PHP in HTML


A PHP code can be embedded in HTML using the PHP Scripting block <?php ?>
<html>
<font color="red">
<?php
echo "PHP is a HTML embedded scripting language..";
?>
</font>
</html>
The message will be displayed on the Web Browser in Red.
Alternatively a PHP scripting block can also include the HTML tag enclosed within quotes (single or double)
<html>
<font color="red">
<?php
echo "PHP is a HTML embedded scripting language";
echo "<br>";
echo "It is used to create dynamic web pages";
?>
</font>
</html>
There can be multiple PHP Blocks within the same file. The above code can also be written as
<html>
<font color="red>
<?php
echo "PHP is a HTML embedded scripting language";
?>
<br/>
<?php
echo "It is used to create dynamic web pages";
?>
</font>
</html>

Comments
Comments are used to explain the code and make it more readable. The PHP interpreter generally ignores
comments.
PHP supports 2 types of comments
Single line comment - //

Copyright IBM Corp. 2011 Unit 1 PHP Basics 8


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

//Comments can be short and crisp.


Multi line comment - /* */
/*
This is a Multi Line Comment.
-Can be used if explanation requires more than one line
-Can be used to temporarily turn off a block of code
*/

Variables
Variables are used to store data that is manipulated throughout the program. All Variables in PHP have to be
declared using the $ symbol
Syntax for declaring a variable
$variablename= value
Variables in PHP need not be declared for assigning a value to it
Variables in PHP are not associated with a particular data type
PHP variables are associated with the data type depending on the value assigned to it from time to time
Rules for Declaring a Variable
A variable name:
must start with a letter of the alphabet or an underscore "_"
can contain alpha numeric characters (a-z, A-Z, 0-9, and _)
should not contain spaces.
Assigning value to a variable
$country=India;
$order_no=122;
$course_fee=20754.75
Illegal Variable names
$+23
$12
$1ABC
Example1.2 Calculating area of a circle
<html>
<body>
<font face="arial">
<h3><b><i>Calculate Area of Circle</i></b></h3>
<?php
$PI=3.14;
$area=0;
?>

9 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

<?php
$radius=3;
$area=$PI*$radius*$radius;
print "PI Value:".$PI."<br>";
print "Radius Value:".$radius."<br>";
print "Area Of Circle(PI*radius*radius) :".$area;
?>
</font>
</body>
</html>
Output on the Web Browser

Indirect reference to Variables


PHP helps us to create variables and access them by name at run time
Example 1.3: Print message to welcome the user
<?php
$name="username";
$$name="Peter";
print "Welcome ".$username;
?>
Output from the Web Browser

Copyright IBM Corp. 2011 Unit 1 PHP Basics 10


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Constants
PHP constants are variables that have a single value through out their lifetime in the program.
The naming rules for PHP variables applies to constants also except that they dont have a leading $ (dollar)
sign. By convention constants are declared in uppercase. Constants have global scope, so they are accessible
anywhere in the PHP scripts, even inside functions
Although we can define case insensitive constants, it is recommended to use case sensitive constants for it will
be consistent and clear when used in the code
A Constant can be declared using the following syntax
define("CONSTANT_NAME", value [, case_insensitive])
where
"CONSTANT_NAME" is a string.
value is any valid PHP expression excluding arrays and objects.
case_insensitive is a Boolean value (true/false) and is optional. The default value is false

$purchase_amount=1000;

define ("DISCOUNT_PE RCE NT",20);

$discount_amount=$purchase_amount*DISCOUNT_PE RCE NT/100;

echo $discount_amount;
An example for a built-in constant is the Boolean value true, which is defined as case-insensitive.

Managing Variables
The following language constructs helps us to
Check if variable exist
Remove variable
Check variables Truth values
isset() returns a Boolean value depending on the variables existence in a PHP

11 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

<?php
$message="hello";
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';
echo "<br>";
if(isset($message1))
print 'Variable $message1 exist';
else
print 'Variable $message1 does not exist';
?>

unset() undeclares an already set variable, and frees any memory that was used by it. Calling isset() on a
variable that has been unset() returns false.
unset($message);
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';

empty() is used to check if a variable has not been declared or its value is false. Generally it is used to check if a
form variable does not contain any data or it has not been sent. The variables value will be converted to
Boolean according to the rules and then it will be checked for truth-value. The rules for Boolean Conversion will
be discussed in the Data Type section
if (empty($message)) {

Copyright IBM Corp. 2011 Unit 1 PHP Basics 12


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

print 'Sorry!! No message given';


}
The empty() method evaluates to true if $message does not contain a value that evaluates to true.

Data Types
PHP supports 8 different data types
Integers
Integers are whole number without a decimal point
int $discount=3000
Read Formats: Integers can be read in three formats
decimal (base 10)
octal (base 8)
hexadecimal (base 16).
Decimal format is the default reading format. Octal integers are specified with a leading 0 and hexadecimals
have a leading 0x.
Note that the read format affects only how the integer is converted as it is readthe value stored in $integer_8
does not remember that it was originally written in base 8.
Range of Integer Data type
PHP integers correspond to the C long type, which in turn depends on the word-size of the machine. For most
common platforms, however, the largest integer is 2 1 (or 2,147,483,647) and the smallest integer is (231 1)
(or 2,147,483,647)
<?php
$integer_10 =-1000;
$integer_8 = 01000;
$integer_16 = 0x1000;
print "integer in decimal format (base 10): $integer_10<BR>";
print "integer in octal format (base 8): $integer_8<BR>";
print "integer in hexadecimal format (base 16): $integer_16<BR>";
?>

13 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Output in the Web Browser

Double
Double values are floating-point numbers
$interest_rate=2.5;
$salary=170000.75;
$temp=52.6E2;
Range of Double
Range of Double is equivalent to C compilers double data type.On common platforms it has a range of
approximately 2.2E308 to 1.8E+308
Boolean
Booleans have only two possible values: TRUE and FALSE.
$status=true;
Boolean constants
PHP also provides Boolean constants TRUE and FALSE
if (true)
print("print when condition is true <br>");
else
print("print when condition is false<br>");
Boolean Rules
The following are the rules by which the truth of a non-boolean value is determined
For Numbers ,all values other than zero evaluate to true and zero evaluates to false
Empty String(has zero characters) and String with the value 0 are evaluated to false, All other Strings
are evaluated to true
NULL values evaluate to false
For compound types like array or an object ,empty array and object(no values) evaluate to false

Copyright IBM Corp. 2011 Unit 1 PHP Basics 14


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Array and Objects with values evaluate to true. An object contains value, if any one of its member
variable is assigned a value
Valid resources are true (although some functions that return resources when they are successful, will
return FALSE when unsuccessful).
Boolean Rules Summary

Data Type False True


Integer 0 All non-zero values
Floating-Point 0.0 All non-zero values
String Empty String: All other Strings
String with value 0: 0
Null Always false Will never be True
Array Empty Array An array with one element atleast
Object Never Always
Resource Never Always

$received=0;
if($received)
print "Product shipped successfully";
else
print "Shipment is pending";
will produce the output: Shipment is pending
NULL
The type NULL takes only one possible value called NULL.NULL indicates an unassigned value, unknown value,
no value or lack of value. NULL is a PHP constant and is case insensitive.
The following assignment statements conveys the same meaning to PHP interpreter, that the des ignation is not
assigned yet
$designation=null;
$designation=NULL;
A Variable when assigned NULL
evaluates to FALSE in a Boolean context.
returns FALSE when tested with IsSet().
PHP will not give any warnings when a NULL value is passed or returned from a function. But it might
sometimes give warnings for a variable that has never been set ,if passed or returned from a function
String

Strings are sequences of characters.


$message=Knowledge is Power!!!

15 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Strings can be enclosed in either single or double quotation marks with a different interpretation during read
time. Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their
values and treat certain specially interpreted character sequences in a different way.
Single Quoted and Double Quoted Strings
Single Quoted Strings read and store their values literally apart from treating few specially interpreted character
sequences in a different way
$message='A Clever person solves a problem. A Wise person avoids it';
print 'Albert Einstein says, $message';

The output for the above code will be


Albert Einstein says, $message

We can use a double quote within a single quote.


print 'Albert Einstein says, "A Clever person solves a problem. A Wise person
avoids it"';

The output for the above code will be


Albert Einstein says, "A Clever person solves a problem. A Wise person avoids
it"

To use a single quote in a single quoted string, escape it with the backslash. To escape a back slash we can use
\\
$msg=' \' can be used with in \'\' by escaping it using \\';
print $msg;

The output for the above code will be


' can be used with in '' by escaping it using \

Here-Docs
Helps us to include large pieces of text in our scripts, which may include lots of double quotes and single quotes,
without having to escape them.

print <<<string_here
Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo!
wherefore art thou Romeo?" and "But, for my own part, it was Greek to me"
form some of literature's most celebrated lines. Many expressions that we use
every day is from William Shakespeare's plays. But we are unaware that we

Copyright IBM Corp. 2011 Unit 1 PHP Basics 16


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

are 'borrowing' sayings from his work!


string_here;

The output for the above code will be


Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo!
wherefore art thou Romeo?" and "But, for my own part, it was Greek to me"
form some of literature's most celebrated lines. Many expressions that we use
every day is from William Shakespeare's plays. But we are unaware that we are
'borrowing' sayings from his work!
Ensure that the String starts with <<<, followed by a string(Example: string_here) that does not appear in our
text. It is terminated by writing that string (Example: string_here) at the beginning of a line, followed by an
optional semicolon (;), and then a required newline (\n). Escaping and variable substitution in here-docs is
identical to double-quoted strings except that we are not required to escape them

Accessing Characters in String

Individual Characters within a string can be accessed using $str(offset) format. We can use this notation to write
and read a String.
To Write String Characters:
$msg="H";
$msg{1}="e";
$msg{2}="l";
$msg{3}="l";
$msg{4}="o";
echo $msg;

will produce the output


Hello
For reading a character in String, we should use only valid offset/index. String index starts with 0
$wish="Happy Birthday!";
echo $wish{0}; //will produce the output: H
echo $wish{14}; //will produce the output: !
echo $wish{15}; // error

Output Function

Echo and Print are the 2 the output statements available in PHP.They can be used with or without parenthesis.
The following statements prints the output on the web browser
echo "hello"; // will produce the output : hello

17 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

echo ("hello"); // will produce the output: hello


Echo
We can have Multiple Arguments for the echo, when used without parenthesis
echo "Everything is okay in the end, if it's not ok, then it's not the
end.","<br>","Never Give UP!!!";
However, echo when used with parenthesis, can accept only one argument. The above statement produces an
error when used with parenthesis
echo ("Everything is okay in the end, if it's not ok, then it's not the
end.","<br>","Never Give UP!!!");
Print
The print statement is very similar to echo, with two important differences:
Unlike echo, print can accept only one argument.
Unlike echo, print returns a value, which represents whether the print statement was successful or not.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful.
Print 24.5;
Print 'c';
Resources
Are special data type, represent a PHP extension resource such as a database query, an open file, a database
connection, and lots of other external types.
Array
An array is a collection of key/value pairs. An array maps keys (or indexes) to values. An array index can either
be an integer or string whereas the value of an array can be of any type (including other arrays).
$fruits=array("apple","mango","grapes");
echo $fruits[0];

will display apple


Object
Objects are instances of programmer-defined classes, which can package both values and functions
that are specific to the class
<?php
class Employee
{
var $id=0;
var $name=null;
}
$empobj=new Employee();
$empobj->id=1;

Copyright IBM Corp. 2011 Unit 1 PHP Basics 18


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

$empobj->name="Sam";
echo "Employee id:".$empobj->id;
echo <br>;
echo "Employee Name:".$empobj->name;
?>

Will produce an output on the web browser as


Employee id: 1
Employee Name: Sam

19 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Summary
Now that you have completed this unit, you should be able to

Understand what is PHP


Install the PHP software and how to use
Understand the basic syntax and data types supported in PHP
Create a Sample PHP page and execute it on the Server

Copyright IBM Corp. 2011 Unit 1 PHP Basics 20


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Self-Assessment Quiz

1. PHP is a --------------------------------------- language


a. Client side scripting
b. Server side scripting
c. Procedural
d. None of the above
2. PHP scripts can be embedded in HTML using
a. <phpscript phpscript>
b. <?phpscript phpscript>
c. <?php php>
d. <?php ?>
3. What is the output of the following code?
<?php
$num1=20;
$num2=30;
echo $num1.$num2
?>
a. 50
b. 60
c. 2030
d. error
4. The isset() method
a. Used to declare a variable
b. Used to undeclared a variable
c. Used to check the variables existence
d. Used to check if the variable is NULL
5. What is the output of the following code?
<?php
$value=-2;
if($value)
echo "true";
else
echo "false";
?>
a. true
b. false

21 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

c. error
6. Which of the following defines a Constant?
a. define(bonus_point,3);
b. define('bonus_point ',3);
c. Define(bonus_point,3);
d. All the above
7. What is the output of the following code snippet?
$msg="H";
$msg{1}="e";
$msg{2}="l";
$msg{1}="l";
$msg{4}="o";
echo $msg;
a. Hello
b. Hllo
c. Hll o
d. Error
8. All data types in PHP can be evaluated to Boolean value
a. True
b. False
9. What is the output of the following statement?
Print("Hello Peter, Welcome to the Show!");
a. Hello Peter, Welcome to the Show!
b. "Hello Peter, Welcome to the Show!"
c. Error, because print function cannot accept multiple arguments
d. Error, because function name has to be in lowercase
10. -----------------------is an unknown or unassigned or no value in PHP
a. Empty Array
b. Object with no attributes
c. False
d. Null

Copyright IBM Corp. 2011 Unit 1 PHP Basics 22


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Answers to Self-Assessment Quiz


1. b
2. d
3. c
4. c
5. a
6. b
7. c
8. a
9. a
10. d

23 PHP Copyright IBM Corp.2011

You might also like