UNIT 1 PHP and MYSQL
UNIT 1 PHP and MYSQL
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL
Unit 1
Introducing PHP: Basic development Concepts -Creating first PHP Scripts -Using Variable and Operators -
Storing Data in variable -Understanding Data types -Setting and Checking variables-Data types -Using
Constants -Manipulating Variables with Operators. Subject:PHP and MySQL
Introducing PHP
PHP(Hypertext Preprocessor) is a versatile scripting language primarily used for web development, but
it can indeed be used in multiple ways. PHP started out as a small open source project that evolved as
more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP
way back in 1995.
It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase,
Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix
side. The MySQL server, once started, executes even very complex queries with huge result sets in
record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object architectures (COM and CORBA), making n-tier development
a possibility for the first time.
PHP is forgiving: PHP language tries to be as forgiving as possible.
What is PHP?
PHP is an acronym for (PHP: Hypertext Preprocessor) is a widely-used open source general-purpose
scripting language that is especially suited for web development and can be embedded into HTML. PHP
scripts are executedon the server. PHP files have extension".php".
History of PHP:
PHP history dates back to the early days of the web, and it has gone through several significant
milestones. Here's a brief history of PHP :
1. Creation of PHP/FI (1994): PHP originated in 1994 when Rasmus Lerdorf, a programmer, created a
set of Perl scripts to track visits to his online resume. He later expanded it to handle form data and
interact with databases, naming it "Personal Home Page/Forms Interpreter" or PHP/FI. It was more of
a collection of tools than a programming language.
2. Introduction of PHP2.0(1995):PHP/FI was further developed,and in 1995,PHP2.0 was released.
This version included more advanced features, better support for web forms, and could communicate
with various databases.
3. Birth of PHP 3.0 (1998): PHP 3.0, released in 1998, marked a significant milestone. It was a
complete rewrite of the PHP codebase and introduced the parser written in C, making it more
efficient and faster.PHP3.0 also added support for various databases and improved support for
different web servers.
4. PHP4.0(2000):PHP4.0,released in 2000,was a major step forward in PHP' evolution. It included
enhanced support for object-oriented programming (OOP), better performance, and added numerous
features. PHP was now recognized as a full-fledged scripting language suitable for building dynamic
websites.
8. PHP 7.0 (2015): PHP 7.0 was a groundbreaking release in terms of performance. It introduced the
ZendEngine3, which significantly improved PHP's execution speed.The update also included scalar
type declarations, the spaceship operator, and the null coalescing operator.
9. PHP7.4(2019):PHP7.4 brought features like arrow functions, typed properties, and improved
performance.
PHP continues to evolve, with regular updates and improvements. It remains a widely used language for web
development, powering countless websites and web applications. Its open-source nature and active
community make it a versatile and robust choice for developers around the world.
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 flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, MacOSX, etc.).
PHP is compatible with almost all servers used today(Apache,IIS,etc.).
2
PHP supports a wide range of databases.
PHP is easy to learn and runs efficiently on the server side.
PHP is widely-used.
Unique Features
If you’re familiar with other server-side languages like ASP.NET or JSP, you might bewondering what makes
PHP so special, or so different from these competing alternatives.well, here are some reasons:
Performance :Scripts written in PHP execute faster than those written in other scripting languages, with
numerous independent benchmarks putting the language ahead of competing alternatives like JSP, ASP.NET,
and Perl. The PHP 5.0 engine was completely redesigned with an optimized memory manager to improve
performance, and is noticeably faster than previous versions. In addition, third-party accelerators are available
to further improve performance and response time.
Portability PHP is available for UNIX, Microsoft Windows, Mac OS, and OS/2, and PHP programs are
portable between platforms. As a result, a PHP application developed on, say, Windows will typically run on
UNIX without any significant issues. This ability to easily undertake cross-platform development is a valuable
one, especially when operating in a multiplatform corporate environment or when trying to address multiple
market segments.
Ease of Use :“Simplicity is the ultimate sophistication,” said Leonardo da Vinci, and by that measure, PHP is
an extremely sophisticated programming language. Its syntax is clear and consistent, and it comes with
exhaustive documentation for the 5000+ functions included with the core distributions. This significantly
reduces the learning curve for both novice and experienced programmers, and it’s one of the reasons that PHP is
favored as a rapid prototyping tool for Web-based applications.
Open Source PHP is an open-source project—the language is developed by a worldwide team of volunteers
who make its source code freely available on the Web, and it may be used without payment of licensing fees or
investments in expensive hardware or software.This reduces software development costs without affecting
either flexibility or reliability.The open-source nature of the code further means that any developer, anywhere,
can inspect the code tree, spot errors, and suggest possible fixes; this produces a stable, robust product wherein
bugs, once discovered, are rapidly resolved—sometimes within a few hours of discovery!
Community Support One of the nice things about a community-supported languagelike PHP is the access it
offers to the creativity and imagination of hundreds of developers across the world. Within the PHP community,
the fruits of this creativity may be found in PEAR, the PHP Extension and Application Repository
(http://pear.php.net/), and PECL, the PHP Extension Community Library (http://pecl.php.net/), which contains
hundreds of ready-made widgets and extensions that developers can use to painlessly add new functionality to
PHP. Using these widgets is often a more time- and cost-efficient alternative to rolling your own code.
Third-Party Application Support One of PHP’s strengths has historically been its support for a wide range of
different databases, including MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. PHP 5.3 supports more
3
than fifteen different database engines, and it includes a common API for database access. XML support makes
it easy to read (and write) XML documents as though they were native PHP data structures, access XML node
collections using XPath, and transform XML into other formats with XSLT style sheets.
From the preceding explanation, it should be clear that to get started building PHP applications, your
development environment must contain at least three components:
● A base operating system (OS) and server environment (usually Linux)
● A Web server (usually Apache on Linux or IIS on Windows) to intercept HTTP requests and either serve
them directly or pass them on to the PHP interpreter for execution
● A PHP interpreter to parse and execute PHP code, and return the results to the Web server
There’s also often a fourth optional but very useful component:
4
● A database engine (such as MySQL) that holds application data, accepts connections from the PHP layer, and
modifies or retrieves data from the database.
An important corollary of this approach is that the PHP code is executed on the server, and
not on the client browser. This allows Web developers to write program code that is completely independent of,
and thus impervious to, browser quirks—an important advantage over client-side scripting languages, such as
JavaScript, which often require complex logic to account for browser-specific differences. Further, because the
code is all executed on the server and only the output is sent to the client, it is impossible for users to see the
source code of your PHP program—an important security advantage over languages like JavaScript.
PHP Syntax:
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
A PHP script can be placed anywhere in the document.
A PHP script starts with
<?php and ends with ?>
Example:
<?php
echo “Hello World”;
?>
Creating first PHP script
To get a feel for PHP, first start with simple PHP scripts.
Writing and Running the Script
PHP scripts are merely plain-text files containing PHP instructions, sometimes combined with other
odds and ends—JavaScript, HTML, and so on. So, the simplest way to write a PHP script is to pop open
your favorite text editor and create a file containing some PHP code as follow
<?php
echo “Hello World”;
?>
save this file to a location under your Web server’s document root, and name it hello.php. Then, start up your
Web browser, and browse to the URL corresponding to the file location
Understanding Scripting
What happened here? Well, when you requested the script hello.php,the Apache Web server received your
request, recognized that the file was a PHP script (by means of the .php file extension), and handed it off to the
PHP parser and interpreter for further processing. This PHP interpreter then read the instructions between the
<?php ... ?> tags, executed them, and passed the results back to the Web server, which in turn sent them back to
your browser. The instructions in this instance consisted of a call to PHP’s echo statement, which is responsible
for displaying output to the user; the output to be displayed is enclosed in quotation marks.There is some useful
information to be gleaned from even this simple PHP script. It should be clear, for example, that all PHP code
must be enclosed within <?php ... ?> tags and every PHP statement must end in a semicolon. Blank lines within
the PHP tags are ignored by the parser.
5
Softwares Required For To Work With Php:
1. Browser - Internet Explorer
2. Server - Apache
3. Server side script - PHP
4. Database - MYSQL
Installation
5. Double click on downloaded file
6. Click on the Next button
7. Select drive where you want to installed
8. Click on the Next button until you will get finished button
9. Click on Finish button
7
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read
by someone who is looking at the code.
Ex:
// This is a single-line comment # This is also a single-line comment
/* This is a multiple-lines comment block that spans over multiple lines */
8
When the parser encounters one of these escape sequences, it knows to replace it with the corresponding value
before sending it to the output device.
Variable Scopes
Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a
variable is the portion of the program with in which it is visible or can be accessed.Depending on the scopes,
PHP has three variable scopes:
9
1. Local variables: The variables declared within a function are called local variables to that function and has
its scope only in that particular function. In simple words it cannot be accessed outside that function. Any
declaration of a variable outside the function with same name as that of the one within the function is a
complete different variable.
Example:
<?php
$num = 60;
function local_var()
{
$num = 50;
echo "local num = $num \n";
}
local_var();
echo "Variable num outside local_var() is $num \n";
?>
Output: local num = 50
Variable num outside local_var() is 60
2. Global variables: The variables declared outside a function are called global variables. These variables can
be accessed directly outside a function. To get access within a function we need to use the “global” keyword
before the variable to refer to the global variable.
Example:
<?php
$num = 20;
function global_var()
{
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output: Variable num inside function : 20
Variable num outside function : 20
3. Static variable: It is the characteristic of PHP to delete the variable, ones it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of function execution.
To do this we use static keyword and the variables are then called as static variables.
Example:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
10
?>
Output: 0 1 2
Destroying Variables
To destroy a variable, pass the variable to PHP’s aptly named unset() function.
Trying to access or use a variable that’s been unset(), as in the preceding script, will result in a PHP
“undefined variable” error message. This message may or may not be visible in the output page,
depending on how your PHP error reporting level is configured.
Example:
<?php
$var1=100;
echo “value of var1 is $var1”;
echo “<br>”;
unset($var1);
echo “value of var1 is $var1”;
?>
Output
value of var1 is: 100
Warning: Undefined variable $var1 in C:\xampp\htdocs\smallprogram\destroy.php on line 9
value of var1 is:
1.PHP String
• A string can be any text inside quotes. You can use single or double quotes.
• It can hold letters or any alphabets, even numbers are included.
• The strings can also be written within single quotes but it will be treated differently while printing
variables.
Ex:
<?php $x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hello world!
Hello world!
2.PHP Integer:
Integers hold only whole numbers including positive and negative numbers, i.e., numbers without
fractional part or decimal point.
An integer must have at least one digit
They can be decimal (base 10), octal (base 8) or hexadecimal (base16).
The default base is decimal (base 10).
The octal integers can be declared with leading 0 and the hexadecimal can be declared with leading 0x.
The range of integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;
12
echo $sum;
?>
Output: 704
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
Ex:
<?php
$x = 5985;
var_dump($x);
?>
Output: int(5985)
Example:
<?php
$x = 4356; //decimal number
echo $x.' is : ';
var_dump($x);
$x = -39; //a negative number
echo '<br />'.$x.' is : ';
var_dump($x);
$x = 057; //octal number (equivalent to 47 decimal)
echo '<br />'.$x.' is : ';
var_dump($x);
$x = 0x4B; //hexadecimal number (equivalent to 75//decimal)
echo '<br />'.$x.' is : ';
var_dump($x);
?>
Output
4356 is : int(4356)
-39 is : int(-39)
47 is : int(47)
75 is : int(75)
4.PHP Float(or)double
It 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;
?>
Output: 705.11
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
Ex:
<?php
13
$x = 10.365;
var_dump($x);
?>
output
float(10.365)
5.PHP 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.
If a string is empty then it is also considered as false in Boolean data type.
Example:
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE
6.PHP Arrays:
Array is a compound data-type which can store multiple values of same data type.
Example
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
Output: First Element: 10
Second Element: 20
Third Element: 30
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Ex:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output:
array(3) {
[0]=> string(5) "Volvo"
[1]=> string(3) "BMW"
[2]=> string(6) "Toyota"
}
14
7.PHP Object
Objects are defined as instances of user defined classes that can hold both values and functions.
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the class, but
each object will have different values for the properties.
If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.
Example:
<?php
class gfg {
public $message;
function __construct($message) {
$this->message = $message;
}
function msg() {
return "This is an example of " . $this->message . "!";
}
}
$newObj = new gfg("Object Data Type");
echo $newObj->msg();
?>
Output:
This is an example of Object Data Type!
8.PHP NULL
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
• Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:
Example:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
9.Resources:
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.
A common example of using the resource data type is a database call.
15
We will not talk about the resource type here, since it is an advanced topic
For example, consider a database call. This is an external resource.
Parameter: This function accepts a single parameter $var. It is the name of the variable which is needed to
be checked for the type of variable.
Here’s an example of juggling(PHP is known as a dynamically typed language. The type of a variable in PHP
changes dynamically. This feature is called "type juggling" in PHP)
<?php
$a = 3;
echo gettype($a) . "<br>";
$b = 3.2;
echo gettype($b) . "<br>";
$c = "Hello";
echo gettype($c) . "<br>";
$d = array();
echo gettype($d) . "<br>";
$f = NULL;
echo gettype($f) . "<br>";
$g = false;
echo gettype($g) . "<br>";
?>
output
integer
double
string
array
array
NULL
Boolean
16
The PHP variable handling functions are part of the PHP core. No installation is required to use these functions.
Function Description
17
is_resource() Checks whether a variable is a resource
Using Constants
Constants are name or identifier that can't be changed during the execution of the script. In php constants are
define in two ways;
1. Using define() function
2. Using const keyword
In php declare constants follow same rule variable declaration.
Constant start with letter or underscore only.
Create a PHP Constant
Create constant in php by using define() function.
Syntax: define(name, value, case-insensitive)
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 in PHP.
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 The quotient of the operands
** Exponentiation $x ** $y $x raised to the power $y
% Modulus $x % $y The remainder of the operands
Example:
<?php
19
// Define two numbers
$x = 10;
$y = 3;
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1++
20
if ($x == 50 or $y == 20)
echo "or Success \n";
if ($x == 50 || $y == 20)
echo "|| Success \n";
if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
3.Comparison Operators:
These operators are used to compare two elements and outputs the result in boolean form. Here are the
comparison operators along with their syntax and operations in PHP.
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
Returns True if both the operands are equal and are
=== Identical $x = = = $y
of the same type
Returns True if both the operands are unequal and
!= = Not Identical $x == $y
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 Equal To $x <= $y Returns True if $x is less than or equal to $y
>= Greater Than or Equal To $x >= $y Returns True if $x is greater than or equal to $y
Example:
<?php
$a = 80;
$b = 50;
$c = "80";
// Here var_dump function has been used to
// display structured information. We will learn
// about this function in complete details in further
// articles.
21
var_dump($a = = $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a < > $b) + "\n";
var_dump($a = = = $c) + "\n";
var_dump($a != = $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
5.Assignment Operators: These operators are used to assign values to different variables, with or without
mid-operations. Here are the assignment operators along with their syntax and operations, that PHP
provides for the operations.
22
Operator Name Syntax Operation
= Assign $x = $y Operand on the left obtains the value of the
operand on the 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 (quotient) $x /= $y Simple division same as $x = $x / $y
%= Divide then Assign (remainder) $x %= $y Simple division same as $x = $x % $y
Example
<?php
// Simple assign operator
$y = 75;
echo $y, "\n";
// Add then assign operator
$y = 100;
$y += 200;
echo $y, "\n";
// Subtract then assign operator
$y = 70;
$y -= 10;
echo $y, "\n";
// Multiply then assign operator
$y = 30;
$y *= 20;
echo $y, "\n";
// Divide then assign(quotient) operator
$y = 100;
$y /= 5;
echo $y, "\n";
// Divide then assign(remainder) operator
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
6.Array Operators:
These operators are used in the case of arrays. Here are the array operators along with their syntax and
operations, that PHP provides for the array operation.
23
Operator Name Syntax Operation
+ Union $x + $y Union of both i.e., $x and $y
7.Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used to increment or
decrement values.
Operator Name Syntax Operation
++ Pre-Increment ++$x First increments $x by one, then return $x
-- Pre-Decrement --$x First decrements $x by one, then return $x
++ Post-Increment $x++ First returns $x, then increment it by one
-- Post-Decrement $x-- First returns $x, then decrement it by one
24
Example:
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
8.String Operators:
This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We
can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the
argument on the left side.
Operator Name Syntax Operation
. Concatenation $x.$y Concatenated $x and $y
Concatenation First concatenates then assigns, same as $x =
.= $x.=$y
and assignment $x.$y
Example: This example describes the string operator in PHP.
<?php
$x = "Vedant";
$y = "BCA";
$z = "College!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
VedantBCACollege!!!
VedantBCACollege!!!
25
Difference Between = = and = = = operators
SL
= = Equality = = = Identity
No
Checks if values are equal, ignoring data
1 Checks if both values and data types are identical.
types.
Performs type juggling (automatic
2 No type juggling; data types must match exactly.
conversion) to compare values.
Returns true if values are equal after type Returns true only if both value and data type are
3
juggling. identical.
Example
<?php
Example
$a = 5;
<?php
$b = '5';
$a = 5;
// Strict comparison (===)
$b = '5';
var_dump($a === $b); // bool(false)
4 // Loose comparison (==)
?>
var_dump($a == $b); // bool(true)
?>
Output
Output
bool(false)
bool(true)
Types Of Errors:
Mistake or fault occurs in a program is called error. There are basically 4 types of errors in PHP:
1. Notice
2. Warning
3. Fatal Error
4. Parse Error
26
1. NOTICE
Notice that an error is the same as a warning error i.e. in the notice error does not stop execution of the script.
Notice that the error occurs when you try to access the undefined variable, and then produce a notice
error.
Example
<?php
$a="Uday ";
echo "Notice Error !!";
echo $b;
?>
Output: In the above code we defined a variable which named $a. But we call another variable i.e. $b, which is
not defined. So there will be a notice error produced but execution of the script does not stop, you will see a
message Notice Error !!. Like in the following image:
2. WARNING
Warning errors will not stop execution of the script. The main reason for warning errors are to include a
missing file or using the incorrect number of parameters in a function.
Example
<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
Output: In the above code we include a welcome.php file, however the welcome.php file does not exist in the
directory. So there will be a warning error produced but that does not stop the execution of the script i.e. you
will see a message Warning Error !!.
27
3. FATAL ERROR
Fatal errors are caused when PHP understands what you've written; however what you're asking it to do can't be
done. Fatal errors stop the execution of the script. If you are trying to access
the undefined functions, then the output is a fatal error.
Example
<?php
function fun1(){
echo "Uday Kumar";
}
fun2();
echo "Fatal Error !!";
?>
Output: In the above code we defined a function fun1 but we call another function fun2 i.e. func2 is not
defined. So a fatal error will be produced that stops the execution of the script. Like as in the following image.
4. PARSE ERROR
The parse error occurs if there is a syntax mistake in the script; the output is Parse errors. A parse error
stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The
common reasons for parse errors are as follows:
Common reason of syntax errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example
<?php
echo "C#";
echo "PHP"
echo "C";
?>
Output: In the above code we missed the semicolon in the second line. When that happens there will be a parse
or syntax error which stops execution of the script, as in the following image:
28
Functions In Php:
1. echo statement
In PHP ‘echo’ statement is a language construct and not a function, so it can be used without parenthesis.
But we are allowed to use parenthesis with echo statement when we are using more than one argument with
it.
The end of echo statement is identified by the semi-colon (‘;’). We can use ‘echo’ to output strings or
variables.
Displaying Strings: The keyword echo followed by the string to be displayed within quotes.
<?php
?>
Output: Hello,This is a display string example!
Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement
instead of single string argument, separating them by comma (‘,’) operator. For example, if we have two strings
say “Hello” and “World” then we can pass them as (“Hello”,”World”).
<?php
echo "Multiple ","argument ","string!";
?>
Output: Multiple argument string!
29
The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new
line and is also known as line-break.
2. print statement
The PHP print statement is similar to the echo statement and can be used alternative to echo at many times.
It is also language construct and so we may not use parenthesis: print or print ().
The main difference between the print and echo statement is that print statement can have only one argument
at a time and thus can print a single string. Also, print statement always returns a
value 1.
Like echo, print statement can also be used to print strings and variables.
Displaying String of Text: We can display strings with print statement in the same way we did with echo
statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print
statement. Below example shows how to display strings with the help of PHP print statement:-
<?php
print "Hello, world!";
?>
Output: Hello, world!
Displaying Variables: Displaying variables with print statement is also same as that of echo statement.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>
Output: Hello, World!
10+20=30
3. printf() :Using this function, we can print variables with the help of format specifies.
Example:
<?php
$x=100;
$y=”Vedant”;
printf(“%d”,$x);
printf(“%s”,$y);
?>
Output: 100 Vedant
30
Difference between Echo and Print in PHP
1 In Echo, we can pass multiple arguments In Print, we cannot pass multiple arguments.
separated by commas.
2 In Echo, we can exhibit the outputs of one or Through the Print statement, we can only show
more strings separated by commas. the strings.
3 Echo can be used with or without parentheses Print can also be used with or without
parentheses.
4 It never returns any value. It always returns the integer value that is 1.
5 This statement is fast as compared to the print It is slow as compared to the echo statement.
statement.
5 Marks Questions
1.Explain Features of PHP or Advantages of PHP.
2.Explain about datatypes in PHP with an example.
3.Explain about the scope of variable.
4.Explain operators in PHP with example
5.How PHP work?Explain.
6.Write a PHP script that demonstrates the use of comparison and logical operators.include coments to
explain each operation.
7.discuss relational and logical operators in PHP
31