Professional Documents
Culture Documents
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
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 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/
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
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
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
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
is an open source software where we are free to add or modify the features of the s oftware
?>
Example1.1: Display a Message in the Web Browser
<?php
echo "Welcome to PHP Programming!!!!"
?>
Output on the Web Browser
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 - //
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;
?>
<?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
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;
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
<?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)) {
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>";
?>
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
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
$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 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';
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;
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
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;
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
$empobj->name="Sam";
echo "Employee id:".$empobj->id;
echo <br>;
echo "Employee Name:".$empobj->name;
?>
Summary
Now that you have completed this unit, you should be able to
Self-Assessment Quiz
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