Unit-1 Introduction To PHP: Bcacst1.9: PHP and Mysql
Unit-1 Introduction To PHP: Bcacst1.9: PHP and Mysql
Unit-1 Introduction To PHP: Bcacst1.9: PHP and Mysql
Unit-1
Introduction to PHP
History, Advantages of PHP, HTML relationship, Interpreting vs. Compiling, Basic syntax of
PHP, Writing and Running PHP scripts, variable types - Local and Global, Superglobal variable
and their scope, Comments, Types of Data, Automatic type conversion, Forcing a type with
type casting, Non-decimal number systems, Pre-set variables, Constants, Pre-set constants,
Operators, unary operators, arithmetic operators, logical operators, conditional operators,
conversion operators, Comparison operators, The Ternary Operator, The scope resolution
operator. Control statements – sequence, Conditional statements, loops, jump statements.
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code are executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension “.php”
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even lash
movies. You can also output any text, such as XHTML and XML
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
1
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
PHP originally stood for Personal Home Page, but it now stands for the recursive acronym
PHP: Hypertext Preprocessor. PHP: Hypertext Preprocessor (or simply PHP) is a server-side
scripting language designed for making dynamic and interactive Web pages. The founder of PHP
is Rasmus Lerdorf in 1994.
1. 1 History
• PHP development began in 1994 when Rasmus Lerdorf wrote several Common Gateway
Interface (CGI) programs in C, which he used to maintain his personal homepage. He
extended the work with web forms and to communicate with databases. This
implementation is called "Personal Home Page/Forms Interpreter" or (PHP/FI 1) version
1.0 in June 8, 1995.
• A development team began to form and, after months of work and beta testing, officially
released PHP/FI 2 in November 1997.
• Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP 3,
changing the language's name to the recursive acronym PHP: Hypertext Preprocessor.
Afterwards, public testing of PHP 3 began, and the official launch came in June 1998.
• On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released. As of August
2008 this branch reached version 4.4.9. PHP 4 is no longer under development nor will any
security updates be released.
• On July 14, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5
included new features such as object-oriented programming, the PHP Data Objects (PDO)
extension and numerous performance enhancements.
• In 2005, a project headed by Andrei Zmievski was initiated to bring native Unicode support
throughout PHP, by embedding the International Components for Unicode (ICU) library,
and representing text strings as UTF-16 internally. Since this would cause major changes
both to the internals of the language and to user code, it was planned to release this as PHP
6 of the language, along with other major features then in development.
• During 2014 and 2015, a new major PHP version was developed, which was numbered
PHP 7. The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next
generation (phpng). PHP 7 included new language features such as, it introduces return
type declarations for functions, which complement the existing parameter type
declarations, and support for the scalar types (integer, float, string, and boolean) in
parameter and return type declarations.
1. 2 Advantages of PHP
2
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
• PHP is cheap, secure, fast and reliable for developing web applications
• MySQL is used with PHP as back-end tool. MySQL is the popular online database and can
be interfaced very well with PHP
• PHP can add, delete, modify data in your database
• PHP language has its roots in C and C++. PHP syntax is most similar to C and C++ language
syntax. So, programmers find it easy to learn and manipulate
• PHP can run on both UNIX and Windows servers
• PHP can create, open, read, write, delete, and close files on the server
• PHP can be used to send and receive cookies
• PHP can be used with a large number of relational database management systems, runs on all
web servers and is available for many different operating systems
• PHP5 a fully object oriented language and its platform independence and speed on Linux
server helps to build large and complex web applications
• PHP can be used to control user-access
• PHP can used to encrypt data
1.3 HTML Relationship with PHP
HTML is a language used to describe to a browser how to display text and other objects in a
browser window. It is not a programming language. HTML works on a client computer. PHP is a
scripting language, and can be used to create web pages written in HTML. PHP runs on the
server (the system from which the page comes), and is a full-fledged programming language.
1.4 Interpreting vs. Compiling
A compiler translates the source code of the program into another language format that can be
directly executed by a lower-level machine. This can be an abstract machine. The translation
from source code into lower-level code depends on the abstract syntax and on the operational
semantics of the programming language. An interpreter executes the source code directly.
The interpreter executes the program directly, translating each statement into a sequence of one
or more subroutines, and then into another language.
1.5 Basic syntax of PHP
There are four ways in which we can embedding PHP within HTML. Few methods are already
set by default and Short-open or ASP-style tags we need to change the configuration of php.ini
file. A PHP script can be placed anywhere in the document.
i. Canonical PHP Tags
ii. SGML or Short HTML Tags
iii. HTML Script Tags
iv. ASP Style Tags
3
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
i. Canonical PHP Tags: The script starts with <?php and ends with ?> . These tags are called
‘Canonical PHP tags’. Every PHP command ends with a semi-colon (;).
<?php
echo "Welcome to PHP.!";
?>
ii. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The
script starts with <? and ends with ?>. This will only work by setting the short_open_tag setting
in php.ini file to ‘on’.
<?
echo "Hello, world!";
?>
iii. HTML Script Tags: HTML Script Tags: These are implemented using script tags. This
syntax is removed in PHP 7.0.0. so its no more used.
<script language="php">
echo "hello world!";
</script>
iv. ASP Style Tags: To use this we need to set the configuration of php.ini file. These are used by
Active Server Pages to describe code blocks. These starts with <% and ends with %>.
Example:
<%
echo "hello world";
%>
4
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
• Any variable names in PHP names must start with a letter or underscore and no numbers.
• PHP is a loosely typed language and we do not require to declare the data types of variables,
rather PHP assumes it automatically by analyzing the values.
5
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
}
global_var(); echo "Variable num outside function : $num";
echo “<br>”;
?>
Output: Variable num inside function : 20
Variable num outside function : 20
iii. Static variable: To store the variables even after the completion of function execution, a
Static variable is able to retain its value between different function calls. The static variable is
only initialized once, if it is not initialized, then it is automatically initialized to 0. Example:
<?php
function static_var()
{ Output:
static $num ; 1
$sum = 7; 8
2
$sum++;
8
$num++;
echo $num;
echo “<br>”;
echo $sum;
echo “<br>”;
}
static_var();
static_var();
?>
1.8 Superglobal variables or Pre-set or Pre-defined variable
The Superglobal variables are specially-defined array variables in PHP that make it easy to store
and get information from one page to another in an application. These variables can be accessed
from any function, class or any file without declaring any global variable. The list of superglobal
variables available in PHP are
i. $GLOBALS
ii. $_SERVER
iii. $_REQUEST
iv. $_GET
v. $_POST
vi. $_SESSION
vii. $_COOKIE
6
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
viii. $_FILES
ix. $_ENV
i. $GLOBALS: It is a superglobal variable which is used to access global variables from
anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[index]. The
index holds the name of the variable.
<?php
$x = 30;
$y = 20;
function multiplication()
{
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
ii. $_SERVER: It is a PHP super global variable that stores the information about headers, paths
and script locations.
<?php /serverglobal.php
localhost
echo $_SERVER['PHP_SELF']; echo "<br>"; localhost
echo $_SERVER['SERVER_NAME']; Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/67.0.3396.87 Safari/537.36
echo "<br>"; /serverglobal.php
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT']; echo "<br>";
echo $_SERVER['SCRIPT_NAME']; echo "<br>"
?>
iii. $_REQUEST: It is a superglobal variable which is used to collect the data after submitting a
HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same
task and are widely used.
iv. $_GET: $_GET is a super global variable used to collect data from the HTML form after
submitting it. When form uses method get to transfer data, the data is visible in the query string,
therefore the values are not hidden. $_GET super global array variable stores the values that
come in the URL.
7
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
v. $_POST: It is a super global variable used to collect data from the HTML form after
submitting it. When form uses method post to transfer data, the data is not visible in the query
string, because of which security levels are maintained in this method.
vi. $_COOKIE: It is often used to identify a user. A cookie is a small file that the server embeds
on the user's computer. Each time the same computer requests a page with a browser, it will send
the cookie too. With PHP, you can both create and retrieve cookie values.
vii. $_SESSION: A session is a way to store information (username, favorite color) to be used
across multiple pages. By default, session variables last until the user closes the browser.
8
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
ii. Double: Can hold numbers containing fractional or decimal part including positive and
negative numbers. By default, the variables add a minimum number of decimal places.
Example:
<?php
$val1 = 50.85; $val2 = 654.26;
$sum = $val1 + $val2; echo $sum;
?>
iii. String: Hold letters or any alphabets, even numbers are included. These are written within
double quotes during declaration. The strings can also be written within single quotes but it will
be treated differently while printing variables. To clarify this look at the example below.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name';
?>
The name of the Geek is Krishna
The name of the geek is $name
iv. NULL: These are special types of variables that can hold only one value i.e., NULL. We
follow the convention of writing it in capital form, but its case sensitive.
v. Boolean: Hold only two values, either TRUE or FALSE. Successful events will return true
and unsuccessful events return false. NULL type values are also treated as false in Boolean.
Apart from NULL, 0 is also consider as false in boolean. If a string is empty then it is also
considered as false in boolean data type.
vi. Arrays: Array is a compound data-type which can store multiple values of same data type.
Below is an example of array of integers.
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
vii. Objects: Objects are defined as instances of user defined classes that can hold both values
and functions.
9
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
viii. Resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources. For example, consider a database
call. This is an external resource.
1.10 Constants
Constants are identifiers that can be assigned any fixed values. They remain constant throughout
the program and cannot be altered during execution.
• By default, a constant is always case-sensitive, unless mentioned
• A constant name must never start with a number
• It always starts with a letter or underscores, followed by letter, numbers or underscore.
• It should not contain any special characters except underscore
• By default, constants are automatically global, and can be used throughout the script,
accessible inside and outside of any function.
Creating a PHP Constant : The define() function in PHP is used to create a constant as shown
below:
Syntax: define(name, value, case_insensitive)
Where, name: The name of the constant.
value: The value to be stored in the constant.
case_insensitive: Defines whether a constant is case insensitive. By default this value is False,
i.e., case sensitive.
Example:
<?php
10
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
constant() function: Instead of using the echo statement, there is an another way to print
constants using the constant() function.
Syntax: constant(name)
Example:
<?php
define("VVFGC", "Vidyavahini First Grade College");
echo VVFGC, "\n";
echo constant("VVFGC"); // same as previous
?>
1.10 Operators
Operators are nothing but symbols needed to perform operations on operands. Thus, PHP
provides us with many operators to perform operations on various operands or variables or
values. Given below are the various groups of operators:
• Arithmetic Operators
• Logical Operators
• Relational Operators
• Bitwise Operators
• Assignment Operators
• Increment/Decrement Operators
• Conditional or Ternary Operators
• Array Operators
• String Operators
• Spaceship Operators
1.10.1 Arithmetic Operators: The arithmetic operators are used to perform simple mathematical
operations like addition, subtraction, multiplication etc. Below is the list of arithmetic operators
along with their syntax and operations that PHP provides us:
Operator Name Syntax Operation
+ Addition $x + $y Sum the operands
- Subtraction $x – $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y Quotient of the operands
11
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
1.10.2 Logical Operators: These are basically used to operate with conditional statements and
expressions. Also, a condition can either be met or cannot be met so the result of a conditional
statement can either be true or false.
Operator Name Syntax Operation
and Logical AND $x and $y True if both the operands are true else false
or Logical OR $x or $y True if either of the operand is true else false
xor Logical XOR $x xor $y True if either of the operand is true and false
if both are true or false
&& Logical AND $x && $y True if both the operands are true else false
|| Logical OR $x || $y True if either of the operand is true else false
! Logical NOT !$x True if $x is false
1.10.3 Relational Operators: These operators are used to compare two elements and outputs the
result in Boolean form.
Operator Name Syntax Operation
== Equal To $x == $y Returns True if both the operands are equal
!= Not Equal To $x != $y Returns True if both the operands are not equal
<> Not Equal To $x != $y Returns True if both the operands are unequal
=== Identical $x === $y Returns True if both the operands are equal
and are of the same type
!== Not Identical $x == $y Returns True if both the operands are unequal
and are of different types
< Less Than $x < $y Returns True if $x is less than $y
> Greater Than $x > $y Returns True if $x is greater than $y
<= Less Than or $x <= $y Returns True if $x is less than or equal to $y
Equal To
>= Greater Than $x >= $y Returns True if $x is greater than or equal to
or Equal To $y
1.10.4 Relational Operators: The Bitwise operators is used to perform bit-level operations on
the operands. The operators are first converted to bit-level and then calculation is performed on
the operands.
Operator Name Syntax Operation
& Bitwise AND $x& $y The result of AND is 1 only if both bits are 1.
| (Bitwise OR) $x | $y The result of OR is 1 any of the two bits is 1
^ Bitwise XOR The result of XOR is 1 if the two bits are different
~ Bitwise NOT ~$x Bitwise NOT operator takes one number and inverts all
bits of it.
<< Bitwise Left Shift $x << $y This will shift the bits of $x towards the left. $y decides
the number of time the bits will be shifted
12
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
>> Bitwise Right Shift $x >> $y This will shift the bits of $x towards the right. $y
decides the number of time the bits will be shifted.
1.10.5 Assignment Operators: These operators are used to assign values to different variable,
with or without mid-operations.
Operator Name Syntax Operation
= Assign $x = $y Operand on the left obtains the value of
the operand on right
+= Add then Assign $x += $y Simple Addition same as $x = $x + $y
-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y
*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
/= Divide then Assign $x /= $y Simple division same as $x = $x / $y
(quotient)
%= Divide then Assign $x %= $y Simple division same as $x = $x % $y
(remainder)
1.10.6 Increment/Decrement Operators: These are called the unary operators as it work on
single operands. These are used to increment or decrement values.
Operator Name Syntax Operation
++ Pre-Increment $x++ First returns $x, then increment it by one
-- Pre-Decrement $x– First returns $x, then decrement it by one
++ Post-Increment ++$x First increments $x by one, then return $x
-- Post-Decrement –$x First decrements $x by one, then return $x
1.10.7 Conditional or Ternary Operators: These operators are used to compare two values and
take either of the result simultaneously, depending on whether the outcome is TRUE or FALSE.
These are also used as shorthand notation for if…else statement
Syntax:
$var = (condition)? value1 : value2;
Here, condition will either evaluate to true or false. If the condition evaluates to True, then
value1 will be assigned to the variable $var otherwise value2 will be assigned to it.
13
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
1.10.10 Spaceship Operators: PHP 7 has introduced a new kind of operator called spaceship
operator (). These operators are used to compare values but instead of returning boolean result, it
returns integer values. If both the operands are equal, it returns 0. If the right operand is greater,
it returns -1. If the left operand is greater, it returns 1.
Operator Syntax Operation
$x < $y $x <=> $y Identical to -1 (right is greater)
$x > $y $x <=> $y Identical to 1 (left is greater)
$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)
$x == $y $x <=> $y Identical to 0 (both are equal)
$x != $y $x <=> $y Not Identical to 0
if Statement: This statement allows us to set a condition. On being TRUE, the following block of
code enclosed within the if clause will be executed.
Syntax :
if (condition)
{
// if TRUE then execute this code
}
if…else Statement: If a condition is TRUE then if block gets executed, otherwise else block gets
executed.
Syntax:
if (condition)
14
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
if…elseif…else Statement: This allows us to use multiple if…else statments. We use this when
there are multiple conditions of TRUE cases.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
switch Statement: The “switch” performs in various cases i.e., it has various cases to which it
matches the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same case
is executed.
Syntax:
switch(n)
{
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
15
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default: code to be executed if n != any case;
}
Flowcharts:
16
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
while loop: The while loop is also an entry control loop like for loops i.e., it first checks the
condition at the start of the loop and if its true then it enters the loop and executes the block of
statements, and goes on executing it as long as the condition holds true.
17
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
Syntax:
while (if the condition is true)
{
// code is executed
}
do-while loop: This is an exit control loop which means that it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at least once on
using the do…while loop. After executing once, the program is executed as long as the condition
holds true.
Syntax:
do
{
//code is executed
} while (if condition is true);
foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element
is assigned and the next counter is shifted to the next element.
Syntax:
foreach (array_element as value)
{
//code to be executed
}
Example:
<?php
$arr = array (5, 8, 30, 1, 3, 6);
foreach ($arr as $val)
{
for ($i=1;$i<&val;$i++)
{
echo "*";
}
echo “<br>”
}
echo “Bye!!”; for -loop
18
Unit-1 Introduction to PHP BCACsT1.9: PHP and MYSQL
?>
do-while while
19