Open Source Programming Course Overview
Open Source Programming Course Overview
COURSE OBJECTIVES
To understand the basics of open source software
To create dynamic web applications using PHP, MySQL
To create web applications based on PHP and AJAX
UNIT – I OPEN SOURCE & FREE SOFTWARE LICENSING:
Open Source Licensing: Basic Principles of Copyright Law – Contract and Copyright – Open
Source Software Licensing – Issues with Copyrights and Patents – Open Source Definition –
MIT License – BSD License – Apache License – GNU General Public License –
Free and Open Source Software Development: Models of Open Source and Free Software
Development – Choosing an Open Source or Free Software License
UNIT – II BASICS OF PHP PROGRAMMING: Basics of PHP Programming: Introduction –
syntax and variables – controls and functions – passing information between pages – strings –
numbers – arrays, array functions and advanced array functions
UNIT – III ADVANCED FEATURES AND TECHNIQUES: Advanced PHP Programming:
Object-Oriented Programming with PHP – String and Regular Expression Functions –
Filesystem and System Functions – Sessions, Cookies and HTTP – Exceptions and Error
Handling
UNIT – IV PHP AND MySQL: Why PHP and MySQL? – Server-Side Web Scripting – SQL
Tutorial – MySQL Database Administration – PHP/MySQL Functions – Displaying Queries in
Tables – Building Forms from Queries
UNIT – V PHP & AJAX AND GITHUB HOSTING SERVICE: PHP and AJAX: JavaScript
and AJAX Client – JavaScript and DOM – XML Http Request Object – AJAX form validation –
Uploading a file using AJAX – Displaying a table in AJAX – Building Pagination using PHP
and AJAX Hosting Open Source Projects using Github: Introduction – Viewing Github Graphs-
Editing Files – Collaborating on Pull Requests – Creating a Repository – Configuring a
Repository
UNIT – VI CURRENT CONTOURS (For continuous internal assessment only): Contemporary
Developments Related to the Course during the Semester Concerned.
REFERENCES:
1. Andrew M. St. Laurent, ‘Understanding Open Source & Free Software Licensing’, O’Reilly
Media, 2004.
2. Tim Converse and Joyce Park, ‘PHP 5 and MySQL Bible’, Wiley Publishing, 2004.
3. [Link], [Link],A .[Link] Anand Babu, Web Programming with PHP and Mysql,
Himalaya Publications. Mumbai, 2012.(ISBN :978- 93 - 5051 - 581• 5)
1
4. Bogdan Brinzarea-Lamandi, Cristian Darie and Audra Hendrix, ‘AJAX and PHP’, Packt
Publishing, 2009.
5. Peter Bell and Brent Beer, ‘Introducing Github: a Non-Technical Guide’, O’Reilly Media,
2014
6. Gordon Haff, ‘How Open Source Ate Software’, Apress, 2018.
7. Rao M. N., ‘Fundamentals of Open Source Software’, PHI Learning Pvt Ltd, 2014.
8. Robin Nixon, ‘Learning PHP, MySQL & JavaScript with jQuery, CSS & HTML5’, O’Reilly
Media, 2015.
9. Steven Holzner, ‘PHP: The Complete Reference’, McGraw Hill Education, 2017.
10. [Link]
11. [Link]
12. [Link]
13. [Link]
COURSE OUTCOMES:
On the successful completion of the course, student will be able to:
Understand the significance of open-source principles and practices
Understand the fundamentals of PHP
Develop object oriented based applications using PHP
Develop web applications using PHP, MySQL and AJAX
Host open-source projects using Github
2
Open Source Programming
Preface
Welcome to this comprehensive learning material designed to provide you with a well-rounded
understanding of essential concepts in open source programming for web development. The
learning material is comprised of five lessons. The lessons are constructed to provide you the
basics of open source software, foundational knowledge and practical skills required to create
dynamic web applications using PHP, MySQL and AJAX
Lesson 1: Open source and free software licensing
In the first lesson, we delve into the basic principles of copyright law and open-source licenses.
Gain insights into the legal aspects of software development, understand the significance of
intellectual property, and explore different open-source licenses that govern the use and
distribution of software. Also, gain a knowledge about the need for free open source software
development models and the factors useful in selecting a particular type of license for your
software
Lesson 2: Basics of PHP Programming
Moving on to the second lesson, it introduces you to the basics of an open source, server-side
scripting language, Hypertext Programming (PHP). Explore the basics programming
fundamentals in PHP including, variables, datatypes, operators, functions, control structures and
arrays and array functions. Gain skills in writing PHP scripts to implement different application
requirement.
Lesson 3: Advanced Features and Techniques
With a solid understanding of basics of PHP, the third lesson takes you deeper into the world of
Object-Oriented Programming (OOP). Uncover the principles of encapsulation, inheritance, and
polymorphism, and discover how OOP enhances code organization, reusability, and
maintainability. Also, explore the regular expression functions for finding patterns in strings.
Understand the power of cookie and session in the maintenance of state variables. With this
lesson, you will be familiarized with different programming aspects that are required for
dynamic web application development
Lesson 4: PHP and MySQL
3
Understanding databases is an essential stuff for dynamic web development. In the fourth
lesson, explore the core architecture of MySQL, a robust relational database management
system. Learn how to design and interact with databases, execute SQL queries, and integrate
them seamlessly into your web applications. The journey takes you through two different
approaches, namely procedure oriented and object oriented PHP/MySQL functions for database
connectivity.
Lesson 5: PHP & AJAX and GitHub Hosting Service
The last lesson introduces you to the dynamic and interactive world of AJAX. Understand how
asynchronous requests transform user experiences, enabling real-time updates without the need
for page reloads. Dive into the integration of AJAX with your PHP-powered backend to create
seamless and responsive web applications. Also, the lesson takes you to a tour on GitHub, a
collaborative platform for version control and project management, enabling developers to
efficiently collaborate, track changes, and host code repositories.
By the end of these five lessons, you will not only have a comprehensive understanding of key
web development concepts but also the practical skills required to build dynamic web
applications. The journey includes exercises consisting of objective type questions, fill-in the
blanks, true/false question, simple but questions of reasoning as well as interesting dialogues
which capture the key points related to the concept under study. Yon can practice the intext
questions at the end of every lesson. In addition, you can enjoy with critical reasoning based
questions for your assignments along with Higher Order Thinking (HOT) questions for your
projects.
Let's begin our pleasant journey on Open Source Programming.
4
UNIT -I OPEN SOURCE & FREE SOFTWARE LICENSING
Objective
This unit aims to provide a comprehensive understanding of basic principles of copyright law,
open source software licensing, different licenses including MIT license, developed at
Massachusetts Institute of Technology, Berkeley Software Distribution (BSD) License, Apache
License, and GNU General Public License. Further, it provides insights into free and open source
software development models.
Learning outcomes
1.0 Introduction
Copyright laws and software licensing work together to protect the rights of creators and
developers. They make sure that those who create original works, like software, get the credit
and control they deserve. These laws and licenses encourage innovation by giving creators
exclusive rights to their creations. This means that developers are more likely to spend time and
resources on making new and better software, knowing they can protect their work and
potentially make money from it. Investors feel secure supporting software development because
copyright laws provide a sense of security. This legal protection reduces the risk of others using
or copying the software without permission, which could harm the financial investment.
Creators receive fair compensation through licensing agreements, where developers set terms for
how their software can be used, shared, and monetized. This ensures that creators are rewarded
5
for their hard work and investment. Quality control is maintained through licensing agreements,
which dictate how the software can be used and distributed. This helps developers protect the
reputation and standards of their software, ensuring a high-quality product.
Consumers are protected as well, as copyright laws and licensing establish clear terms of use and
warranty conditions. This means users can trust that the software they buy or use meets certain
standards and is not associated with legal risks.
Licensing frameworks also promote collaboration between developers and businesses. For
example, open source licenses allow developers to share their work under certain conditions.
This collaboration can lead to the creation of stronger and more feature-rich software. Copyright
laws act as a deterrent against unauthorized use, reproduction, or distribution of software. Legal
consequences for infringement serve as a warning, reducing the chances of piracy and
unauthorized exploitation.
Global standardization is facilitated by copyright laws and international treaties, which are
crucial in the software industry where products are distributed worldwide. Standardized legal
frameworks support international trade and collaboration.
Lastly, copyright laws are adaptable and evolve to address challenges posed by new
technologies. They provide guidelines for emerging issues like Digital Rights Management
(DRM), ensuring that legal protections stay relevant in a rapidly changing technological
landscape.
6
Distribution: Distribution right gives legal right to a copy right owner in distributing the
copies of the work. The right includes different kinds of distribution such as selling, renting,
or lending copies to the public.
Public display – Public display right grants permission to the creator to display his work in
public
Public performance - Public display right grants permission to the creator to display his work
in public
Creation of derivative work – This right controls the permission related to creating
derivations from the original work of a creator. It includes various rights like translation,
modification, adaptation, etc
Public digital performance right – This right grants permission to the creator to perform his
work through digital means like streaming services.
Public communication to the public – This right refers right given to a copyright owner to
broadcast his work to the public
Originality – to be eligible for copyright protection, the work of the owner should be
original. It should not copy of someone else’s work
Fixed/Tangible form – the work should be in tangible form, like written in pages or recorded
audio or video
Exclusive rights – Through this principle, the owner of a creative work would be given
different rights like reproduction, distribution, public display, etc.
Limited duration – the copyright production lasts only for a specified duration and afterwards
it can be freely used by public
Scope of protection – this principle defines the what kinds of creative works can fall under
the scope of copyright laws. Basically, the scope includes a wide range of creative works
such as books, music, films, paintings, sculptures, photographs, software, and other forms of
creative expression
7
Fair use - Fair use is an exception to copyright protection that allows limited use of
copyrighted material without permission
Public domain – After the expiry, a copyrighted work will enter public domain for free use
by the public
Registration - While copyright protection is automatic upon the creation of a work, the
owner of the work may optionally register with copyright office also
Digital rights – copyright law must address issues related to distribution, reproduction, and
dissemination of works through digital means also
8
Exercise – 2 - Test Your Understanding
1. A contract in the context of software development is a legally binding ____________
that outlines the terms and conditions for the use of software
2. Why do software developers use licenses?
Exercise – 1
1. The primary purpose of copyright law is to -------------- the rights of creators.
2. How does copyright protect the rights of creators?
9
and compiler are publicly accessible. Any user can use, modify, and distribute according to his
needs. Open source license is a legal agreement between the author of an open source software
and a user. There are two types of open source license as shown in Fig. 1.1
The MIT license was developed at Massachusetts Institute of Technology. It is also called as
Expat license. It is a permissive open source license. Under the MIT License, a user can
essentially do anything with the software if the user includes the original copyright and license
notice in the copy of the software. MIT license is very simple and most straightforward. The
MIT License can be used for software written in any programming language and for any
platform. MIT license provides high degree of freedom to the users
Apache license
Apache license is a permissive open source license. With Apache license, a user is allowed to do
any changes in the software, provided the user must include the original copyright, license notice
and changes done by the user. Apache license emphasizes on collaborative project development
and encourages contributions from a wide range of diverse developers. The unique feature of
Apache license is that it provides a specific clause related to patent of the original contributor.
10
That is, the license offers provision to clearly state the use of patented technologies within the
software, reducing the risk of patent disputes
11
Exercise – 3
1. What is a key characteristic of permissive open source licenses?
a. They require derivative works to be open source.
b. They impose minimal restrictions on how the software can be used and distributed.
c. They mandate strict control over commercial use.
d. They permit unlimited modifications without any restrictions.
2. Which open source license is known for its simplicity and permissiveness?
a. MIT License
b. Apache License
c. BSD License
d. Binary Code License (BCD)
3. The Apache License is often chosen for projects that require:
b. Compatibility with the GPL
4. Which license is associated with the University of California, Berkeley, and comes in
different variants like the 2-clause, 3-clause, and 4-clause?
5. What is the primary characteristic of the Binary Code License (BCD)?
The GPL was written by Richard Stallman in 1989, for use with programs released as part of the
GNU (stands for Gnu’s Not Unix & Gnu is pronounced as ‘noo’ with ‘g’ silent) project, a mass
collaborative initiative for the development of free software
12
Features of GNU’s GPL
GUN’s GPL ensures that the software released under it remains free and open source
It allows users to modify, and redistribute the software covered by the license under the same
terms and conditions as that of the original GPL
The GPL includes a disclaimer stating that the software is provided without any warranty.
The GPL prohibits any kind of discrimination against individuals or groups in the use of the
software
The GPL is designed to be applicable worldwide
Variants of GPL
Following is a brief overview about the three variants of GNU’s GPL
GUN’s GPL – version -1 – This license was released in 1989. This license specifies that the
software released under GNU’S GPL- version – 1 is free to use, modify, and distribute
GUN’s GPL – version -2 – This license was released in 1991. This license updates the version -
1 two distinct features.
(i) It states that GPL is a kind of copyleft license
(ii) The version-2 ensures that the source code of the software should remain open
GUN’s GPL – version -3 – This license was published in 2007. It includes provisions related to
Digital Rights Management, software patents, and compatibility with other open-source licenses
GNU LGPL — This license refers to the “Lesser GPL” which allows software being applied in a
proprietary project under certain circumstances and to some parts of the project’s code. The
LGPL is usually considered as a compromise between the strong copyleft licenses like GPL and
permissive licenses like the BSD or MIT.
13
Exercise – 4
2. Copyleft licenses, such as the GPL, aim to ensure that the ____________ nature of the
software is preserved, encouraging the ongoing availability and improvement of the
source code.
3. What is the primary difference between GPL version-2 and GPL version-3?
Narrator: Now, let's join a dialogue, between Vicky and Nandhu, two developers
exploring the Free and Open Source Software Development Models.
Vicky: Nandhu, what's the buzz about Free and Open Source Software Development?
Nandhu: Open source allows developers to collaborate, share code, and build amazing
things together.
Vicky: That sounds interesting. How does it work, and what models are commonly
used?
Nandhu: Great question! Let's find out.
1.3 Open source software development model
The model proposed by Department of Defense (DoD), United States is given in Fig. 1.2
(Mandal, S., Kandar, S., & Ray, P. (2011). Open Incremental Model: An Open Source Software
Development Life Cycle Model 'OSDLC'. International Journal of Computer Applications, 21.
[Link] The objective behind Open source software development to
obtain the practical benefits of transparent, collaborative development. It is based on the
principle that open collaboration leads to high-quality, secure, and reliable software. With the
collaborative effort, OSS aims to produce software that is technically superior and can compete
with proprietary alternatives. In addition, since OSS is based on the fact that making source code
available, it can lead to reduced development costs, faster innovation, and greater market
opportunities.
14
Developer
Bug report
Trusted Developer
Trusted Repository
Distributor
Source code
User
The typical tasks of open source software development model include the following
Free software Development model is based on the objective that the user should have freedom
over the software they use. Free software ensures that users have the rights to access, modify,
and distribute the source code of software. This is the fundamental aspect of free software
development. The users should have control over the software and Free Software Foundation
(FSF) specifies four essential freedoms, namely, (i) The freedom to run the program for any
purpose (ii) The freedom to study how the program works and modify it (iii) The freedom to
redistribute copies and (iv) The freedom to distribute copies of your modified versions.
The components involved in the free software model are shown in Fig 1.3
Version
control Software
contributors system repository
documentation users
Release
management
16
Software repository - This is the central location where the source code is stored and
managed.
Development environment - It includes different tools used the developers to develop the
software
Testing and issue tracking – This component refers to the verification and validation of the
software. Also, Issue Tracking refers to logging and tracking of bugs
Documentation – This representation the documentation related to the software
Release management – This represents the distribution of the software as a release
Users – This represents the users who utilize software and provide feedback
Exercise – 5
1. Why do we need open source software development model?
2. what is free software development model?
3. What does the word free in the free software development model signify?
17
commercial use. The Apache License encourages collaboration while allowing for proprietary
adaptations, making it suitable for both community-driven and commercial projects.
The GNU General Public License is another widely-used free software licenses that
guarantee end users the freedom to run, study, share, and modify the software. But while giving
the right for commercial usage, the GPL forces that author to expose how they made the original
better. Table 1.1 highlights the core aspects which can provide the basic idea while choosing a
license type
Table 1.1 Comparison of different licenses
MIT APACHE BSD GPL LGPL
Type Permissive Permissive Permissive Copyleft Copyleft
Free distribution Yes Yes Yes Yes (under Yes (under
GPL) GPL)
Can be used for Yes Yes Yes NO Partially
proprietary
project
Grant for Yes Yes Yes Yes Yes
Derivative works
Can be used as a Yes Yes Yes No Yes, with
module in a specific
proprietary conditions
application
Summary
This lesson provided a comprehensive idea about the basics of copy right laws and software
licensing. The readers would have a notion about various licenses including MIT license,
Apache license, BSD license and GNU GPL. Further, the readers have got understanding on
open source software development model along with the factors influencing the selection of a
suitable software license. Having obtained an idea about open source software license, in the
next lesson, the reader will explore the programming essentials of a widely used and versatile
open-source scripting language—Hypertext Preprocessor (PHP).
18
Intext Questions
1. Explain the primary purpose of copyright law in two sentences.
2. Differentiate between permissive and copyleft licenses in open source software development.
3. Define the free software development model and provide one key principle associated with it.
4. Discuss two fundamental principles of copyright law and how they protect the rights of
creators.
5. Discuss about MIT and Apache license
6. Write a note on GPL
7. What is BSD license?
8. Conduct a comparative analysis of permissive and copyleft licenses, discussing their
advantages, disadvantages, and use cases.
9. Outline the main steps in the open source development model, emphasizing collaboration and
community involvement.
10. Give a brief account on the components of free software development model
References
1. Mandal, S., Kandar, S., & Ray, P. (2011). Open Incremental Model: An Open Source
Software Development Life Cycle Model 'OSDLC'. International Journal of Computer
Applications, 21. [Link]
2. [Link] accessed on
26.11.2023
3. [Link] , accessed on 26.11.2023
ANSWERS
Exercise – 1
1. protect
19
2. Copyright protects the rights of creators by granting them exclusive rights to reproduce,
distribute, and display their original works
Exercise – 2
1. agreement
2. Software developers use licenses to specify how users can use, distribute, and modify their
software and to protect their intellectual property rights.
Exercise - 3
1. b. They impose minimal restrictions on how the software can be used and distributed.
2. a. MIT License
3. b. Compatibility with the GPL
4. BSD License
5. It restricts the use and distribution of software.
Exercise – 4
1. copyleft
2. open source
3. GPLv3 allows more restrictive terms than GPLv2. GPLv3 places more emphasis on
compatibility with proprietary software.
Exercise – 5
1. To encourage collaborative contributions, transparency, and community-driven innovation in
the creation and enhancement of software.
2. The free software development model is a paradigm in which software is distributed with a
license that grants users the freedom to use, modify, & distribute the software with its source
code.
3. In the context of the free software development model, the word "free" refers to freedom
rather than price. It signifies the fundamental freedoms granted to users, including the freedom to
run, study, modify, and redistribute the software and its source code.
20
Case study - Choosing a Software License for Smartweb - Hints
Option - 1
Consider that anyone be able to use it however they want. Allow users to do almost
anything with the software, including using it, modifying it, and even selling it.
(Hint – MIT license)
Option – 2
Everyone can use and change Smartweb, but if they share it, they must also share their
changes.
(Hint – GNU GPL)
21
UNIT II BASICS OF PHP PROGRAMMING
Objective
This lesson introduces the programming concepts of a general purpose, open source scripting
language, PHP, which is extensively used for dynamic web development. The objective of the
lesson is to provide the readers a comprehensive knowledge about the fundamental concepts of
PHP, including syntax, variables, control structures, array functions. strings, numbers, and
advanced array functions.
Learning outcomes
Upton completion of this unit, the reader would be able to
define and explain the concepts of constants and variables in PHP.
declare and using variables to store and manipulate data.
differentiate between various data types in PHP
work with different operators
to utilize different branching and loop statements
implement different kinds of functions
to define array to store multiple values of similar data type
to have a notion about different functions of arrays
write PHP scripts to solve basic programming problems.
develop problem-solving skills through hands-on exercises and projects.
2.0 Introduction
Hypertext Preprocessor (PHP) is a server-side scripting language, used to develop web
applications. It is free to download. Rasmas Lerdorf developed the first version of PHP. It is an
interpreted language. The purpose of PHP is used for building dynamic websites and web
applications. It is used to generate dynamic content, interact with databases, handle forms, etc.
The rest of this lesson discusses the fundamental concepts of PHP including data types,
variables, control structures, numbers, strings, functions, arrays, array functions and advanced
array functions
2.1 Features of PHP
PHP is an acronym for "Hypertext Preprocessor" or “Personal Home Page”
It is a widely-used, open source, server-side scripting language
22
It can work on different operating systems like Windows, Linux and MacOS
It provides a rich library support
It is simple and fast
It can generate dynamic page content
The PHP scripts are executed on the server
It is free to download and use
PHP files can contain text, Hyper Text Markup Language (HTML), Cascading Style Sheets
(CSS), JavaScript, and PHP code
PHP code is executed on the server, and the result is returned to the browser as plain HTML
PHP files have extension ".php"
It can create, open, read, write, delete, and close files on the server
It can collect form data
It can send and receive cookies
It can add, delete, modify data in your database
It can be used to control user-access
It can encrypt data
It is case sensitive
2.2 Advantages of PHP
PHP offers several unique advantages as a server-side scripting language.
Its widespread adoption, ease of learning, and platform independence make PHP suitable to a
wide range of developers
PHP seamlessly integrates with HTML, which makes it easy to generate dynamic web
content
The rich library support of PHP which facilitates the development of dynamic web
applications with a wealth of resources for developers.
PHP has a strong database interaction capabilities and scalability which makes PHP suitable
for building large-scale applications.
PHP also provides command-line scripting and desktop application development.
PHP has in-built security features which prevent common vulnerabilities.
23
Thus, the overall combination of accessibility, flexibility, resourcefulness, and robust
features make PHP a common choice for developing web applications
Author: Let’s listen to Nandhu and Vicky for their plan to develop some php scrips using
XAMPP server
Nandhu: Vicky, have you heard about XAMPP?
Vicky: let me quickly introduce XAMPP. XAMPP is a free, open-source software that
makes it incredibly easy to set up a local web server environment on your computer. It
includes essential components like Apache, MySQL, PHP, and more, allowing you to run
and test your web projects offline. XAMPP lets us create our very own web server on our
computer
Nandhu: You are right. You can download XAMPP from
[Link]
Vicky: oh great! After installation how to save my php scripts
Nandhu: There is a special spot called ‘htdocs’. It is a folder. make sure to place my PHP
scripts in that magical htdocs spot
Vicky: That’s fine. How to see the output? Where to see?
Nandhu: Good question. Actually, htdocs" is like the root directory of your local web
server. If you have a file named [Link] in the "htdocs" directory, you can access it
through your browser using the URL [Link]
I hope, now you are ready to test your php scripts. Am I right?
Vicky: Yes, Now I am alright. I will download the XAMPP from the above link and
create a local server environment using XAMPP to test my php scripts
Nandhu: good luck
PHP script
PHP engine
HTTP Request
24
Fig. 2.1 Working of PHP
As in Fig. 2.1, the browser makes a request for a web resource. This request is given to the web
server. The web server will then analyze it and determine what to do with it. If the web server
determines that the request is for a PHP file (.php doc) it will pass that file to the PHP interpreter.
The PHP interpreter will read the PHP file, parse it (and other included files) and then execute it.
Once the PHP interpreter finishes executing the PHP file, it will return an output. The web server
will take that output and send it back as a response to the browser
2.4 Basic PHP syntax
PHP is a scripting language; its code is embedded within HTML. The basic PHP syntax is
<html>
<body>
<?php
// PHP code goes here
?>
</body>
</html>
Example – The following PHP code will print “Hello World”. Here, the echo statement is used
to display the string
<html>
<body>
<?php
echo “Hello World”;
?>
</body>
</html>
25
Exercise – 1
1. PHP stands for ------------------------------
2. A single-line comment in PHP is denoted by ________.
3. What is a key advantage of PHP in web development?
a) Compiled execution
b) Cross-platform compatibility
c) Strict typing
d) Native support for mobile apps
<?
# This is a comment, and
// This is also a single line comment too.
26
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
• Resources − are special variables that hold references to resources external to PHP (such
as database connections).
The first five are simple types, and the next two (arrays and objects) are compound. The
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
2.7 Constant
A constant represents a quantity whose value cannot be changed. The define() function is used
to define a constant
define(constant_name, constant_value)
Example
define(“PIE”, 3.14);
2.8 Variables
Variables are "containers" for storing information. Fundamentally, variable represents a name
given to memory location. In PHP, a variable starts with the $ sign, followed by the name of the
variable
Example
<?php
$a=10; //here $a is a variable
?>
Rules
A variable starts with the $ sign, followed by the name of the variable
27
Narrator : Let us eavesdrop the dialog between Vicky and Nandhu discussing about
scope of variables in PHP
Vicky: Nandhu, I've been working on this PHP project, and I'm a bit confused about
variable scopes. Can you help me understand the difference between local, global, and
static variables?
Vicky: Of course, Nandhu! Local variables are confined to the function they're declared
in, global ones are like script-wide VIPs, and static variables are like persistent
memories within functions.
Scope of variables
In PHP, a variable can have three different scopes. They are local, global, and static
Local - A variable declared within a function has a local scope. It is visible only inside the
function and can be accessed only within that function
Example
<?php
function myTest() {
$x = 5; // local scope
}
?>
Global - The global keyword is used to access a global variable from within a function. To do
this, use the global keyword before the variables (inside the function)
<?php
$x = 10;
function myTest() {
global $x
$y = $x + 5;
}
myTest();
echo $y; // outputs 15
?>
Static - Static variables inside functions retain their values between function calls
Example
<?php
function myTest() {
static $x = 10;
28
echo $x;
}?>
Exercise – 2
1. How do you declare a variable in PHP?
a) var
b) $variable
c) #variable
d) variable
2. To declare a constant in PHP, one can use the ________ function.
3. What is the purpose of the static keyword in PHP?
a) To define a constant variable
b) To declare a variable with local scope
c) To retain the value of a variable across function calls
d) To restrict access to a variable
4. What is the key feature of global variable?
2.9 Operators
Operators are special symbols or keywords which are used to perform operations on variables
and values. They are important in expressing computations and conditions while performing
complex algorithms and logic within a language
PHP divides the operators in the following groups
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
Arithmetic operators
29
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
Table 2.1 Arithmetic Operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the
$yth power
Assignment operators
The PHP assignment operators are used with numeric values to write a value to a variable. The
basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
expression on the right. The basic assignment and compound assignment operators are given in
Table 2.2
Comparison operators
comparison operators are used to compare two values (number or string). Different comparison
operators available in PHP are given in Table 2.3
Table 2.3 Comparison operators
30
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and
they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or
they are not ofthe same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than $x >= $y Returns true if $x is greater than or equal to $y
or equal to
<= Less than or $x <= $y Returns true if $x is less than or equal to $y
equal to
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, according to if $x is
less than, equal to, or greaterthan $y.
Logical operators
Logical operators are used to combine conditional statement. They are described in Table 2.5
Table 2.5 Logical operators
31
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true,
but notboth
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
Conditional assignment operator
The conditional assignment operator, often referred to as the ternary operator, provides a concise
way to assign values to a variable based on a condition. The syntax of the ternary operator is:
$variable = (condition) ? value_if_true : value_if_false;
In the above syntax, the condition is evaluated. If it returns true, the value before the colon (:) is
assigned; otherwise, the value after the colon is assigned.
Example
$age = 25;
$status = ($age >= 18) ? "Adult" : "Minor";
If the variable $age is greater than or equal to 18, the value "Adult" is assigned to $status;
otherwise, "Minor" is assigned. In the above example, since the value of $age is 25, the value
“Adult” would be assigned to $status
String operators
PHP has two operators that are specially designed for strings. They are given in Table 2.6.
Table 2.6 String operators
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and
$txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
32
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; //output Helloworld!
?>
Example for Concatenation assignment
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
Exercise -3
1. Which PHP operator is used to compare two values for equality, both in terms of value
and type?
a) ==
b) ===
c) !=
d) !==
2. What operator is used for concatenating strings in PHP?
3. What is the purpose of the ternary operator (? :) in PHP?
33
Simple if – With simple if statement, a set of code is executed if a condition is true. If the
False
Condition?
True
Code block
condition is false, the code is not executed. The block diagram of simple if is shown in Fig. 2.2
Fig. 2.2 Simple if
Example
<?php
$a=10;
if($a<20) echo “Hello”;
?>
Output : Hello
If-else - If-else is a two-way branching statement. A set of code is executed if the given
condition is true and another set of code is executed if the condition is false. The block diagram
of if-else is given in Fig. 2.3
Condition?
If block else
block
Condition-1?
Condition-2?
35
Switch case is a multi-way branching statement. PHP switch statement compares a variable or
an expression against many different values and executes a code block based on the value it
equals to. The block diagram of switch case is given in Fig. 2.5
Switch (expression)
True
Case Code block 1
Value 1
False
True
Case
Code block 2
Value 2
False
True
Case
Value 3 Code block 3
False
36
Exercise - 4
1. In an "if-else" statement, the code block executed when the condition is false is
defined in the _______ block.
2. What will be the output?
<?php
$a = 5;
$b = 10;
if ($a < $b) {
echo "India";
} elseif ($a > $b) {
echo "USA";
} else {
echo "Equal";
}
?>
3. Spot the error
<?php
$number = 2;
switch ($number) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default
echo "Not a valid number"; }
?>
4. What is nested if?
37
False
Condition?
True
Body
Fig. 2.6
Syntax
while(condition)
{
//Statements
}
Example
<?php
$i=0; while($i<5)
{
echo $i;
echo ("<br>");
$i++;
}
?>
Output
0
1
2
3
4
38
do while – do-while is an exit-controlled loop. It is also used to perform a task repeatedly based
on some condition. The code inside do-while loop is executed at least once. The block diagram
of do-while is shown in Fig. 2.7
Body
True
Condition?
False
39
initialization, the test condition and the counter. Initially, the initialization will be done. Then
the condition will be tested. If the condition is satisfied, the body of the for loop will be
executed. After the execution of the body, the counter is incremented/decremented. Again, the
condition is tested and based on the outcome of the condition, the loop will be either executed or
not executed. The block diagram of for loop is shown in Fig. 2.8
Initialization
Condition?
True
Increment/Decrement
40
?>
Output
0
1
2
3
4
2.10.3 Transfer statements
There are two transfer statements, namely, continue and break.
continue statement - Continue state is used within loop structure. It is used to skip the rest of
current iteration and begins the next iteration
Example
<?php
for ($i = 0; $i < 5; ++$i)
{ if ($i == 2)
continue print "$i\n";
}
?>
Output
0
1
3
4
break statement – The break statement is used inside the conditional statements or loops and it
is used to exit the loop
Example
<?php
for ($i = 0; $i < 5; ++$i)
{ if ($i == 1)
break; print "$i\n";
}
41
?>
Output
0
Exercise - 5
1. Match the loop type with its description.
a. for i. Executes a block of code repeatedly as long as the condition is true.
b. while ii. A loop with a predetermined count of iterations.
c. do-while iii. Similar to while, but always executes the block of code at least once.
2. What is the purpose of the continue statement in a loop?
2.11 Functions
A function is a block of statements that can be used repeatedly in a program. A function will be
executed by a call to the function. In PHP a function is created using the following syntax
Syntax
function functionName() {
//code to be executed;
}
Example
<?php
function writeMsg()
{
echo "Hello world!";
42
}
writeMsg(); // call the function
?>
Different types of functions
Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions.
User Defined Functions : PHP allows us to create our own customised functions called the user-
defined functions.
The user-defined functions can be of different types
(i) functions with no arguments, no return types
(ii) functions with arguments but no return types
(iii) functions with no arguments but with return types
(iv) functions with both arguments and return type
Example for function with no arguments and no return types
<?php
function writeMsg() { echo "Hello world!";
}
writeMsg(); // call the function
?>
Example for function with arguments but no return types
<?php
function add($a, $b)
{ echo $a+$b;
}
add(3,6); // call the function & output is 9
?>
Example for function without arguments but with return type
<?php
function greetings() { return “god is great”;
}
greetings(); // call the function output- god is great
43
?>
Example for function with both argument and return type
<?php
function add($a, $b) {
return $a+$b;
}
$c=add(3,6); //call the function
echo $c; // output is 9
?>
45
Exercise – 6
1. Once a function is defined, it can be called multiple times within the same script.
State true or false
2. A function is invoked by using its _________
3. When passing a variable by value in PHP, what is modified inside the function?
a) Original variable
b) A copy of the variable
c) Reference to the variable
d) Function parameter
4. How is pass by reference indicated in a function parameter in PHP?
46
<form action="[Link]" method="post">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
Code in [Link]
<?php
$name = $_POST['name'];
echo "Hello, $name!";
?>
Sessions - Sessions allow to store information on the server that can be shared across multiple
pages.
Code in [Link]
<?php
session_start();
$_SESSION['name'] = 'John';
?>
Code in [Link]
<?php
session_start();
echo $_SESSION['name'] ;
?>
Cookies - Cookies store information on the client's machine.
Code in [Link]
<?php
setcookie("name", "John", time() + 3600, "/");
?>
Code in [Link]
<?php
echo $_COOKIE['name'];
?>
47
2.13 Strings, Numbers and Arrays
String is a sequence of characters enclosed within double quotes.
Example
<?php
$a=”hello”;
?>
Numbers are a fundamental data type used to represent numerical values. There are two main
types of numbers. integers and floating-point numbers. PHP is a loosely typed language. So,
one does not need to explicitly declare the data type of a variable. The data type of a variable is
determined dynamically based on the value it is assigned
<?php
$a=10; //integer number
$b=45.56 //floating point number
?>
Exercise – 7
1. Data is sent in the URL with the _______ method.
2. The _______ method sends data in the request body.
3. Data sent with the GET method is visible in the _______.
4. _______ is generally considered more secure than GET for sensitive data.
2.13.1 Arrays
Array is a subscripted variable used to hold more than one value of similar data type. Its size is
fixed. Array is created using array().
Example
<?php
48
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars); //output is 3
?>
In PHP, there are 3 types of arrays
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Indexed array - Each element of the array has a numeric index
Example
<?php
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
?>
Associative array - Each element has named key as its index
Example
<?php
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Multi-dimensional array - A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep
2.14 Array functions
Basic array functions include the following
(i) array_keys() - Returns all the keys of an array
(ii) array_merge() - Merges one or more arrays into one array
(iii) array_pop() - Deletes the last element of an array
(iv) array_push() - Inserts one or more elements to the end of an array
(v) array_reverse() - Returns an array in the reverse order
(vi) array_search() - Searches an array for a given value and returns the key
(vii) array_values() - Returns all the values of an array
49
(viii) count () - Returns the number of elements in an array
(ix) key() - Fetches a key from an array
Exercise – 8
1. How do you declare an indexed array in PHP with elements 10, 20, and 30?
2. Which PHP function is used to find the number of elements in an array?
50
Example
<?php
$numbers = [1, 2, 3, 4, 5];
$even_numbers = array_filter($numbers, function($n) { return $n % 2 == 0; });
print_r($even_numbers);
?>
Output
Array
(
[1] => 2
[3] => 4
)
array_walk() - applies a user-defined function to each element of an array.
Example
<?php
$cities = ["Chennai", "Calcutta", "Mumbai"];
array_walk($cities, function(&$value, $key) { $value = strtoupper($value); });
print_r($cities);
?>
Output
Array
(
[0] => CHENNAI
[1] => CALCUTTA
[2] => MUMBAI
)
array_column() - returns the values from a single column in a multi-dimensional array
Example
<?php
$employees = [
['name' => 'Raj', 'age' => 45],
51
['name' => 'Kamal', 'age' => 56],
['name' => 'Karthi', 'age' => 45]
];
$names = array_column($employees, 'name');
print_r($names);
?>
Output
Array
(
[0] => Raj
[1] => Kamal
[2] => Karthi
)
Exercise – 9
1. What does the array_map() function do in PHP?
2. What is the purpose of the array_column() function?
Summary
This lesson has introduced the basic programming concepts of PHP including, defining
constants, declaring variables, using operators, constructing conditional statements, using
different iterative statement, implementing functions, creating arrays, and employing array
functions with examples. Upon the completion of the lesson, the reader would be able to write
PHP scripts using the above concepts. This lesson has laid the foundations of PHP programming
52
which is crucial developing dynamic web applications. In the next lesson, the reader will delve
into the object oriented concepts and advanced functions for patten matching in string in PHP.
Intext questions
1. Describe with example how to declare a variable in PHP. List out the rule of variables
2. List out various data types in PHP
3. Why do we need different control structures?
4. Explain different branching statements in PHP
5. Explain briefly different looping statements
6. Give an account of continue and break in PHP
7. Do we really need functions, Justify
8. Explain in detail, how to create functions and invoke them
9. What is the purpose of array? Give its types
10. Write a note on array functions
11. Write a PHP program to determine the grade of a student for the given marks in different
subjects using nested if
References
[Link]
[Link]
[Link]
ANSWERS
Exercise – 1
1. Hypertext Preprocessor
2. //
3. b) Cross-platform compatibility
Exercise – 2
1. b) $variable
2. define
53
3. c) To retain the value of a variable across function calls
4. A global variable is a variable declared outside of any function and is accessible from
anywhere in the script
Exercise – 3
1. b) ===
2. . (period)
3. Conditional assignment
Exercise – 4
1. else
2. India
3. : is missing after the keyword default
4. Nested if is a programming construct where one if statement is placed inside another, allowing
for conditional execution based on multiple levels of conditions.
Exercise – 5
1.
a. ii
b. i
c. iii
2. To skip the rest of the code inside the loop and move to the next iteration.
Exercise – 6
1. true
2. name
3. b) A copy of the variable
4. By using the & symbol
Exercise – 7
1. Get
2. Post
3. URL
4. Post
54
Exercise – 8
1. $a = array(10, 20, 30);
2. count()
Exercise – 9
1. It applies a specified callback function to each element of an array and returns a new array of
the results
2. It returns the values from a single column in the input array.
Exercise – 10
1. define("G", 9.81);
2. <?php
$num = 6;
if ($num % 2 == 0) {
echo "$num is even.";
} else {
echo "$num is odd.";
}
?>
3. <?php
$count = 1;
while ($count <= 5) {
echo "hello";
echo “<br>”;
$count++;
}
?>
4. <?php
function findArea($base, $height) {
// Area of a triangle formula: (base * height) / 2
55
$area = ($base * $height) / 2;
return $area;
}
// Example usage:
$b = 8;
$h = 5;
$area = findArea($b, $h);
echo "The area of the triangle is: $area";
?>
56
UNIT III ADVANCED FEATURES AND TECHNIQUES
Objective
The objective of this unit is to provide a brief overview of the basic concepts of object-oriented
programming and to familiarize readers with fundamental Object Oriented Programming (OOP)
concepts in PHP, such as classes, objects, constructors, destructors, access modifiers, and method
overriding. Additionally, the unit explores some advanced topics in PHP, including regular
expression functions, cookies, sessions, and exception handling
Learning outcomes
Upon completing this unit, the reader would be able to
define the fundamental concepts of object-oriented programming, including classes and
objects.
comprehend the purpose of constructors and destructors.
apply access modifiers to control the visibility of class properties and methods.
understand the use of regular expression functions for pattern matching
store state variables using cookies and sessions.
employ the concept of exception handling
apply the acquired knowledge through while writing PHP scripts
3.0 Introduction
Object-oriented programming is a kind of programming paradigm that emphasizes importance to
both data and functions while developing a software. It uses the concept of objects to organize
and structure code. Here, inside the object, the data and functions are coupled in such a way that
a particular data can be manipulated by its corresponding functions only. This kind of
programming paradigm make the structure of any complex programme more modular. In
addition, the modules would be developed with important principles like cohesion. Modules are
cohesive but independent of other modules. Modules can communicate with one another in a
loosely coupled manner, with the help of message. Ultimately, the object oriented programming
paradigm helps in the development of complex software in the form or more modular, organized,
and scalable manner so that software reusability and maintenance can be achieved easily.
Software modification will affect only the concerned module and other modules will remain
unaffected. In short, object-oriented programming has the potential to improve code
57
organization, promote reusability, enhance security through encapsulation, simplify complex
systems through abstraction, and provide flexibility and scalability through polymorphism. This
lesson will introduce the object oriented programming concepts in PHP with a series of examples
3.1 Concepts of Object Oriented Programming
58
In addition to the above OOPs concepts, there are also other design features such as modularity,
cohesion within a class and loose coupling among the modules are being adopted in OOP
paradigm as these principles help in the development of more manageable and maintainable
software. Here, modularity refers to the process of breaking down a software system into
smaller, independent, and interchangeable modules or components. Cohesion refers to the
degree to which the elements within a module or class are related to each other and contribute to
a single, well-defined purpose. Coupling refers to the degree of interconnectedness between
modules in a software. The goal of coupling is to reduce the dependencies among the modules
Author: Let’s watch the conversation between Vicky and Nandhu, on the topic classes and
objects in PHP
Vicky: Nandhu, you were talking about your mini project in PHP. Why don’t you develop
your work using OOPs in PHP?
Nandhu: Yes, I have already decided to do so. Just started reading about classes and
objects in PHP
Vicky: What are they?
Nandhu: Think of a class as a blueprint for creating something in the programming world.
Consider that you want to model a ‘Scooty’.
You'd create a class called "Scooty" that defines what a Scooty is through its attributes (i.e.
properties) and methods (i.e. behaviour). It could have attributes like colour, model, and
methods like start or stop.
Vicky: then, you mean, a class is like a description of something
Nandhu: That’s right. Now, an object is an instance of that class. When we create an
object, memory would be allocated to the object
3.2 Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces
Syntax
<?php
class Fruit {
// code goes here...
}
59
?>
Example:
<?php
class Fruit {
// Properties public
$name;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
There is one property ($name) and two methods set_name() and get_name().
3.3 Object and its creation
We can create multiple objects from a class. Each object has all the properties and methods
defined in the class, but they will have different property values. Objects of a class is created
using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
<?php
class Fruit {
// Properties public $name;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {return
$this->name;
}
60
}
Vicky: Have you ever thought of how to initialize an object upon its creation
Nandhu: yeah, there is a wonderful concept of constructor, a special function used to
initialize the instance variables of an object immediately upon its creation. The beauty of
constructor is that it would be automatically invoked.
Also, similar to constructor, you can include the cleanup tasks such as closing a database
which is in opened state or release resources associated with an object before it is
removed from memory, in another special method called destructor. Let’s move on to the
syntax with an example
Vicky: Sure
3.4 Constructor
A constructor is a special function which is automatically called when an object is created. Its
primary purpose is to initialize the attributes of a newly created object and used to perform any
setup tasks such as establishing connections, or setting default values. In PHP, the basic syntax of
a constructor is
public function _ _construct()
{
//code to initialize parameters
}
<?php
class Box
{
public $length;
61
public function _ _construct($len)
{
$this->length = $len;
}
}
echo $mybox->length;
?>
3.5 Destructor
A destructor is called when the object is destroyed. A destructor is also another special method
within a class that is automatically invoked when an object is destroyed or goes out of memory. In
PHP, the destructor method is named _ _destruct(). The primary purpose of a destructor is to
perform cleanup tasks or release resources associated with the object before it is removed from
62
}?>
3.6 Inheritance
As discussed earlier, inheritance allows one class to inherit the properties and behaviour of
another class using ‘extends’ keyword. In this way, inheritance has advantages of both
extensibility and code reusability
Example
<?php
class BaseClass
{
function add()
{
//code
}
}
class child extends BaseClass
{
//code in subclass
}
?>
Exercise – 1
1. What is a class?
a) An instance of an object.
b) A function that performs a specific task.
c) A blueprint or template for creating objects.
d) A data type that represents a single value.
2. An ____________ is an instance of a class.
3. Which keyword is used in PHP to implement inheritance between classes?
a) extends
b) inherit
c) derive
d) implements
4. The class that inherits from another class is called the ____________ class.
63
3.7 Method overriding
Method overriding in PHP allows a subclass to modify the implementation of a method that is
already defined in its parent class. This means that the subclass overrides the implementation of
the concerned method, that is defined in the superclass. The overridden method in the subclass
must have the same signature (name, return type, and parameters) as the method in the
superclass. Another important aspect is that, the type of the object determines which method
must be invoked during run time. i.e., when an object of subclass is invoked, then the method
defined in the subclass will be executed. If an object of superclass invokes the method, then the
method defined in the superclass will be executed.
Example
<?php
class A {
public function greetings() {
return "Hello from class A";
}
}
class B extends A {
public function greetings() {
return "Hello from class B";
}
}
$a = new A();
$b = new B();
echo $a->greetings(); // Output: "Hello from A!"
echo $b->greetings(); // Output: "Hello from B!"
?>
64
Exercise – 2
1. Why is method overriding referred to as run-time polymorphism in object-
oriented programming?
function setRollno($r) {
$this->rollno = $r;
}
}
$s = new Student();
$s->setRollno('5649'); // OK
?>
Example for protected
<?php
class Student {
65
protected $rollno; //protected scope
function setRollno($r) {
$this->rollno = $r;
}
}
class Pgstudent extends Student
{
}
$s = new PgStudent();
$s->setRollno('5649'); //accessing protected $rollno in a subclass
?>
Example for private
<?php
class Student {
private $rollno; //private scope
function setRollno($r) {
$this->rollno = $r; //accessing private $rollno within the class
}
}
Exercise – 3
1. Access modifiers control the ________ of class properties and methods.
2. The protected access modifier limits visibility to the class itself and its _______.
3. Private access modifier restricts visibility to the ________ itself.
Author: Let us listen to the talk of Vicky and Nandhu on regular expression functions
Vicky: Have you work with regular expression function in PHP?
Nandhu: Regular expression functions are used to perform pattern matching and
manipulation on strings
Vicky: Let us a look at regular expression functions in PHP
67
Splitting: Divide a string into an array of substrings based on a pattern.
Following are the some of the regular expression functions available in PHP
preg_match() – This function searches for a pattern in the given string and returns true if a
match is found.
preg_match_all() – This function searches for all occurrences of a pattern in a string and
returns an array of all matches.
preg_replace() – This function replaces occurrences of a pattern with a specified
replacement.
preg_split() – This function splits a string into an array of substrings based on a regular
expression pattern.
preg_quote() – This function escapes special characters in a string
Exercise - 4
1. Walk through the following program. What will check($input) return?
<?php
function check($text) {
$pattern = '/World/';
if (preg_match($pattern, $text)) {
return true;
} else { return false; }
}
$input = "Hello, World!";
check($input);
?>
68
Narrator: Let us listen to the motivational chat of Vicky and Nandhu on session and
cookie
Nandhu: Have you worked with cookie and session in PHP?
Vicky: No, what they are?
Nandhu: cookie and session are mechanisms to store state variable in a HTTP based
communication. They are used to store information related to user authentical,
personalization and tracking user activity
Vicky: Why there are two mechanisms? What is the difference between these two?
Nandhu: Cookies are small pieces of data stored on the user's browser, while sessions are
server-side storage. Cookies are handy for persisting small amounts of data on the user's
machine, like user preferences. On the other hand, sessions are often used to store larger
sets of data securely on the server.
69
User-1
Server
Session - 1
(for User-1)
Session - 2
User-2 (for User-2)
<?php
session_start();
$_SESSION[‘name’] = ‘John’;
?>
Code in [Link]
<?php
session_start();
echo $_SESSION[‘name’] ;
?>
Thus, session allows stateful interaction, server-side storage, cross-page communication,
scalability, ease of use, customization and versality
3.10.2 Cookies
Cookies store information on the client’s machine. A cookie is a small piece of data that a web
server sends to a browser. This data is stored on the browser and is sent back to the server with
subsequent requests. The data is stored in the form of key-value pairs in cookie. The concept of
cookie is illustrated in Fig. 3.2
70
Cookie created by server and stored in browser
Browser
Cookie is stored at
Server
Cookie name=”John” browser
Cookie
creation at
server Cookie
name=”John”
71
terminated. To avoid the termination or halting of the program, the exception must be handled.
Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors
(runtime errors are called exceptions). So that the normal flow of the application can be
maintained.
The main purpose of using exception handling is to maintain the normal execution of the
application.
PHP offers the following key words for exception handling
try
catch
throw
finally
When an exception occurs, the current state of program execution would be saved. The
execution would be transferred to the predefined handler’s function. The handler function can
take different actions like (i) resume the execution from the saved state or (ii) continue the
execution from another location or (iii) halting the execution, according to the nature of
exception occurred
3.11.1 Exception handling using try – catch
The structure of try-catch block is as shown
try {
// the code where the exception occurs
}
catch (exception $e) {
//code to handle the exception
}
try - The try block contains the code in which an exception may occur during execution. The
code within the try block is executed until an exception occurs
catch - The catch block will be called only if an exception occurs within the try block. The catch
block catches the exception that occurred in the try block and handles the exception
Example
<?php
try {
72
$a=5;
$b =0;
$c=$a/$b; // DivideByZeroException occurs as the denominator is zero
echo $c;
}
catch (DivideByZeroException $e) {
echo “Divide by Zero error has occurred”;
}
?>
[Link] Exception handling using try with multiple catches
The code in try block may contain more than one exception and, in such situation, the try block
would be accompanied by multiple catch blocks to handle multiple exceptions that are likely to
occur.
Consider the following example. The code in try block shows a function called divide which
performs the division of a number (called numerator) by another number called (denominator).
It is obvious that the division process can be applied only to numerical values. In case any of the
above values is not numeric, then InvalidArgumentException will be thrown. In addition, when
the denominator is zero, DividebyZeroException will be thrown. The example handles these two
exceptions with two catch blocks
<?php
function divide($a, $b) {
try {
$result = $a / $b;
} catch (InvalidArgumentException $e1) {
// Catch and handle the InvalidArgumentException
echo "Caught InvalidArgumentException: " . "\n";
} catch (DivisionByZeroError $e2) {
// Catch and handle the DivisionByZeroError
echo "Caught DivisionByZeroError: " . "\n";
}
}
73
divide(10, "india"); // calling the function with denominator not numeric
divide(10, 0); //calling the function with denominator zero
?>
3.11.2 Exception handling with try-finally block
The finally block is used in combination with a try block to a block of code that will be executed
irrespective of whether an exception occurred or not in the try block. This means that the code
inside the finally block will always be executed which helps in ensuring that certain cleanup or
finalization action has been taken place.
The structure of try-finally block is given below
<?php
try {
// Code Inside try block
} finally {
// code inside finally block. This block will always be executed irrespective of whether an
exception //occurred or not
}
?>
Example
<?php
try {
$a=5;
$b =0;
$c=$a/$b; // DivideByZeroException occurs as the denominator is zero
echo $c;
} finally {
echo “DivideByZeroException”;
}
?>
As seen through the above example, one can understand that a try block must always be
associated with a catch or finally block. The try block cannot stand alone. In addition, finally
block can also be included in try-catch structured as given below
74
<?php
try {
$a=5;
$b =0;
$c=$a/$b; // DivideByZeroException occurs as the denominator is zero
echo $c;
}
catch (DivisionByZeroError $e) {
echo "DivisionByZeroError caught in catch block”;
}
finally {
echo “This code block in finally block”;
}
?>
3.11.3 Exception handling using throw
The throw keyword in PHP is used to explicitly throw an exception. The throw keyword is used
to create and throw and object that represents an exception. Further, the throw keyword can be
used while creating custom exception
Example
<?php
function myfunction($value) {
if (!is_numeric($value)) {
throw new InvalidArgumentException("Value must be numeric");
}
}
try {
myfunction("india");
} catch (InvalidArgumentException $e) {
echo "The argument of the function must be numeric”;
}?>
In the above example, the argument of myfunction, called $value is checked against whether it is
75
a numeric value or not. If the argument is not numeric, then the keyword ‘throw’ is used to
create a new object of InvalidArgumentException and it is thrown. The above function is called
inside a try block. Kindly note that the argument passed is a text “india”. Since, the argument is
not numeric, InvalidArgumentException will occur, which will be caught in the corresponding
catch.
Exercise – 5
1. In PHP, what keyword is used to initiate exception handling within a block of code?
a) throw
b) catch
c) try
d) finally
2. What is the purpose of the catch block in exception handling?
a) Not to handle exception
b) To handle or catch exceptions
c) To define the finally block
d) To terminate the script
3. What is the primary purpose of the finally block in exception handling?
a) To handle exceptions
b) To throw exceptions
c) To execute code regardless of whether an exception occurs or not
d) To define the catch block
Summary
This lesson, has described the basics of Object-Oriented Programming such as class, object,
constructor, destructor along with a brief note on encapsulation, inheritance, and polymorphism.
The concept of inheritance has been explored. The use of regular expression functions for string
pattern matching and manipulation has been introduced. Two important facilities to maintain
the state variable of HTTP, namely, cookie and session have been discussed. Further, exception
handling mechanisms have been described with examples. In the next lesson, the reader will be
76
exploring how to establish database connections from PHP, using a popular relational database
management system - MySQL
Intext Questions
1. Describe in detail the object oriented programming concepts
2. How can encapsulation be implemented in PHP?
3. Explain class and object with example
4. Describe the purpose of constructor and destructor in PHP
5. Define HTTP
6. Why do we need cookie and session?
7. Explain in detail session and cookie?
8. Describe briefly inheritance with example
9. What is exception? What is the necessity for exception handling?
10. Elaborate in detail, different exception handling mechanisms with example
11. Write a note on regular expression functions
12. Write a note on access modifiers
References
1. [Link]
2. [Link]
3. [Link]
Consider a scenario where a web application relies heavily on sessions for user
authentication.
Discuss the security implications of session-based authentication. How can the
application protect against session hijacking or session fixation attacks?
ANSWERS
Exercise -1
1. c) A blueprint or template for creating objects.
2. object
3. a) extends
77
4. sub
Exercise – 2
1. Because the type of the object determines which method will be invoked and it occurs during
run-time
Exercise – 3
1. visibility
2. subclasses
3. class
Exercise – 4
1. true
Exercise – 5
1. c)try
2. b) To handle or catch exceptions
3. c) To execute code regardless of whether an exception occurs or not
78
UNIT IV - PHP AND MySQL
Objective
The objective of this lesson is to provide the readers with fundamental concepts of server-side
scripting, focusing on establishing connections with MySQL and performing database-related
operations using SQL. The lesson introduces the features of SQL, MySQL, logical architecture
of MySQL Server. Also, the lesson presents, the significance of MySQL database administration
with special emphasis to PHP/MySQL functions. It provides a tour of the PHP scripts,
demonstrating how to connect to databases, retrieve and display queries through examples
Learning outcomes
By the end of this unit, the reader should achieve the following
79
Develop data-driven web applications using PHP and MySQL
Vicky: Hey Nandhu, have you ever wondered how websites store and manage all that
data?
Nandhu: It's like magic! How do they do it?
Vicky: Well, it's a combo of MySQL, PHP, and SQL. MySQL is the database where all
the information is stored.
Nandhu: Ah, the database! So, how does PHP come into play?
Vicky: PHP is the language that talks to the database.
Nandhu: Nice teamwork! And what's SQL's role in all this?
Vicky: SQL is the query language that PHP uses to chat with MySQL. It tells the
database what to do, like fetching data or updating stuff.
Nandhu: Got it! So, MySQL stores the data, PHP talks to it, and SQL is the query
language that informs the database about what needs to be done.
Vicky: Exactly! Let’s move on to a quick tour of the stuff.
4.0 Introduction
PHP is a server-side, object-oriented scripting language, used to generate dynamic web content
that is then sent to the client's browser. PHP is open-source and it can be easily integrated with
databases. It supports a variety of databases which makes the language a popular choice for
developing dynamic web applications.
MySQL is an open-source relational database management system (RDBMS). It employs
Structured Query Language (SQL) (RDBMS) to manage databases. MySQL is known for its
speed, reliability, and scalability. MySQL supports various storage engines. MySQL is a key
component in the two popular technology stacks for web application development, namely,
Linux, Apache, MySQL, PHP (LAMP) and MongoDB, [Link], AngularJS, [Link]
(MEAN).
Thus, in the combination of PHP and MySQL, PHP handles the server-side scripting, while
MySQL manages the database which allows developers to develop useful scalable data-driven
applications.
4.1 Server-side web scripting
80
Server-side scripting is required to process and generate dynamic content on the server before
delivering it to the client's browser. The significance of server-side scripting lies in its ability to
perform complex operations, interact with databases, and handle server-level tasks, ensuring a
more secure and efficient web experience while maintaining separation of presentation and logic.
As we discussed in the previous chapter, PHP is a server side scripting languages and the
following features makes it a special choice for implementing server side code
PHP is open-source. It is freely available for use and modification.
It has a large community support
PHP is specifically strong in integrating with databased. It works seamlessly with MySQL
PHP is platform independent
It is easy to learn
It provides large library support for performing different tasks
It facilitates rapid application development
It provides built-in security features
Ultimately the unique attributes of PHP include its adaptability, database integration
capabilities, extensive community support, and its role in facilitating the development of
dynamic and interactive web applications
Structured Query Language (SQL)
Structured Query Language (SQL) is a standard language for creating, managing and
manipulating relational databases. SQL is used to organize, manage and retrieve data from
relational databases
4.2 Features of SQL
SQL is a declarative language
SQL includes two different types of languages, namely, Data Definition Language (DDL)
and Data Manipulation Language (DML).
DDL is used to specify the structure of a database. It includes the structure of tables, views,
indexes, and constraints. DDL commands include CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
81
DML is used to insert, update, remove, and retrieve data from a database. The DML
commands include INSERT, UPDATE, DELETE, and SELECT. DML statements have a
direct impact on the database’s data.
SQL is a non-procedural and declarative language
SQL is based on ANSI standards.
SQL supports transactions, which allow a sequence of one or more atomic tasks to be
executed as a single unit. This ensures the Atomicity, Consistence, Isolation and Durability
(ACID) properties of relational database management systems
SQL includes data integrity constraints, namely, primary key and foreign key which help to
achieve accuracy and reliability of the data.
SQL supports join operations which help to combine data from more than one table
SQL allows the grouping of data using the GROUP BY clause, and aggregation functions
(e.g., COUNT, SUM, AVG) enable the calculation of summary values for grouped data.
SQL supports subqueries, allowing queries to be nested within other queries which are useful
in performing complex database operations
SQL includes security features such as user authentication, authorization, and the ability to
set permissions on database objects to control access.
SQL allows the creation of indexes on tables to improve the speed of data retrieval
Views in SQL provide a virtual representation of data stored in one or more tables. They
allow users to simplify complex queries and control access to specific columns or rows of a
table
SQL supports the creation of stored procedures and functions, allowing users for code reuse
Exercise – 1
1. MySQL is a relational database management system. Say True / False
2. SQL is a ______ language, meaning it focuses on what needs to be achieved rather
than how to achieve it.
3. SQL allows the creation of ______ on tables to improve the speed of data retrieval
4. Data integrity constraints in SQL include ______ and ______ keys.
5. DDL is used to specify the ______ of a database, including the structure of tables,
views, indexes, and constraints.
83
Security - The client layer contributes to security by enforcing secure communication between
the client and the MySQL server. This includes encryption of data during transmission and
ensuring that only authorized clients can access the database.
Client Layer
File system
84
SQL interface - It provides an interface between the client layer and the MySQL server. This is
where SQL commands received from the client are processed and executed by interacting with
underlying database.
SQL parser - The SQL parser is a component of the core layer that interprets and analyzes the
SQL commands received from the SQL interface. It breaks down the SQL statements into a
structured format that the MySQL server can understand. This parsing step is essential for
translating user queries into a form that the server can execute.
Optimizer - The optimizer is a critical component responsible for determining the most efficient
way to execute a given SQL query. It analyzes different execution plans and chooses the one that
minimizes the overall cost, considering factors like indexes, join methods, and other optimization
strategies. This contributes to the performance and efficiency of query execution.
Caches and buffers - Caches and buffers are components within the core layer that enhance
performance by storing frequently accessed data in memory. This includes query caches, which
store the results of frequently executed queries, and various buffers for managing data during
read and write operations.
Storage engine layer - Storage engines are MySQL components, that can handle the SQL
operations for different table types to store and manage information in a database. Various
storage engines supported by MySQL include the following
InnoDB is the default storage engine. It provides transaction-safe tables and supports
referential-integrity constraints. It supports commit, rollback, and crash-recovery capabilities
to protect data. It also supports row-level locking. It provides high performance. It stores
data in clustered indexes.
MyISAM – The MyISAM storage engine, manages non transactional tables, provides high-
speed storage and retrieval, supports full text searching.
Memory – Memory storage engine provide in-memory tables and stores data in RAM. It
provider faster performance
Merge – Merge storage engine groups more than one MyISAM non-transactional table and
provides a single table view.
CSV – CSV engine stores data in comma separated value format in text file
Archive – Archive storage engine is used to store very large amount of data
Federated – Federated storage engine is used to store data in remote database
85
File system – The bottom most layer represents the underlying file system
Exercise -2
1. In the MySQL Server logical architecture, the ______ layer interacts directly with the
end-user applications and manages user requests.
2. The ______ layer in the MySQL Server logical architecture is responsible for
processing SQL statements, managing connections, and handling security and
authentication.
3. The ______ layer of the MySQL Server logical architecture involves storage, retrieval,
and manipulation of data, including the implementation of storage engines.
86
Estimating future growth and resource needs to plan for additional storage, processing power, or
other infrastructure requirements.
Database administrators work closely with other IT professionals, including developers, system
administrators, and network engineers, to ensure the overall success and reliability of database
systems in an organization.
4.5.1 Facilities for MySQL database administration
MySQL provides the following facilities for database administration
MySQL Workbench - It is an integrated development environment (IDE) for MySQL that
provides visual tools for database design, SQL development, administration, and maintenance
Command-line tools - MySQL offers a set of command-line tools that allow administrators to
interact with the database system directly.
MySQL Enterprise Edition – It is a commercial offering from Oracle that provides additional
features and tools for database administration, including advanced monitoring and management
tools, as well as premium support.
System variables - MySQL provides a wide range of system variables that allow administrators
to configure and tune the behavior of the MySQL server.
Performance schema – The Performance Schema is a feature in MySQL that provides a way to
inspect the internal execution of the server at runtime.
MySQL Enterprise Monitor - It is a tool that provides real-time monitoring and analysis of the
MySQL database server.
Event Scheduler - The Event Scheduler allows administrators to schedule and automate recurring
tasks within the database, such as backups, maintenance, and other administrative processes.
Backup tools - MySQL provides tools like mysqldump for creating logical backups of databases
and mysqlbackup for creating physical backups. These tools are essential for implementing
backup and recovery strategies.
Security tools - MySQL includes robust security features for managing user access,
authentication, and encryption. This includes user account management, roles and privileges, and
support for secure connections using SSL.
Replication tools - MySQL supports replication, allowing administrators to create copies of a
database on different servers. This is useful for high availability, load balancing, and disaster
recovery.
87
MySQL Utilities – It refers to a collection of command-line utilities that assist in the
management of MySQL servers. It includes tools for tasks such as data copying, failover, and
replication setup.
Database administrators working with MySQL often use a combination of command-line
interfaces (CLI) and graphical tools like MySQL Workbench, depending on their preferences,
the task at hand, and the specific requirements of their environment.
Which one to use?
The MySQL Command-Line Interface is a standard and essential tool, particularly for tasks that
require scripting, automation, or direct server access. Command line interface provides a direct
interaction with the server. It is lightweight and efficient for quick tasks and scripting. It is ideal
for remote server management through Secure Shell. It provides more control over specific
commands and parameters. More importantly, command line interface offer precise control and
automation
MySQL Workbench Provides a visual interface for database design, development, and
administration. It simplifies complex tasks through a graphical user interface. It includes
features like visual query building, schema design, and performance monitoring. It is often
preferred for tasks such as database design, schema management, and visual query building. In
addition, a database administrator is likely to employ different tools such as MySQL enterprise
monitor, replication and backup tools according to the specific needs
88
Exercise – 3
1. Which MySQL administration tool is best suited for users who prefer a graphical
user interface (GUI) for managing databases?
a) MySQL Command Line
b) MySQL Shell
c) MySQL Workbench
d) MySQL Terminal
2. What is the primary advantage of using MySQL Command Line tools for
administration tasks?
a) Provides a graphical user interface for easy navigation
b) Allows direct interaction with database and supports efficient batch processing and
automation
c) Only supports basic SQL queries
d) Requires less memory compared to other tools
Example
// Establish a procedural-style connection
89
$conn = mysqli_connect("localhost", "username", "password", "database");
// Perform a query
$result = mysqli_query($conn, "SELECT * FROM table");
// Fetch and process the results
while ($row = mysqli_fetch_assoc($result)) {
// Process each row
}
mysqli_close($conn); // Close the connection
The procedure-oriented functions are listed below with a description
mysqli_connect() - Opens a new connection to the MySQL server.
Example
$conn = mysqli_connect("localhost", "username", "password", "database");
mysqli_close() - Closes a previously opened database connection
Example
mysqli_close($conn);
mysqli_select_db() - Sets the default database for the connection.
Example:
mysqli_select_db($conn, "database");
mysqli_query() - Performs a query on the database
Example
$result = mysqli_query($conn, "SELECT * FROM table");
mysqli_fetch_assoc() - Fetches a result row as an associative array.
Example
$row = mysqli_fetch_assoc($result);
mysqli_fetch_object() - Fetches a result row as an object.
Example
$row = mysqli_fetch_object($result);
mysqli_fetch_array() - Fetches a result row as an associative array, a numeric array, or both.
90
Example
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
mysqli_num_rows() - Gets the number of rows in a result.
Example
$numRows = mysqli_num_rows($result);
mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation.
$affectedRows = mysqli_affected_rows($conn);
mysqli_error() -Returns a string description of the last error.
Example
$error = mysqli_error($conn);
Exercise – 4
1. What is the purpose of mysqli_connect()?
2. What is the primary purpose of the mysqli_select_db() function in PHP?
a) Open a new connection to the MySQL server.
b) Close a previously opened database connection.
c) Execute a query on the MySQL database.
d) Set the default database for the connection.
3. What is the main use of mysqli_query() function when interacting with MySQL
databases?
4. What is the difference between mysqli_fetch_object() and mysqli_fetch_array()
5. mysqli_num_rows() - Gets the number of ________ in a result.
6. -------- returns the number of rows affected in a previous MySQL operation
91
// Establish an object-oriented connection
$conn = new mysqli("localhost", "username", "password", "database");
// Perform a query
$result = $conn->query("SELECT * FROM table");
// Fetch and process the results
while ($row = $result->fetch_assoc()) {
// Process each row
}
$conn->close(); // Close the connection
mysqli::__construct() - Constructor for the mysqli class. Establishes a connection to the
MySQL server.
Example
$conn = new mysqli("localhost", "username", "password", "database");
mysqli::close() -Closes a previously opened database connection (used with the mysqli class).
Example
$conn->close();
mysqli::query()-Performs a query on the database (used with the mysqli class).
Example
$result = $conn->query("SELECT * FROM table");
4.7 Displaying Queries in Tables
Displaying queries in tables in MySQL typically involves executing a query and presenting the
results in a tabular format for easy understanding and analysis
Consider the following SQL query
SELECT * FROM employees;
The results can be formatted into HTML tables for display on the web pages.
<?php
// Assuming $result is the query result
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
92
echo "<tr>";
foreach ($row as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Exercise - 5
1. mysqli::__construct() - Constructor for the mysqli class and used to _________.
2. ---------------------------- is used to perform sql queries on a MySQL database in
an object oriented manner
Exercise – 6
1. What is the purpose of building forms from queries?
2. What is the use of action and method attributes of form?
Summary
This lesson has explored essential concepts related to MySQL database connectivity from PHP.
It covers features of SQL and MySQL, discussing their significance in database management.
95
The logical MySQL server architecture is presented to offer readers with a holistic view. PHP
boasts built-in functions for connecting to MySQL, available in both procedural and object-
oriented approaches. The lesson delves into the potential of PHP in the context of MySQL
interactions, providing readers with insights into practical skills for integrating databases into
web applications using PHP and MySQL. In the next lesson, the reader will explore the power
of Asynchronous JavaScript And Xml (AJAX) in achieving enhanced user experience.
Intext Questions
1. List out the features of SQL
2. Write down the features of MySQL
3. What is DDL?
4. What is DML?
5. Describe in detail the logical architecture of MySQL server
6, Write a note on MySQL database administration
7. Explain in detail the uses of various PHP/MySQL functions
8. What the two major approaches for MySQL and PHP database connectivity. Give a brief note
on each of them
9. How to display the results of a query in HTML table
10. Write a note on how to submit a form data to a PHP script to perform simple database
operation.
References
1. Php & My Sql In Easy Steps by Mike Mc Grath, BPB Publications, ISBN – 9789386551405,
2017
96
2. Sams Teach Yourself Php Mysql And Apache, By Meloni J C, Pearson India, ISBN-
9789332502017
3. Learning PHP & MySQL, 2nd Edition by Michele E. Davis, Jon A. Phillips, Released August
2007, Publisher(s): O'Reilly Media, Inc., ISBN: 9780596514013
ANSWERS
Exercise – 1
1. True
2. non-procedural and declarative
3. indexes
4. primary and foreign
5. structure
Exercise – 2
1. client layer
2. MySQL Server layer
3. Storage engine layer
Exercise – 3
1. c) MySQL Workbench
2. b) Allows direct interaction with database and supports efficient batch processing and
automation
Exercise – 4
1. Opens a new connection to the MySQL database
2. d) Set the default database for the connection.
3. The main use is to perform a query on the MySQL database.
4. mysqli_fetch_object() fetches a result row as an object, while mysqli_fetch_array() fetches a
result row as an associative array, a numeric array, or both
5. rows
6. mysqli_affected_rows()
Exercise – 5
1. establish connection to a mysql database using object oriented approach
97
2. mysqli::query()
Exercise – 6
1. Building forms from queries in MySQL involves creating an interface for users to input data,
sending that data to a server, and then using SQL queries to interact with a MySQL database.
2. The action attribute specifies the PHP script to which the form data should be submitted when
the user clicks the submit button. The method attribute defines the HTTP method used when
sending the form data to the server.
98
Answer for Try your assignment
<?php
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
// Create a connection to MySQL
$conn = mysqli_connect($servername, $username, $password);
// Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create the 'test' database
$sqlCreateDatabase = "CREATE DATABASE test";
if (mysqli_query($conn, $sqlCreateDatabase)) {
echo "Database 'test' created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn) . "<br>";
}
mysqli_select_db($conn, "test"); // Select the 'test' database
// Create the 'student' table
$sqlCreateTable = "CREATE TABLE student (
rollno INT PRIMARY KEY,
marks1 INT,
marks2 INT,
marks3 INT,
marks4 INT,
marks5 INT
)";
if (mysqli_query($conn, $sqlCreateTable)) {
echo "Table 'student' created successfully<br>";
} else { echo "Error creating table: " . mysqli_error($conn) . "<br>"; }
mysqli_close($conn); // Close the database connection
?>
Objective
99
contents of web pages. Further, the lesson provides the readers, the basics of AJAX and how it
makes use of XMLHttpRquest for asynchronous communication.
Learning outcomes
Upon completion of this lesson, students will get
a comprehensive understanding of fundamental concepts in JavaScript and Asynchronous
JavaScript and XML (AJAX).
an insight into how JavaScript utilizes the Document Object Model (DOM) to manipulate the
contents of web pages.
the basics of AJAX, understanding its mechanism of asynchronous communication using
XMLHttpRequest.
the knowledge of applying JavaScript and AJAX techniques for effective web page
manipulation and enhanced user experience.
Why don’t we listen to the chat between Vicky and Nandhu on dynamic web pages
Vicky: "Why does our webpage look so static and dull?"
Nandhu: "That's because HTML gives only structure, but JavaScript adds interaction! It
uses the DOM to dynamically update and change content."
Vicky: "But what about slow page loading?"
Nandhu: "That's where AJAX comes in; it fetches data in the background, making our
page faster and more responsive!"
5.0 Introduction
JavaScript and Asynchronous JavaScript and XML (AJAX) are the two essential technologies
for developing web applications. JavaScript, a client-side, versatile programming language,
used to develop interactive of web pages. It uses Document Object Model (DOM) for content
manipulation. Furthermore, the lesson extends its focus to AJAX which is more powerful in
creating dynamic web pages with its asynchronous communication. The lesson discusses how
AJAX employs XMLHttpRequest to enable seamless communication between web pages and
servers. AJAX enhances the user experience through efficient asynchronous communication.
5.1 JavaScript
JavaScript is a platform independent, object-oriented, client-side scripting language, used to
create interactive web contents. It adds interaction and behaviour to HTML. Java Script was
100
developed by Brendan Eich in Netscape in 1995. The first code of Javascript was named as
‘Mocha’. Later the language was named as ‘LiveScript’. Again, in 1995, it was renamed as
‘JavaScript. It is light weight language enables dynamic interactivity in HTML. It is an
interpreted language. It is case sensitive. The primary intention and utmost purpose of
JavaScript are to enhance the interactivity and functionality of web pages
Typical use cases of JavaScript include
(i) client-side validation
(ii) displaying date and time
(iii) displaying pop-up windows and
(iv) displaying drop-down menus
Javascript is embedded in HTML using <script> tags.
A simple JavaScript is shown below
<script>
[Link](“hello world”);
</script>
5.2 Document Object Model (DOM)
The Document Object Model (DOM) is a cross-platform and language-independent interface that
treats an HTML or XML document as a tree structure, wherein each node is
an object representing a part of the document.
The DOM represents a document with a logical tree.
Each branch of the tree ends in a node, and each node contains objects.
DOM methods allow programmatic access to the tree;
With DOM, one can modify style or content of a document.
Nodes can have event handlers (also known as event listeners). Once an event is triggered,
the event handlers get executed.
Since, in DOM, every element is a node, there are different types of nodes such as the following.
A document is a document node.
All HTML elements are element nodes.
All HTML attributes are attribute nodes.
Text inserted into HTML elements are text nodes.
Comments are comment nodes.
101
Here is a simple HTML document and its corresponding DOM tree (See Figure 5.1).
<html>
<body>
<h1> DOM tree example</h1>
<p> Fruits give the essential minerals and vitamins </p>
<p> Examples are apple, orange, and mango </p>
</body>
</html>
<html>
<body>
As mentioned above, the DOM represents the tree structure of an HTML (or XML) document.
However, it is more than just a tree-like structure; it serves as an Application Programming
Interface (API) that provides a way for scripts to interact with the structure, style, and content of
a document. The DOM API consists of various objects and collections that represent different
elements of the document. In addition, the API offers a range of methods to access and
manipulate the document
5.2.1 Objects and specific HTML collections in DOM API
The commonly used objects and specific HTML collections of DOM API are given in Table 5.1
and Table 5.2 respectively
Table 5.1 Important objects of DOM API
102
Object Description
window This object represents the browser window
history This object keeps track of the sites visited by the browser user.
navigator This object contains information about the user’s web browser
event This object represents an event, such as a user's interaction with a webpage
Collections Descriptions
all Refers to all elements in the document.
The DOM API provides various methods for accessing and manipulating different contents of
HTML documents. Some commonly used methods, along with brief explanations are given in
Table 5.3
Table 5.3 Commonly used methods of DOM API for accessing elements
Method Description and example
103
getElementById(id) Retrieves an element by its id attribute.
var a = [Link]("myid");
getElementsByClassName(classname) Retrieves a collection of elements with the specified
class name.
var a = [Link]("a");
getElementsByTagName(tagName) Retrieves a collection of elements with the specified tag
name.
var ps = [Link]("p");
querySelector(selector) Retrieves the first element that matches the specified
CSS selector
var a = [Link](".example");
querySelectorAll(selector) Retrieves a NodeList containing all elements that match
the specified CSS selector
var a = [Link](".example");
Table 5.4 Commonly used methods of DOM API for manipulating contents
Method Description and example
104
element is accessed using getElementById() method. The text is modified using innerHTML
property
Exercise – 1
1. What does the getElementById method do in the DOM?
a) Retrieves an element by its class name
b) Retrieves an element by its tag name
c) Retrieves an element by its ID
d) Retrieves all elements in the document
2. Which method is used to select all elements with a specific class name?
a) querySelector
b) getElementsByClassName
c) getElementsByTagName
d) querySelectorAll
3. What property is used to get or set the HTML content of an element?
a) innerText
b) textContent
c) innerHTML
d) outerHTML
4. parentElement.__________ is used to add the newchild ‘child’ to the parentElement
105
The potential of AJAX lies with its asynchronous communication with the server which makes
the user interface highly responsive. The working of AJAX is shown in Fig. 5.2
XMLHttpRequest
Object
106
<html>
<body> This is where data
would be updated
asynchronously
<div id="data-container">
<p>Data will be displayed here.</p>
</div>
new XMLHttpRequest object
<script>
var xhr = new XMLHttpRequest(); ‘true’ indicates
[Link]('GET', '[Link] true); that the request is
asynchronous
[Link] = function() {
if ([Link] === 4 && [Link] === 200) {
var responseData = [Link]([Link]);
[Link]('data-container').innerHTML = responseData;
}
};
[Link](); The onreadystatechange
</script> event is set to a callback
function, which is triggered
whenever the state of the
</body>
request changes
</html>
Asynchronous request is
sent to the server
A typical example using XMLHttpRequest is shown in the self-explanatory diagram in Fig. 5.3.
Fig. 5.3 An example using XMLHttpRequest
As in the example, the asynchronous request is realized with the help of XMLHttpRequest.
It is configured for an asynchronous GET request to a [Link]/example endpoint.
107
At first, An XMLHttpRequest object (xhr) is created.
In the open method, the third parameter is set to true, indicating that the request should be
asynchronous.
This means that the browser will not wait for the request to complete before continuing to
execute the rest of the code. Instead, it will asynchronously handle the request in the
background.
If the request is successful (status 200), the JSON response is parsed, and the webpage is
updated with the received data.
Thus, the asynchronous approach ensures that the webpage remains responsive, and the user
can continue interacting with the content while the request is being processed
Example – 2
1. XMLHttpRequest operates by making __________ requests to a server.
2. Say True or False: XMLHttpRequest can be used to fetch data from a server without
refreshing the entire page.
3. Which method is used to create an instance of XMLHttpRequest?
4. Which method is used to initialize an HTTP request with the XMLHttpRequest object?
5. Fill in the blank: The onreadystatechange event is triggered when the __________ state
of the XMLHttpRequest object changes.
6. What property holds the response data obtained from the server?
Let’s watch the conversation between Vicky and Nandhu on AJAX validation
Vicky: "Why use AJAX for form validation on our website?"
Nandhu: "With AJAX, we can check user input without reloading the whole page."
Vicky: "But why is that important?"
Nandhu: "It makes the user experience smoother by providing instant feedback without
causing page refreshes."
108
the server and reloading the page, Ajax allows you to send a request to the server in the
background, validate the data, and receive a response without disrupting the user experience.
To explain the validation using AJAX, the following example is illustrated.
HTML and JavaScript portion (client side code)
<html> <head>
<script src="[Link]
<script>
$(document).ready(function() {
$('#ageForm').submit(function(event) {
[Link]();
// Get the age value
var age = $('#age').val();
// Validate the age using Ajax
$.ajax({
type: 'POST',
url: '[Link]', // Specify the path to your PHP validation script
data: { age: age },
success: function(response) {
// Update the error message based on the validation result
$('#ageError').text(response);
}
});
});
});
</script>
</head>
<body>
<form id="ageForm">
<label for="age">Age:</label>
<input type="text" id="age" name="age">
<span id="ageError" style="color: red;"></span>
<br>
<input type="submit" value="Submit">
</form>
</body></html>
In the above example, a single input field, ‘age’ is validated for whether it is numeric and its
value exists in the range 18 to 60. There are three portions of the code, (i) HTML form code
109
which takes the age input from the user (ii) JavaScript which captures the value of age when
form is submitted. It sends and AJAX request to server-side script ([Link]) which
performs the validation and generates an appropriate response. Also, it handles the response
from the server (iii) [Link] script which performs the validation check. It validates the
age on the server. It checks whether the age field is numeric and its value ranges from 18 to 60.
In the above script, the line $(document).ready(function() { ensures that JavaScript code
inside the function is executed only when the document is fully loaded.
The line $('#ageForm').submit(function(event) { targets the form with the ID ageForm and
attaches a submit event handler.
The line [Link](); prevents the default form submission behavior, which
would cause a page reload. The form data will be submitted asynchronously using Ajax.
The line var age = $('#age').val(); retrieves the value entered in the input field with the ID
age and stores it in the age variable.
An AJAX request is initiated using $.ajax(). It is a POST request to the [Link]
script, and the data being sent includes the age value obtained from the form. The success
callback function is executed when the Ajax request is successful. It takes the response from
the server (which could be an error message) and updates the content of the element with the
ID ageError with this response.
The [Link] is shown below
<?php
// Get the age from the Ajax request
$age = $_POST['age'];
// Validate that the age is a number between 18 and 60
if (is_numeric($age) && $age >= 18 && $age <= 60)
{ echo ''; // Empty string means no error}
else
{ echo 'Age must be a number between 18 and 60';}
?>
110
5.5 Uploading a file using AJAX
File uploading using AJAX enhances web interactivity by allowing users to submit files without
the need for page refreshes. Below are the steps that outline the straightforward process of
implementing AJAX file uploads on a web page.
Step – 1 creation of HTML form with an input of type “file” which allows the users to select a
file to upload. Further the form should contain a button with click event to trigger the file upload
process using AJAX. The form also must include an area to display the result of file upload
HTML form
<html >
<head>
<script src="[Link]
<script src="[Link]"></script>
</head>
<body>
<h2>File Upload</h2>
<form id="fileForm" enctype="multipart/form-data" method="post">
<input type="file" id="fileInput" name="fileInput">
<button type="button" onclick="uploadFile()">Upload</button>
<div id="fileResult"></div>
</form>
</body>
</html>
Step – 2 Create a JavaScript function (uploadFile) that gets triggered when the upload button is
clicked. Inside the function, jQuery is used to create a FormData object which appends the
selected file and sends it to the server using an AJAX POST request. Also, the script updates the
result area with the server's response.
function uploadFile() {
var formData = new FormData();
[Link]('file', $('#fileInput')[0].files[0]);
$.ajax({
type: 'POST',
111
url: '[Link]', // Specify the path to your PHP file handling the upload
data: formData,
contentType: false,
processData: false,
success: function(response) {
$('#fileResult').text(response);
}
});
}
Step – 3 Create a PHP script that receives the file from the AJAX request. It moves the file to a
particular directory and sends a response to client
<?php
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File is valid, and was successfully uploaded.';
} else {
echo 'Error uploading the file.';
}
} else {
echo 'Error: ' . $_FILES['file']['error'];
}
?>
5.6 Displaying a table in AJAX
Displaying data in a table using AJAX involves fetching information from a server
asynchronously and updating the HTML content dynamically without requiring a full page
reload.
The following is a simple example which shows how the data can be dynamically loaded into a
table
Initially HTML table structure has been created using the following code
112
<body>
<table id="myTable" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Table body content will be populated dynamically -->
</tbody>
</table>
</body>
Secondly a javascript has been created to fetch data and populate the data into the table. Also, in
the provided example, testdata has been used to show the population (kindly note in real
scenario, instead of the test data, the data from the server has been loaded)
<script>
const testData = [
{ id: 1, name: 'John Doe', email: 'john@[Link]' },
{ id: 2, name: 'Jane Doe', email: 'jane@[Link]' },
{ id: 3, name: 'Bob Smith', email: 'bob@[Link]' }
];
function fetchData() {
// Simulate fetching data from an API
// For school-level understanding, use a placeholder URL
fetch('[Link]
.then(response => [Link]())
.then(data => {
// After data is fetched, call a function to populate the table
populateTable(testData);
113
})
.catch(error => [Link]('Error fetching data:', error));
}
function populateTable(data) {
const tableBody = [Link]('tableBody');
[Link] = ''; // Clear existing table rows
// Loop through the data and create table rows
[Link](item => {
const row = [Link]('tr');
[Link] = `
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
`;
[Link](row);
});
}
// Call the fetchData function to initialize the table
fetchData();
</script>
5.7 Building Pagination using PHP and AJAX
Pagination is a technique used on websites to break down a large set of data into smaller pieces
of data or pages. It is commonly applied to long lists or tables of data to improve user experience
by presenting information in a more organized manner. Each page typically contains a specific
number of items, and users can navigate through pages to view different parts of the dataset.
In the context of pagination, PHP is used to retrieve data from a database or another data
source and prepare it for display. Also, PHP is used to generate the HTML structure for
displaying the data and pagination controls. The data is displayed in a table or list, and
pagination links or buttons are added below.
114
AJAX is used to enable dynamic updates without requiring a full page reload. When a user
clicks on a pagination link, AJAX sends a request to the server, and only the necessary data
is updated without refreshing the entire page.
JavaScript is used to handle AJAX requests and update the content on the page. Event
listeners are set up to detect when a user clicks on a pagination link, triggering an AJAX
request to fetch the corresponding data.
The client side and server side coding corresponding to building pagination using PHP and
AJAX are given below
Client code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="[Link]
</head>
<body>
<div id="results"></div>
<div id="pagination"></div>
<script>
function loadPage(page) {
$.ajax({
url: 'fetch_data.php',
type: 'GET',
data: { page: page },
success: function(response) {
$('#results').html(response);
}
});
}
$(document).ready(function() {
loadPage(1); // Load initial page
});
115
</script>
</body>
</html>
The above code includes jQuery library for AJAX functionality. It contains a results div to
display the fetched data. Further, it has a pagination div where one can add pagination controls.
The javascript defines a function loadPage that uses AJAX to fetch data from the server
(fetch_data.php). It calls loadPage(1) on document ready to load the initial page.
Server side code
<?php
// Fetch data based on the page number
$perPage = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $perPage;
// Replace this with your actual data fetching logic
$data = range($start + 1, $start + $perPage);
// Display fetched data
foreach ($data as $item) {
echo "<div>$item</div>";
}
?>
Example – 3
1. Why is AJAX validation beneficial for user experience?
a) It reduces server load
b) It provides instant feedback
c) It enhances browser compatibility
d) It simplifies HTML structure
2. The __________ attribute is used in HTML forms to enable file uploads.
3. The contentType: ________ option in an AJAX request is set to ensure proper
handling of form data.
116
5.8 GitHub
Nandhu: "Yeah, it's that platform for storing code or something, right?"
Vicky: "Exactly! It's not just a code repository; It's a centralized platform where we store
our code, manage changes, and collaborate on projects."
Nandhu: "Why not just use a shared folder or something? What's the big deal?"
Vicky: "Well, GitHub goes beyond that. GitHub allows multiple people to work on the
same codebase simultaneously.
Nandhu: "Hmm, sounds convenient. But what if someone messes up the code?"
Vicky: "Good question! GitHub has 'version control.' It tracks changes in the code, so if
something goes wrong, we can easily roll back to a previous, working version.
Nandhu: "Interesting. How do you coordinate work with your team, though?"
Vicky: "GitHub has 'branches' to work on specific features or fixes. Each person can go
with his own branch, and when he finished, he has to create a 'pull request.' to check out
his changes. Then, the development team review the code and merge it into the main
project. Code review and merging are collaborative efforts, and the responsibility for
these tasks is often shared among team members according to the project's guidelines.
The GitHub makes collaboration smoother, code safer, and projects more manageable.
Plus, it's the heart of the open-source community. So, are you ready to give it a try?"
Nandhu: "Definitely!
117
GitHub is a web-based platform for version control and collaborative software development. It
facilitates efficient teamwork by allowing multiple developers to work on the same codebase
simultaneously. GitHub provides features such as version tracking, issue management, and pull
requests, making it a central hub for code collaboration, project organization, and open-source
development. The core components of GitHub are shown in the following Fig.
GitHub
On the left side of the graph, a series of connected nodes is present. Each node is a commit.
Corresponding to each commit, there are three entries. The first entry is the unique identifier
for the commit. Second entry is the commit message and third entry is the author name.
The graph must be read vertically from bottom to top.
Also, in the graph, one can see that one commit may be connected by line to another commit.
For example, the commit having unique id, ‘master’ is connected to the commit having id,
‘111a67e’. Also, note that the commit message for 111a67e is ‘Add text parser’. The
commit message conveys that the commit 111a67e is actually includes the change, ‘add text
parser’ with the previous commit, master.
119
In this way, a reader can understand the changes taken place in a project with a holistic
view
120
Edit button – Github provides edit button to perform changes in the file
Include the commit message - After making your edits, scroll down to find a section for
adding a commit message
Commit – ultimately one can commit the change in the same branch or in a new branch
5.8.3 Collaborating on pull requests
Collaborating on pull requests (PRs) in GitHub involves proposing and reviewing changes to a
repository. Users initiate a pull request after making modifications in their own forked
repository, describing the purpose and context of the changes. Assigned reviewers assess the
proposed modifications, providing feedback and ensuring adherence to coding standards. The
pull request serves as a collaborative space for discussion and iteration, with the option to
address feedback and make further improvements. Continuous integration tools may run
automated tests, and the results are often displayed in the pull request. Upon approval, changes
can be merged into the main branch, triggering potential automatic deployments. The
collaborative nature of pull requests facilitates effective communication, code quality assurance,
and a streamlined integration process in collaborative development workflows.
5.8.4 Creating a repository
One can easily create a new repository on GitHub using the following steps
Github account – At first one has to create Github account
Navigating dashboard – After creating account, one can navigate the dashboard, explore
projects and manage profile
New repository button – One can create a new repository using New button and then by
selecting ‘Repository’ option
The newly created repository would be configured and initialized with an README file,
describing about the repository
121
Exercise – 4
1. What is the primary purpose of a GitHub repository?
a) Storing coffee recipes
b) Version control and collaboration
c) Virtual gaming
d) Social networking
2. What does a "fork" mean in GitHub?
a) Eating utensil
b) Copying a repository to your GitHub account
c) A dance move
d) A bug in the code
3. Which Git command is used to commit changes to a local repository?
a) git fetch
b) git commit
c) git dance
d) git sleep
4. Pull requests in GitHub are used to propose and review changes before they
are merged into the __________.
5. GitHub uses the term "Issues" to track and manage __________ within a
repository.
5.8.5 Configuring a repository
Configuring a repository on GitHub involves setting up various parameters to manage the project
effectively. Here is a brief overview:
Repository Settings - After creating a repository, one must navigate to its settings.
Branch Protection – one can configure branch protection rules to safeguard important
branches from unauthorized changes. Enabling required reviews and status checks can ensure
that changes meet specific criteria before being merged.
122
Collaborators and Teams – One can add individuals or teams who should have access to the
repository in the "Collaborators" section, add. Further, one define his/her permissions to
control who can push changes, merge pull requests, or administer the repository.
Webhooks and Integrations – one can set up webhooks to automate workflows and integrate
with external services.
Repository Topics and Descriptions – Also, one can enhance discoverability by adding
relevant topics to his/her repository.
Summary
This lesson presented the power of AJAX for dynamic web content, allowing seamless data
retrieval without page reloads. It had discussed the uploading files using AJAX, mastering the art
of presenting data in organized tables. GitHub became coding haven for open source project
development. The lesson provided a quick tour on the core components of GitHub, GitGraph
visualizations along with steps involved in creating and configuring a repository.
Intext Questions
1. List out the features of JavaScript
2. What is the purpose of DOM?
3. Explain the objects and HTML specific collections present in DOM API.
4. Describe in detail, various methods available in DOM for accessing and manipulating the
HTML contents
5. Describe in detail about AJAX validation
6. What is the need for AJAX validation?
7. Do we really need the uploading facility using AJAX? Explain uploading file using AJAX.
8. What is the primary purpose of GitHub?
9. Describe the core component of GitHub in detail
10. What is use of Git Graph? Write a note about Git Graph
123
Higher order thinking – try for your mini project
Imagine you are building a weather website, and you want to display the current
temperature for a city without refreshing the entire page.
Explain how you can use AJAX and the XMLHttpRequest object to achieve this
asynchronous communication with the server. Provide a step-by-step explanation of the
process, including the key functions and events involved.
References
1. [Link]
accessed on 23.11.2023
2. [Link] accessed on 02.12.2023
3. [Link]
4. [Link]
ANSWERS
Exercise – 1
1. c) Retrieves an element by its ID
2. b) getElementsByClassName
3. c) innerHTML
4. appendChild(child)
Exercise – 2
1. asynchronous
2. True
3. new XMLHttpRequest();
4. open
5. ready
6. responseText or response
Exercise – 3
1. b) It provides instant feedback
2. enctype="multipart/form-data"
3. false
Exercise – 4
1. b) Version control and collaboration
124
2. b) Copying a repository to your GitHub account
3. b) git commit
4. main brance
5. tasks
125