PHP Nep Notes
PHP Nep Notes
Words of Concern
Point to be As Allan Bloom has said "Education is the movement from darkness to light".
Through this handbook, I have tried to illuminate what might otherwise appear as black
boxes to some. In doing so, I have used references from several other authors to synthesize
or simplify or elaborate information. This is not possible without omitting details that I deem
trivial while dilating the data that I consider relevant to topic. Every effort has been made to
avoid errors. In spite of this, some errors might have crept in. Any errors or discrepancies
noted maybe brought to my notice which I shall rectify in my next revision.
This handbook is solely for educational purpose and is not for sale. This handbook shall not
be reproduced or distributed or used for commercial purposes in any form or by any means.
Thanks,
Deeksha.V.
Interface College of Computer Applications (ICCA)
Davangere
Bibliography
1. PHP & MySQL for Dynamic web sites- Fourth Edition By Larry Ullman.
2. Learning PHP,MySQL and Javascript By Robin Nixon -O “REILLY publications.
3. Programming PHP By Rasmus Lerdorf,Kevin Tatroe,Peter MacIntyre.
4. SAMS Teach Yourself PHP in 24 hours,Author:Matt Zandstra,Sams Publishing.
Syllabus:
Course Code: DSC17
Course Title: PHP and MySQL
Credits - 04
Sem - VI
Hours- 52
Formative Assessment Marks: 40
Summative Assessment Marks: 60
Duration of SEA/Exam: 02 hrs.
Course Outcomes (COs): After the successful completion of the course, the student will be
able to:
1.Design dynamic and interactive web pages and websites.
2.Run PHP scripts on the server and retrieve results.
3.Handle databases like MySQL using PHP in websites.
Contents 52 Hrs
Unit I 10 Hrs
Introduction: -Introduction to PHP, History and Features of PHP, Installation &
Configuration of PHP, Embedding PHP code in your web pages, Understanding PHP,HTML
and white space, Writing comments in PHP, Sending data to the web browser, Data types in
PHP, Keywords in PHP, using variables, constants in PHP, expressions in PHP, operators in
PHP.
Unit II 12 Hrs
Programming with PHP: - Conditional statements: If, if-else, switch, The? Operator,
Looping statements: While Loop, do-while Loop, for Loop, Arrays in PHP: Introduction-What
is array?, Creating Arrays, Accessing array elements, Types of arrays: Indexed v/s
Associative arrays, Multidimensional arrays, Creating array, Accessing array, Manipulating
Arrays, Displaying array, using array functions, Including and requiring files-use of Include()
and Require(),Implicit and Explicit casting in PHP.
Unit IV 10 Hrs
Class & objects in PHP: - What is class & object, Creating and accessing a class & object,
Object properties, Object methods, Overloading, inheritance, constructor and destructor,
form handling: Creating HTML form, Handling HTML form data in PHP.
Unit V 10 Hrs
Database Handling using PHP with MySQL: - Introduction to MySQL: Database terms,
Data types, Accessing MySQL- Using MySQL Client and using PHP MyAdmin, MySQL
commands, using PHP with MySQL: PHP MySQL functions, connecting to MySQL and
selecting the database, Executing simple Queries, Retrieving query results, Counting
returned records, Updating records with PHP.
Unit 1
Introduction to PHP
PHP
• PHP is the Web development language written by and for Web developers.
• PHP stands for PHP: Hypertext Preprocessor. The product was originally named
Personal Home Page Tools.
• PHP is a server-side scripting language, which can be embedded in HTML or used
as a standalone binary.
History:
1. Creation (1994): Rasmus Lerdorf created PHP as a set of Perl scripts for his
personal use to manage his online resume and track web visits.
2. PHP/FI (1995): Lerdorf extended his scripts and released the PHP/FI (Personal
Home Page/Forms Interpreter) version, which added the ability to create simple
dynamic web applications.
3. PHP 3 (1998): The first formal version of PHP was released, introducing a more
robust and modular architecture.
4. PHP 4 (2000): This version brought significant improvements and features such as
better support for object-oriented programming (OOP) and introduced the Zend
Engine, which greatly enhanced PHP's performance.
5. PHP 5 (2004): PHP 5 further improved support for OOP with features like interfaces
and exceptions. It also introduced the Standard PHP Library (SPL) and enhanced
XML support.
6. PHP 6 (Development halted): Work began on PHP 6 to add native Unicode support.
However, due to technical challenges and delays, the project was eventually
abandoned.
7. PHP 7 (2015): PHP 7 was a major release known for its significant performance
improvements, with up to twice the speed of PHP 5. PHP 7 also introduced many
new features and enhancements, including scalar type declarations, return type
declarations, anonymous classes, and more.
8. PHP 8 (2020): PHP 8 brought several new features and improvements, including
Just-In-Time (JIT) compilation for improved performance, union types, named
arguments, attributes, and more.
Features:
1. Server-Side Scripting: PHP is primarily used for server-side scripting, meaning that it
runs on a web server and processes code before sending the output to the client's
browser. This allows for dynamic content generation.
2. Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.
3. Ease of Use: PHP syntax is relatively easy to learn and understand, especially for
beginners. It is similar to C, Java, and Perl, making it accessible to developers from
various programming backgrounds.
4. Wide Compatibility: PHP is compatible with most web servers and operating
systems, including Linux, Unix, Windows, macOS, and more. It also supports a wide
range of databases, including MySQL, PostgreSQL, SQLite, and Oracle.
5. Support for Various Protocols: PHP supports various network protocols, such as
HTTP, SMTP, LDAP, IMAP, POP3, and more, making it versatile for web
development and beyond.
6. Extensive Library Support: PHP has a vast ecosystem of libraries and frameworks,
such as Laravel, Symfony, CodeIgniter, and WordPress, which help developers build
web applications more efficiently.
7. Embeddable: PHP code can be embedded directly into HTML, allowing developers to
mix dynamic content with static content seamlessly.
8. Open Source: PHP is open-source software, meaning it is freely available for anyone
to use, modify, and distribute.
9. Active Community: PHP has a large and active community of developers who
contribute to its development, provide support, and share resources and knowledge.
1. Downloading XAMPP
• Visit the official XAMPP download
page: https://www.apachefriends.org/download.html
• Select the download corresponding to your operating system (Windows, macOS, or
Linux).
• Choose either the installer or the archive (.zip) file.
2. Installing XAMPP
• For Installer: Double-click the downloaded .exe file.
• Follow the on-screen instructions in the XAMPP Setup Wizard.
• Choose an installation directory (it's recommended to keep the default suggested
location, typically C:\xampp).
4 INTERFACE
8884768574)
BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
PHP
• You can optionally select which components to install (Apache, MySQL, PHP, etc.).
By default, all components are selected.
• Click "Next" and follow any further prompts until the installation is complete.
4. Verifying Installation
• Open a web browser and navigate to http://localhost. You should see the default
XAMPP welcome page if everything is functioning correctly.
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1>Today's Date</h1>
<p>
<?php
// PHP code to display today's date
echo "Today is " . date("Y-m-d") . ".";
?>
</p>
</body>
</html>
index.php
<!DOCTYPE html>
<html>
<head>
<title>External PHP Example</title>
</head>
<body>
<?php include 'external.php'; ?>
<p><?php echo $message; ?></p>
</body>
</html>
3. Examples:
• In PHP scripts, developers can format code across multiple lines without affecting
functionality.
<?php
echo "ICCA"; // Whitespaces can be used better readability
?>
• In HTML source, different formatting styles will render the same page, as HTML is
mostly white space insensitive.
<html>
<head><title>HTML Code</title></head>
<body>
<?php echo "<h1>Welcome to ICCA</h1>";?>
</body>
</html>
• Multi-line comments: Use the /* and */ symbols to enclose your comment text. This
allows comments to span multiple lines.
/*
This is a multi-line comment.
It can explain a complex code block
or provide additional information.
*/
var_dump( $arrayele[1] );
?>
Example
<?php
$a = 25; //Integer
$b = 12.25; //Float
$c = $a-$b;
$d = "ICCA";//String
echo "$c<br/>";
echo "$d";
?>
Output
Note:
1) Resource types are often returned by functions that deal with external applications or files
2) The NULL type is reserved for variables that have been declared but no value has been
assigned to them.
Example
<?php
$testing = 5;
echo "is an integer? ".is_int($testing) ."<br/>";
$testing = "five";
echo "is a string? ".is_string($testing) ."<br/>";
$testing = 5.024;
echo "is a double? ".is_double($testing) ."<br/>";
$testing = true;
echo "is boolean? ".is_bool($testing) ."<br/>";
$testing = array('apple', 'orange', 'pear');
echo "is an array? ".is_array($testing) ."<br/>";
echo "is numeric? ".is_numeric($testing) ."<br/>";
echo "is a resource? ".is_resource($testing) ."<br/>";
echo "is an array? ".is_array($testing) ."<br/>";
?>
Output
Keywords in PHP
• PHP has a set of keywords that are reserved words which cannot be used as
function names, class names or method names.
Variables in PHP
A variable is a special container, which “holds” a value, such as a number, string,
object, array, or a Boolean.
Example
<?php
$a = 25; //Integer
$b = 12.25; //Float
$c = $a-$b;
$d = "ICCA";//String
echo "$c<br/>";
echo "$d";
?>
1. Global Variables
• In addition to the rules for naming variables, there are rules regarding the
availability of variables.
• In general, the assigned value of a variable is present only within the function
or script where it resides.
• For example, if you have scriptA.php that holds a variable called $name with
a value of joe, and you want to create scriptB.php that also uses a $name
variable, you can assign to that second $name variable a value of john
without affecting the variable in scriptA.php.
• The value of the $name variable is local to each script, and the assigned
values are independent of each other.
• However, you can also define the $name variable as global within a script or
function. If the $name variable is defined as a global variable in both
scriptA.php and scriptB.php, and these scripts are connected to each other
(that is, one script calls the other or includes the other), there will be just one
value for the now- shared $name variable.
2. Superglobal Variables
• In addition to global variables of your own creation, PHP has several
predefined variables called superglobals.
• These variables are always present, and their values are available to all your
scripts. Each of the following superglobals is actually an array of other
variables:
o $_GET contains any variables provided to a script through the GET
method.
Constant in PHP
• The value does not change after the execution of the program is called constant.
• You must use PHP’s built-in define() function to create a constant, which
subsequently cannot be changed unless you specifically define() it again.
• To use the define() function, place the name of the constant and the value you want
to give it within parentheses and separated by a comma:
Example
<?php
define("THE_YEAR", "2024");
echo "It is the year ".THE_YEAR;
?>
Output
• The define() function can also accept a third Boolean argument that determines
whether the constant name should be case sensitive.
• By default, constant names are case sensitive.
• However, by passing true to the define() function, you can change this behavior. you
could access the “THE_YEAR” constant without worrying about case:
eg: echo the_year;
echo ThE_YeAr;
echo THE_YEAR;
constant() function
• As indicated by the name, this function will return the value of the constant.
• This is useful when you want to retrieve value of a constant, but you do not know its
name, i.e. It is stored in a variable or returned by a function.
Example
<?php
define("THE_YEAR", "2024");
echo "It is the year ".THE_YEAR."<br/>";
echo constant("THE_YEAR");
?>
Output
Predefined Constants
• PHP automatically provides some built-in constants for you.
• For example, the constant FILE returns the name of the file that the PHP engine is
currently reading. The constant LINE returns the current line number of the file.
Expression
• An expression is any combination of functions, values, and operators that resolves to
a value
(OR)
• The combination of operands with an operator to produce a result is called an
expression
Eg: a + b; Where: a & b are operands + is a operator
Operators in PHP
• Operators are symbols used to manipulate data stored in variables, to make it
possible to use one or more values to produce a new value, or to check the validity of
data to determine the next step in a condition, and so forth
4. Comparison Operators
o Comparison operators perform comparative tests using their operands and
return the Boolean value true if the test is successful or false if the test fails.
Example:
(1) $x=5; (2) $x=5;
$y=5.0; $y=5.0;
$x= = $y // returns true $x= = = $y // returns false
++$x; $x is incremented by 1
- -$x ; $x is decremented by 1
6. Logical Operator
o Logical operators test combinations of Boolean values.
o For example, the or operator, which is indicated by two pipe characters (||) or
simply the word or, returns the Boolean value
Operator precedence
• Operator precedence determines the grouping of terms in an expression.
• This affects how an expression is evaluated.
• Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator
Example
<?php
$num1 = 100;
$num2 = 200;
$num3 = 90;
if(( $num1 > $num2 ) && ($num1>$num3))
{
echo "$num1 is greater";
}
elseif( $num2 > $num3 )
{
echo"$num2 is greater";
}
else
{
echo"$num3 is greater";
}
?>
Output
Conditional Statements
It is common for scripts to evaluate conditions and change their behavior accordingly.
The if Statement
• The if statement is a way of controlling the execution of a statement that follows it.
• The if statement evaluates an expression found between parentheses.
• If this expression results in a true value, the statement is executed. Otherwise, the
statement is skipped entirely
Example
<?php
$var = "ICCA";
if ($var == "ICCA")
{
echo "Welcome to ICCA" ;
}
?>
Output
Example
<?php
$var = "DVG";
if ($var == "ICCA")
16 INTERFACE BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
8884768574)
PHP
{
echo "Welcome to ICCA" ;
}
else
{
echo "Welcome to Davangere";
}
?>
Output
Example
<?php
$var = "Interface";
if ($var == "ICCA")
{
echo "Welcome to ICCA" ;
}
elseif($var == "Interface")
{
echo "Welcome to Interface" ;
}
else
{
echo "Welcome to Davangere";
}
?>
Output
Example
<?php
$var = "ICCA";
switch ($var)
{
case "ICCA":
echo "Welcome to ICCA";
break;
case "ISAT":
echo "Welcome to ISAT";
break;
default:
echo "Welcome to Interface";
break;
}
?>
Output
Example
<?php
$num = 10;
$result = ($num % 2 == 0) ? "Even" : "Odd";
echo "The number $num is $result.";
?>
Output
Looping Statement
• Loops in PHP are used to execute the same block of code a specified number of
times. PHP supports following four loop types.
o for − loops through a block of code a specified number of times.
o while − loops through a block of code if and as long as a specified condition is
true.
o do...while − loops through a block of code once, and then repeats the loop as
long as a special condition is true.
o foreach − loops through a block of code for each element in an array.
While loop
• The while statement will execute a block of code if and as long as a test expression
is true.
• If the test expression is true then the code block will be executed.
• After the code has executed the test expression will again be evaluated and the loop
will continue until the test expression is found to be false.
Example
<?php
$i = 0;
$num = 50;
Example
<?php
$i = 0;
$num = 0;
do {
$i++;
echo "$i ";
} while( $i < 10 );
echo "<br/> Loop stopped at i = $i";
?>
Output
Example
<?php
for ($counter=1; $counter<=5; $counter++)
{
echo "$counter * 2 = ". ($counter * 2)."<br/>";
}
?>
Output
Example
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
Output
Break Statement
• Both while and for statements incorporates a built in test expression with which you
can end a loop.
• The break statement enables you to break out of a loop based on the results of
additional tests.
Example
<?php
for($a=0;$a<=10;$a++)
{
if($a==5)
{
break;
}
else
{
echo "$a ";
}
}
?>
Output
Continue Statement
• The continue statement ends execution of the current iteration but doesn’t cause the
loop as a whole to end.
Example
<?php
for($a=0;$a<=10;$a++)
{
if($a==5)
{
continue;
}
else
{
echo "$a ";
}
}
?>
Output
Arrays
• Array is collection; it might be homogenous or heterogeneous in nature.
• Accessing array elements is carried by index and index starts from 0 and its max
length is maxsize – 1.
• Memory allocation of the array is mostly sequential.
Creating array
• You can create an array using either the array() function or the array operator
[ ].
• The array() function is usually used when you want to create a new array and
populate it with more than one element, all in one fell swoop.
• The array operator is often used when you want to create a new array with
just one element at the outset, or when you want to add to an existing array
element.
Accessing Array
• Array can be accessed using index and foreach statement
Example
<?php
$clgname = array("I", "C", "C", "A");
$clgname[] = "Interface";
echo $clgname[2]."<br/>";
echo $clgname[0]."<br/>";
echo $clgname[4]."<br/>";
?>
Output
2. Associative Arrays
• The associative arrays are very similar to numeric arrays in term of functionality
but they are different in terms of their index.
• Associative array will have their index as string so that you can establish a strong
association between key and values.
Note 1: Don't keep associative array inside double quote while printing otherwise it would
not return any value.
Note 2: The only difference between an associative array and a numerically indexed array is
the key name.
3. Multidimensional Array
• The first two types of arrays hold strings and integers, whereas this third type
holds other arrays.
• In a multi-dimensional array each element in the main array can also be an array.
• And each element in the sub-array can be an array, and so on.
Example 1:-
<?php
$characters = array(
array("name" => "Rama","age" => 20, "Course" =>"BCA" ),
array("name" => "Shama","age" => 20,"Course" => "Bsc" ),
array("name" => "Bhama","age" => 20,"Course" => "BBA")
);
echo $characters[0]['name'];
?>
Output
Example 2
<?php
$characters = array(
array(1,2,3,4,5 ),
array( 6,7,8,9,10),
array(11,12,13)
);
echo "characters[0][1]= ".$characters[0][1]."<br/>";
echo "characters[1][1]= ".$characters[1][1]."<br/>";
?>
Output
Example 3
<?php
$characters = array(
"Rama" => array("age" => 20, "Course" =>"BCA" ),
"Shama" => array("age" => 20,"Course" => "Bsc" ),
"Bhama" => array("age" => 20,"Course" => "BBA")
);
echo "The Course taken by Rama is ".$characters['Rama']['Course'];
?>
Output
1. count() and sizeof( ): - Each of these functions counts the number of elements in an
array; they are aliases of each other.
Example:-
<?php
$clgname = array("I", "C", "C", "A");
echo "Displaying the number of elements in an array using count function =
".count($clgname);
echo "<br/>Displaying the number of elements in an array using sixzeof
function = ".sizeof($clgname);
?>
Output
2. array_push(): - This function adds one or more elements to the end of an existing
array.
Syntax
int array_push(array &$array, mixed $value1 [, mixed $value2, ...])
26 INTERFACE
8884768574)
BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
PHP
Where,
• array &$array: This is a reference to the array to which you want to add elements.
The ampersand (&) ensures the changes are reflected in the original array.
• mixed $value1, [, mixed $value2, ...]: These represent the values you want to
append to the end of the array. You can specify one or more values to be
pushed.
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before adding new elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
array_push($clgname,"Davangere");
echo "<br/>Array elements after adding new elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
Output
3. array_pop(): - This function removes the last element of an existing array and returns
the remaining elements of an array.
Syntax
mixed array_pop(array &$array)
Where,
• array &$array: This is a reference to the array from which you want to remove the
last element. The ampersand (&) ensures the modification happens on the
original array itself.
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before deleting last elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
array_pop($clgname);
echo "<br/>Array elements after deleting last elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before adding new elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
array_unshift($clgname,"Welcome","to");
echo "<br/>Array elements after adding new elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
5. array_shift(): -This function removes (and returns) the first element of an existing
array.
Syntax
mixed array_shift(array &$array)
Where,
• array &$array: This is a reference to the array you want to remove the first
element from. The ampersand (&) ensures that the modification happens on the
original array itself.
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before deleting last elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
array_shift($clgname);
echo "<br/>Array elements after deleting last elements<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
7. array_keys(): -This function returns an array containing all the key names within a
given array.
Syntax
array array_keys(array $input, mixed $filter_value = null, bool $strict =
false)
Where,
• array $input: The array from which you want to extract the keys.
• mixed $filter_value (optional): If provided, it filters the keys based on their values
(using strict comparison by default).
• bool $strict (optional): When set to TRUE, uses strict comparison during value
filtering with $filter_value
Example
<?php
$character = array("name" => "Rama", "clg" =>"ICCA","age" => 20,
"course" => "BCA");
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
$keyarray = array_keys($character);
foreach ($keyarray as $key)
{
echo "<br/>". $key ."";
}
?>
Output
8. array_values(): -This function returns an array containing all the values within a given
array.
Syntax
array array_values(array $input)
Where,
array $input: This is the array from which you want to extract the values.
Example
<?php
$character = array("name" => "Rama", "clg" =>"ICCA","age" => 20,
"course" => "BCA");
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
$keyarray = array_values($character);
foreach ($keyarray as $key)
{
echo "<br/>". $key ."";
}
?>
Output
9. shuffle(): - This function randomizes the elements of a given array. The syntax of this
function is simply as follows:
Syntax
bool shuffle(array &$array)
Where,
• array &$array: This is a reference to the array you want to shuffle. The
ampersand (&) ensures the shuffling happens on the original array.
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before Shuffle<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
shuffle($clgname);
echo "<br/>Array elements after Shuffle<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
10. reset(): - This function rewinds the pointer to the beginning of an array
Syntax
mixed reset(array &$array)
Where,
• array &$array: This is a reference to the array for which you want to reset the
internal pointer. The ampersand (&) ensures changes are reflected in the
original array.
11. sort(): Sorts an array in ascending order based on the values. It reassigns numerical
keys, starting from 0.
Syntax
sort(array &$array, int $sort_flags = SORT_REGULAR)
Where,
• array &$array: This is a reference to the associative array you want to sort. The
ampersand (&) ensures the sorting happens on the original array.
• int $sort_flags = SORT_REGULAR (optional): This parameter specifies how the
keys in the array should be compared during sorting. It can be set to the same
constants as the asort function:
o SORT_REGULAR (default): Sorts keys using a normal comparison
(equivalent to comparing two strings).
o SORT_NUMERIC: Sorts keys numerically (assuming they are valid
numbers).
o SORT_STRING: Sorts keys as strings.
o SORT_LOCALE_STRING: Sorts keys as strings, considering the current
locale.
o SORT_NATURAL: Sorts keys as strings using a "natural order" algorithm
that handles numbers correctly.
o SORT_FLAG_CASE: Can be combined with other flags to control case-
sensitivity (e.g., SORT_NUMERIC | SORT_FLAG_CASE for case-
insensitive numeric sort).
Example
<?php
$clgname = array("I", "C", "C", "A");
echo "Array elements before Sorting<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
sort($clgname);
echo "<br/>Array elements after Sorting<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
12. rsort(): - Sorts an array in descending order based on the values. Similar to sort(), it
reassigns numerical keys.
Syntax
rsort(array &$array, int $sort_flags = SORT_REGULAR)
Where,
• array &$array: This is a reference to the associative array you want to sort. The
ampersand (&) ensures the sorting happens on the original array.
• int $sort_flags = SORT_REGULAR (optional): This parameter specifies how the
keys in the array should be compared during sorting. It can be set to the same
constants as the asort function:
o SORT_REGULAR (default): Sorts keys using a normal comparison
(equivalent to comparing two strings).
o SORT_NUMERIC: Sorts keys numerically (assuming they are valid
numbers).
o SORT_STRING: Sorts keys as strings.
o SORT_LOCALE_STRING: Sorts keys as strings, considering the current
locale.
o SORT_NATURAL: Sorts keys as strings using a "natural order" algorithm
that handles numbers correctly.
o SORT_FLAG_CASE: Can be combined with other flags to control case-
sensitivity (e.g., SORT_NUMERIC | SORT_FLAG_CASE for case-
insensitive numeric sort).
Example
<?php
$clgname = array(5,100,20,48,26,30,78);
echo "Array elements before Sorting<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
rsort($clgname);
echo "<br/>Array elements after Sorting<br/>";
foreach($clgname as $name)
{
echo "$name ";
}
?>
Output
13. ksort(): - Sorts an array in ascending order based on the keys. It maintains the
original association between keys and values.
Syntax
ksort(array &$array, int $sort_flags = SORT_REGULAR)
Where,
• array &$array: This is a reference to the associative array you want to sort. The
ampersand (&) ensures the sorting happens on the original array.
• int $sort_flags = SORT_REGULAR (optional): This parameter specifies how the
keys in the array should be compared during sorting. It can be set to the same
constants as the asort function:
o SORT_REGULAR (default): Sorts keys using a normal comparison
(equivalent to comparing two strings).
o SORT_NUMERIC: Sorts keys numerically (assuming they are valid
numbers).
o SORT_STRING: Sorts keys as strings.
o SORT_LOCALE_STRING: Sorts keys as strings, considering the current
locale.
o SORT_NATURAL: Sorts keys as strings using a "natural order" algorithm
that handles numbers correctly.
o SORT_FLAG_CASE: Can be combined with other flags to control case-
sensitivity (e.g., SORT_NUMERIC | SORT_FLAG_CASE for case-
insensitive numeric sort).
Example
<?php
$character = array("name" => "Rama", "clg" =>"ICCA","age" => 20,
"course" => "BCA");
echo "Before sorting<br/>";
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
ksort($character);
echo "</br>";
echo "After sorting<br/>";
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
?>
Output
Note: - krsort(): Sorts an array in descending order based on the keys. It maintains the
original association between keys and values.
14. asort(): - Sorts an associative array in ascending order based on the values. It
maintains the original association between keys and values.
Syntax
asort(array &$array, int $sort_flags = SORT_REGULAR)
Where,
• array &$array: This is a reference to the associative array you want to sort. The
ampersand (&) ensures the sorting happens on the original array.
• int $sort_flags = SORT_REGULAR (optional): This parameter specifies how the
values in the array should be compared during sorting. It can be set to one of the
following constants:
o SORT_REGULAR (default): Sorts elements using a normal comparison
(equivalent to comparing two strings).
o SORT_NUMERIC: Sorts elements numerically.
o SORT_STRING: Sorts elements as strings.
o SORT_LOCALE_STRING: Sorts elements as strings, considering the current
locale.
o SORT_NATURAL: Sorts elements as strings using a "natural order" algorithm
that handles numbers correctly.
o SORT_FLAG_CASE: Can be combined with other flags to control case-
sensitivity (e.g., SORT_NUMERIC | SORT_FLAG_CASE for case-insensitive
numeric sort).
Example
<?php
$character = array("name" => "Rama", "clg" =>"ICCA","age" => 20,
"course" => "BCA");
echo "Before sorting<br/>";
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
asort($character);
echo "</br>";
echo "After sorting<br/>";
foreach ($character as $key => $value)
{
echo "". $key ."->". $value ."<br/>";
}
?>
Output
Note: - arsort(): Sorts an associative array in descending order based on the values. It
maintains the original association between keys and values.
}
} else
{
echo "<br>Invalid position specified. The position should be between 0 and " .
count($original_array);
}
?>
Output
• require():
o If the specified file is not found or there's an error including the file, it throws
a fatal error (E_COMPILE_ERROR) and halts the script's execution entirely.
This ensures your script doesn't proceed with potentially broken code due to
a missing file.
• include():
o On the other hand, if include() encounters an error including the file, it only
generates a warning (E_WARNING) and the script execution continues. This
might lead to unexpected behaviour if the missing file contains essential code.
Example:-
includedfile.php
<?php
function factorial($number) {
if ($number < 0) {
throw new Exception("Factorial is not defined for negative numbers.");
}
$factorial = 1;
for ($i = 1; $i <= $number; $i++) {
$factorial *= $i;
}
return $factorial;
}
?>
originalfile.php
<?php
include("includedfile.php");
echo"The factorial of 5 is: -".factorial(5);
?>
Output:
Example
includedfile.php
<?php
function factorial($number) {
if ($number < 0) {
throw new Exception("Factorial is not defined for negative numbers.");
}
$factorial = 1;
for ($i = 1; $i <= $number; $i++) {
$factorial *= $i;
}
return $factorial;
}
?>
originalfile.php
<?php
require("includedfile.php");
echo"The factorial of 6 is: -".factorial(6);
?>
Output
• This is the process of changing a variable's data type to another data type
automatically or manually. This process is known as typecasting and it can be done
in two ways.
o Implicit Casting (Automatic)
o Explicit Casting (Manual)
Implicit Casting
• Implicit data typecasting can be done by PHP automatically.
• For example the divide operation by two integer numbers then in this case result
might be either an integer or float number.
<?php
$num = 4;
$num1 = 8;
echo $num/$num1;
?>
Output
Explicit Casting
• Explicit casting can be customized by the user. Users can change variable types
from one data type to another data type with the help of PHP methods.
Example
<?php
$a = 3.14;
echo "is $a a double?".is_double($a)."<br/>";
$b = (string) $a;
echo "is $b a string?".is_string($b)."<br/>";
$b = (integer) $a;
echo "is $b a integer?".is_integer($b)."<br/>";
$b = (boolean) $a;
echo "is $b a boolean?".is_bool($b)."<br/>";
?>
Output
Where:--
settype():-- it is a function
$variabletochange:-- name of the variable being converted.
new type:-- Type of the variable to which you want to convert
Example
<?php
$a = 3.14;
echo "is $a a double?".is_double($a)."<br/>";
settype($a, 'string');
echo "is $a a string?".is_string($a)."<br/>";
settype($a, 'Integer');
echo "is $a a integer?".is_integer($a)."<br/>";
?>
Output
Function
• A function is a self-contained block of code that can be called by your scripts.
• When called, the function’s code is executed and performs a particular task.
• Functions are of two types
o Built-in functions
o User defined functions
Built-in functions
• PHP has hundreds of built-in function.
• Example :- strtoupper(), abs(), count(), sizeoff() etc…
• This function calls the strtoupper( ) function, passing it the string “Hello Web!!”.
• The function then goes about its business of changing the contents of the string to
upper case letters.
• A function call consists of the function name followed by parentheses, between those
parentheses we can pass the information.
• A piece of information passed to a function is called arguments.
Defining a Function
Where,
function:- keyword
function_name : - name of the function
arg:- arguments
Output
Example
<?php
function return_eg($a,$b) //Formal parameters
{
return $a + $b;
}
echo return_eg(5, 7); //Actual parameters
?>
Local Variable
• A variable declared in a function is considered local; that is, it can be referenced
solely in that function.
• Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function.
Example
<?php
$x = 4;
function assignx ()
{
$x = 0;
print "<h2>\$x inside function is $x. </h2>";
}
assignx();
print "<h1>\$x outside of function is $x. </h2>";
?>
Output
Global Variable
• In PHP, variables declared outside of functions are not directly available within
functions by default. These variables are considered local to the global scope and
separate from the function's local scope.
• So, in order to access and modify the global variable within function, use
the global keyword followed by the variable name.
Example
<?php
$x=4;
function eg()
{
global $x;
$x++;
echo "$x";
}
eg();
echo "<br/> $x <br/>";
?>
Output
Recursion
• Recursion is a technique where a function calls itself directly or indirectly. This
creates a loop where the function keeps executing until a certain condition is met, at
which point it stops calling itself and the loop unwinds.
Example
<?php
function factorial($n) {
if ($n < 0) {
return -1; // Handle negative input (optional)
} else if ($n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return $n * factorial($n - 1); // Recursive call
}
}
$number = 5;
$result = factorial($number);
echo "$number factorial is: $result";
?>
Output
Library functions
• PHP offers a rich set of built-in library functions that cover various functionalities,
saving you time and effort from writing code from scratch. Here's an overview of
some key categories:
1. String Manipulation:
• strlen(): Get the length of a string.
• strpos(): Find the first occurrence of a substring within a string.
• str_replace(): Replace occurrences of a substring with another string.
• strtolower(): Convert a string to lowercase.
• strtoupper(): Convert a string to uppercase.
• trim(): Remove whitespace from the beginning and end of a string.
2. Arrays:
• count(): Get the number of elements in an array.
• array_push(): Add one or more elements to the end of an array.
• array_pop(): Remove and return the last element from an array.
• array_merge(): Merge two or more arrays.
• in_array(): Check if a value exists in an array.
• array_key_exists(): Check if a specific key exists in an array.
Example 2
<?php
$date_array = getdate(1710150937);
foreach($date_array as $key => $value)
{
echo "<br/>". $key ."--". $value ."";
}
?>
Output
Example
<?php
$time = time(); //stores the exact timestamp to use in this script
echo date("m/d/y G:i:s e", $time);
echo "<br/>";
echo "Today is";
echo date("jS \of F Y, \a\\t g:ia \i\\n e", $time);
?>
Output
Strings in PHP
• There are four primary ways to create strings in PHP:
1. Single-quoted strings: This is the simplest and most common way. Enclose the text
within single quotes (''). Any single quotes within the string must be escaped with a
backslash (').
Example:-
$message = 'ICCA';
echo $message;
2. Double-quoted strings: Similar to single-quoted strings, but double quotes ("") are
used. However, double-quoted strings allow variable interpolation and interpretation
of escape sequences.
Example:-
$message = 'ICCA';
echo $message;
3. Heredoc: Heredoc is a way to create strings in PHP that span multiple lines and may
contain variables without using string concatenation. It's particularly useful for
creating large blocks of text or HTML markup within PHP code
Syntax
<?php
$str = <<<IDENTIFIER
Multiple lines of strings
IDENTIFIER;
?>
• Three opening heredoc delimiters (<<<) followed by an identifier (chosen name
without quotes) initiate the heredoc syntax.
• The actual string content goes on the next lines, indented at the same level
(indentation is not strictly required, but improves readability).
• The string ends with the same identifier on a new line, but without any leading or
trailing whitespace. This closes the heredoc block.
• Heredoc does interpret variable values within the string content when using double
quotes or single quotes.
Example
<?php
$name = "ICCA";
$message = <<<MESSAGE
Hello,Welcome to "$name".
MESSAGE;
echo $message;
?>
Output
4. Nowdoc
• Nowdoc is similar to Heredoc but behaves like a single-quoted string. It does not
parse variables or special characters within the string.
Syntax
<?php
$str = <<<'IDENTIFIER'
Multiple lines of strings
IDENTIFIER;
?>
• Start with three less-than signs (<<<) followed by a single quote (').
• Follow it with an identifier (a word consisting of letters, numbers, and
underscores). This identifier is unique within the script and acts as a marker for
the nowdoc string.
• Type your multi-line string content. You can indent the content for better
readability, but the indentation level must be consistent throughout the string.
• To terminate the nowdoc string, type the same identifier again on a new line,
followed by a semicolon (;)
• Unlike heredoc, nowdoc strings don't allow variable interpolation
using ${variable_name} syntax. Any variable names within the string will be
treated literally.
Example
<?php
$name = "ICCA";
$message = <<<'MESSAGE'
Hello,Welcome to "$name".
MESSAGE;
echo $message;
?>
Output
String Functions
There are number of built- in string functions some are explained below
1. strtoupper()
• To get an uppercase version of a string, use the strtoupper( ) function. This
function requires only the string that you want to convert and returns the
converted string:
Example
<?php
$var = "interface college of computer applications";
echo "Before converting to uppercase:--".$var;
echo "<br/>After converting to uppercase:- ".strtoupper($var);
?>
Output
2. strtolower
• To convert a string to lowercase characters, use the strtolower( ) function.
Example
<?php
$var = "INTERFACE COLLEGE OF COMPUTER APPLICATIONS ";
echo "Before converting to lowercase:--".$var;
echo "<br/>After converting to lowercase:- ".strtolower($var);
?>
Output
3. ucwords
• The ucwords( ) function makes the first letter of every word in a string
uppercase.
Example
<?php
$var = "interface college of computer application ";
echo $var;
echo "<br/>".ucwords($var);
?>
Output
4. ucfirst()
• The ucfirst( ) function capitalizes only the first letter in a string
Example
<?php
$var = "interface college of computer application ";
echo $var;
echo "<br/>".ucfirst($var);
?>
Output
5. trim()
• The trim( ) function shaves any whitespace characters, including newlines,
tabs, and spaces, from both the start and end of a string.
• It accepts the string to modify and returns the cleaned-up version.
Syntax
trim($string, $charlist)
Example
<?php
$text = "\t\texample for trim function";
echo "<pre>$text</pre>";
$text1 = trim($text);
echo "<pre>$text1</pre>";
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Output
Note: - The <pre> tag in HTML stands for "preformatted text." It's used to display text
exactly as it appears in the HTML code, preserving spaces, line breaks, and other
formatting.
6. ltrim()
PHP provides the ltrim() function to strip whitespace from the beginning of a string.
Example
<?php
7. rtrim()
• rtrim() removes whitespace only at the end of the string argument:
Example
<?php
$text = "\t\t example for rtrim function ";
echo "<pre>$text<pre>";
$text = rtrim($text);
echo "<pre>$text</pre>";
?>
Output
8. substr()
• Extracts a portion of the string based on starting index and length.
Syntax
substr($str, start, length)
Where,
• $str: The original string from which you want to extract the substring.
• $start: (Integer) The starting position of the substring within the original string.
Indexing starts from 0, so the first character is at position 0.
• $length (Optional, Integer): The length of the substring to extract. If omitted,
the function extracts characters from the $start position till the end of the
string.
Example
<?php
$text = "INTERFACE COLLEGE OF COMPUTER APPLICATIONS";
$substr = substr($text,0,9);
$substr1 = substr($text,10,7);
echo $substr;
echo " $substr1";
?>
Output
9. str_repeat()
Repeats a string a specified number of times.
Syntax
str_repeat($str, multiplier)
Where,
• $str: The string you want to repeat.
• $multiplier: (Integer) The number of times you want to repeat the string.
Example
<?php
$symbol = "*";
for($i=1;$i<=5;$i++)
{
$asterisk_line = str_repeat($symbol,$i);
echo $asterisk_line."<br/>";
}
?>
Output
10. substr()
• The substr() function returns a string based on the start index and length of
the characters.
• This function requires two arguments: a source string and the starting index.
• Using these arguments, the function returns all the characters from the
starting index to the end of the string.
• You can also (optionally) provide a third argument—an integer representing
the length of the string you want to return.
• If this third argument is present, substr( ) returns only that number of
characters, from the start index.
Example
<?php
$sentence = "Interface college of computer applications";
echo substr($sentence,0)."<br/>";
echo substr($sentence,3,2)."<br/>";
echo substr($sentence,-2);
?>
Output
11. substr_replace()
• The substr_replace() function works similarly to the substr() function, except it
enables you to replace the portion of the string that you extract.
• The function requires three arguments: the string to transform, the text to add
to it, and the starting index; it also accepts an optional length argument.
• The substr_replace( ) function finds the portion of a string specified by the
starting index and length arguments, replaces this portion with the string
provided, and returns the entire transformed string.
Example
<?php
$sentence = "Interface college of computer applications";
echo "text before replacing : ".$sentence."</br>";
echo "text after replacing string :
".substr_replace($sentence,"INTERFACE",0,9);
?>
Output
12. str_replace()
• The str_replace( ) function is used to replace all instances of a given string within
another string.
• It requires three arguments: the search string, the replacement string, and the
master string. The function returns the transformed string.
Example
<?php
$sentence = "Interface college!!,interface,Interface";
echo "text before replacing : ".$sentence."</br>";
echo "text after replacing string :
".str_replace("Interface","INTERFACE",$sentence);
?>
Output
13. strcmp()
• The strcmp() function in PHP is used for string comparison. It takes two
strings as arguments and returns an integer value indicating the relationship
between them.
Syntax
strcmp($str1, $str2)
Return values,
• 0: If the two strings are identical.
• Negative value (< 0): If the first string ($str1) is less than the second string
($str2). This happens when the first difference between corresponding
characters in the strings has a lower ASCII value in $str1 compared to $str2.
• Positive value (> 0): If the first string ($str1) is greater than the second string
($str2). This occurs when the first difference between corresponding
characters has a higher ASCII value in $str1 compared to $str2.
Example
<?php
$str1 = "apple";
$str2 = "banana";
$str3 = "Apple";
14. strlen()
• strlen($str): Returns the length of the string (number of characters).
Example
<?php
$text = "Interface College";
echo "Number of characters in a string=".strlen($text);
?>
Output
15. str_word_count()
• Counts the number of words or returns an array of words based on the
specified type.
Syntax
str_word_count(string $string [, int $format = 0 [, string $charlist ]] )
Where,
• $string: The input string to be analyzed.
• $format (optional): Specifies the return value. It can take three possible
values:
o 0: Returns the total number of words found in the string (integer).
o 1: Returns an array containing all the individual words identified within
the string.
o 2: Returns an associative array where:
o The key is the numeric position (0-based index) of the word within the
original string.
o The value is the actual word itself.
o $charlist (optional): A list of additional characters to consider as
words.
Example
<?php
$sentence = "Interface college of computer applications !!!";
$total_words = str_word_count($sentence);
echo "Total words: $total_words <br/>";
$words_array = str_word_count($sentence, 1, ",!");
print_r($words_array);
echo "<br/>";
$words_with_positions = str_word_count($sentence, 2);
print_r($words_with_positions);
?>
Output
2. Define a Object
• 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 are created using the new keyword.
Syntax
class ClassName
{
//code
}
ObjectName = new ClassName();
Example
class BankAccount
{
//code
}
acc1 = new BankAccount();
• To access a property, you use the object operator (->)
<?php
$object->property;
Object Properties
• Properties are essentially variables associated with an object. They represent the
data or state of the object.
• You define properties within a class definition.
• Access modifiers (public, private, protected) control access to properties from outside
the class.
1. Directly Inside the Class: Assign default values directly inside the class definition
using property declarations
class DavangereUniversity
{
public $clgname = "ICCA";
public $course = "BCA";
}
2. Directly Accessing Properties: We can also directly assign values to properties after
the object has been created
class DavangereUniversity
{
public $clgname;
public $course;
59 INTERFACE
8884768574)
BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
PHP
}
$college = new DavangereUniversity();
$college->clgname = "ICCA";
$college->course = "BCA";
3. Using Setter Methods: We can define setter methods within the class to assign
values to properties after the object has been created:
class DavangereUniversity
{
public $clgname;
public $course;
public function setclgname($clgname)
{
$this->clgname = $clgname;
}
public function setcourse($course)
{
$this->course = $course;
}
}
$college = new DavangereUniversity();
$college->setclgname("ICCA");
$college->setcourse("BCA");
4. Inside the Constructor: We can assign values to properties when creating an object
by passing them as arguments to the constructor:
class DavangereUniversity
{
public $clgname;
public $course;
public function __construct($clgname, $course)
{
$this->clgname = $clgname;
$this->course = $course;
}
}
$college = new DavangereUniversity("ICCA","BCA");
Object Methods
• Methods are functions defined within a class that represent the actions or behaviors
an object can perform.
• They can access and manipulate the object's properties, as well as interact with
other objects.
• Similar to properties, methods can also have access modifiers (public, private,
protected).
Example
<?php
class DavangereUniversity
{
public $clgname; // Object Properties
public $course;
public function display() // Object Methods
{
echo "I am studing $this->course in $this->clgname College";
}
}
$college = new DavangereUniversity();
$college->clgname = "ICCA";
$college->course = "BCA";
$college ->display();
Output
function display($clg)
{
$this->clgname = $clg;
echo "Welcome to, $this->clgname !!";
}
}
$obj1 = new College();
$obj1->display("Interface College");
Output
Overloading
• Unlike some other object-oriented languages, PHP doesn't support overloading in the
traditional sense.
• Traditional overloading refers to having multiple methods with the same name but
different argument lists.
• However, PHP offers a mechanism to achieve similar behavior using magic methods.
These are special methods that allow you to define custom logic for how PHP
interacts with object properties and methods that aren't explicitly declared within the
class.
Property Overloading
• Property overloading in PHP refers to the ability to create dynamic properties for an
object at runtime.
• PHP utilizes special methods prefixed and suffixed with double underscores (__) for
property overloading.
• The key methods involved are:
o __get($propertyName): This method is invoked whenever you try to access a
property that isn't explicitly declared within the class. You can define custom
logic here to handle property retrieval or perform actions based on the
accessed property.
o __set($propertyName, $value): This method is called when you attempt to set
a value to a non-existent property. It allows you to define how the object
should handle setting properties that aren't formally defined.
Example
<?php
class MyClass {
private $data = [];
Method Overloading
• In PHP, method overloading allows you to dynamically create methods that are not
explicitly declared within a class.
• These dynamic methods are processed using magic methods
• Here’s how method overloading works in PHP:
o Using __call() and __callStatic():
▪ When an inaccessible or undefined method is called within a class
instance or statically, PHP automatically invokes the magic
methods __call() and __callStatic().
▪ These methods allow you to handle method calls that haven’t been
explicitly defined in your class.
Example
<?php
class example
{
public function __call($methodName, $arguments)
{
$method = [$this, $methodName.count($arguments)];
if (is_callable($method))
{
return call_user_func_array($method, $arguments);
}
}
private function multiply1($argument1)
{
echo $argument1;
}
private function multiply2($argument1, $argument2)
{
echo $argument1 * $argument2;
}
}
$class = new example;
echo $class->multiply(2)."<br>";
$class->multiply(5, 7);
?>
Output
Inheritance
• Inheritance in PHP is a fundamental concept in object-oriented programming
(OOP) that allows classes to inherit properties and methods from other classes.
• Inheritance is implemented using the extends keyword in PHP, where a child class
extends a parent class.
• The child class inherits all the non-private properties and methods defined in the
parent class, enabling it to utilize and build upon the functionality provided by the
parent class.
• By inheriting from a parent class, the child class gains access to the public and
protected properties and methods defined in the parent class.
• It can use them as if they were defined within the child class itself.
• This promotes code reusability, as common functionality can be encapsulated in a
base class and inherited by multiple derived classes.
• In addition to inheriting properties and methods, the child class has the flexibility to
override or extend inherited methods by providing its implementation.
• This allows the child class to customize the behavior inherited from the parent class
and adapt it to its specific needs.
1. Single Inheritance:
• Single inheritance refers to a scenario where a class inherits from a single parent
class.
• In PHP, single inheritance is the most commonly used type of inheritance.
• It allows a class to inherit the properties and methods of one parent class, also
known as the superclass or base class.
Syntax:
class ParentClass
{
//code;
}
class ChildClass extends ParentClass
{
// code;
}
Example
<?php
class College
{
function display()
{
echo "Welcome to ICCA";
}
}
class ChildClass extends College
{
function display1()
{
echo ", Happy Learning!!";
}
}
$obj1 = new ChildClass();
$obj1->display();
$obj1-> display1();
Output
2. Multilevel Inheritance:
• Multilevel inheritance involves a class inheriting from a parent class, and that parent
class itself inheriting from another parent class.
• This forms a hierarchy or chain of classes.
• In PHP, multilevel inheritance allows classes to inherit properties and methods from
multiple levels up the class hierarchy.
Syntax
class ParentClass
{
//code;
}
class ChildClass extends ParentClass
{
//code;
}
class GrandChild extends ChildClass
{
//code;
}
Example
class Animal
{
public function eat()
{
echo "Animal is eating.<br>";
}
}
class Dog extends Animal
{
public function bark()
{
echo "Dog is barking.<br>";
}
}
class GermanShepherd extends Dog
{
public function guard()
{
echo "German Shepherd is guarding.<br>";
}
}
$germanShepherd = new GermanShepherd();
$germanShepherd->eat();
$germanShepherd->bark();
$germanShepherd->guard();
Output
3. Hierarchical Inheritance
• In hierarchical inheritance, more than one child class is inherited from the single
parent class. The hierarchy forms a tree-like structure.
Syntax
class ParentClass
{
//code;
}
class ChildClass1 extends ParentClass
{
//code;
}
class ChildClass2 extends ParentClass
{
//code;
}
Example
<?php
class Fruit
{
public function fruit()
{
echo "This is Fruit class<br>";
}
}
class Apple extends Fruit
{
public function apple()
{
echo "This is Apple class<br>";
echo "" .$this->fruit();
}
}
class Mango extends Fruit
{
public function mango()
{
echo "This is Mango class<br>";
echo "".$this->fruit();
}
}
$a = new Apple();
$a->apple();
$m = new Mango();
$m->mango();
?>
Output
4. Multiple Inheritance
• In multiple inheritance, there can be more than one parent class for a single child
class.
• Multiple inheritance is not supported in PHP, but we can achieve this by
using interfaces or traits.
• Traits are similar to classes, but they cannot be instantiated on their own. Instead,
they are intended to be used by classes to incorporate their methods.
Example
<?php
// trait 1
trait t1
{
public function sayhello()
{
echo "Hello! Welcome to";
}
}
// trait 2
trait t2
{
public function sayfor()
{
echo" ICCA.";
}
}
class Child
{
//Include trait in class
use t1;
use t2;
public function fun()
{
echo "\nHappy Learning!";
}
}
$obj = new Child();
$obj->sayhello();
$obj->sayfor();
$obj->fun();
?>
Output
Overriding
• Overriding refers to the ability to define a method in a child class that is already
defined in the parent class.
69 INTERFACE BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
8884768574)
PHP
• This allows the child class to provide its own implementation of the method,
potentially with different behavior or functionality, while still maintaining the same
method signature (name and parameters) as the parent class.
Example
<?php
class ParentClass
{
public function sayHello()
{
echo "Hello from ParentClass!<br>";
}
}
class ChildClass extends ParentClass
{
public function sayHello()
{
echo "Hello from ChildClass!<br>";
}
}
$parent = new ParentClass();
$child = new ChildClass();
$parent->sayHello();
$child->sayHello();
?>
Output
• In this example, both ParentClass and ChildClass have a method named sayHello().
When you call sayHello() on an instance of ParentClass, it executes the method
defined in ParentClass. However, when you call sayHello() on an instance of
ChildClass, it executes the method defined in ChildClass, overriding the behavior of
the parent class method.
Constructor
• A constructor in PHP is a special method within a class that gets automatically
executed when an object of the class is created.
• It allows initialization tasks, such as setting default property values or performing
necessary setups, to be performed seamlessly during object instantiation.
Types of Constructor
1. Default Constructor:
• This is the most basic type and is automatically provided by PHP if you don't define
any constructor in your class.
• It has no arguments (public function __construct() {}) and performs no specific
initialization tasks.
• While it works, it's often recommended to define a custom constructor to ensure
proper object initialization.
Example 1
<?php
class College
{
}
$obj1 = new College();
?>
Example 2
<?php
class College
{
public function __construct()
{
echo "Welcome to ICCA";
}
}
$obj1 = new College();
?>
Output
Note:- In older versions of PHP (before PHP 5), the way classes were constructed differed
from the more modern approach shown in the previous code example. In the old-style
constructors, you would define a method with the same name as the class itself, and this
method would serve as the constructor.
2. Parameterized Constructor:
• This is the most commonly used type. It's explicitly defined within a class using
the __construct method and accepts arguments (parameters).
• These arguments allow you to pass values during object creation, which are then
used to set the object's properties or perform other initialization tasks.
• Parameterized constructors provide more control over the initial state of your objects.
Example
<?php
class College
{
public $clgname;
public function __construct($clgname)
{
$this->clgname = $clgname;
echo "Welcome to $this->clgname ";
}
public function display()
{
echo "<br>Welcome to $this->clgname ";
}
}
$obj1 = new College("ICCA");
$obj1->display();
71 INTERFACE BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
8884768574)
PHP
?>
Output
3. Copy Constructor
• PHP doesn't have built-in support for copy constructors, which are used to create
a new object as a copy of an existing one.
• However, you can achieve similar functionality using a few different approaches:
i. Cloning:
• The clone keyword is the most common way to create a copy of an object in
PHP. It performs a shallow copy, meaning it copies the values of the object's
properties but references remain references. This can be problematic if the object
holds references to other objects.
Example
<?php
class MyClass
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
// Method to get the value
public function getValue()
{
return $this->value;
}
}
class CopyClass
{
// Method to create a copy of MyClass instance
public static function copyInstance(MyClass $original) {
return clone $original;
}
}
// Creating an instance of MyClass
$instance1 = new MyClass(10);
// Creating a copy using the CopyClass method
$instance2 = CopyClass::copyInstance($instance1);
// Checking the values of both instances
echo "Instance 1 Value: " . $instance1->getValue() . "<br>";
echo "Instance 2 Value: " . $instance2->getValue() . "<br>";
Output
• Instead of a dedicated copy constructor, you can define a static method that
takes an existing object as input and returns a new object with the same
properties. This approach offers more flexibility and can be used for various
object creation scenarios.
Example
<?php
class MyClass
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
// Method to get the value
public function getValue()
{
return $this->value;
}
}
class CopyClass
{
// Method to create a copy of MyClass instance
public static function copyInstance(MyClass $original)
{
return new MyClass($original->getValue());
}
}
// Creating an instance of MyClass
$instance1 = new MyClass(10);
// Creating a copy using the CopyClass method
$instance2 = CopyClass::copyInstance($instance1);
// Checking the values of both instances
echo "Instance 1 Value: " . $instance1->getValue() . "<br>";
echo "Instance 2 Value: " . $instance2->getValue() . "<br>";
?>
• MyClass is the original class, and CopyClass contains the method copyInstance()
which is responsible for creating a copy of MyClass instances.
Output
Constructor in inheritance
• Unlike methods, a child class constructor doesn't automatically call the parent class
constructor.
• If the child class defines its own constructor, it needs to explicitly call the parent
constructor using parent::__construct($arguments) syntax within its own constructor
body.
• This ensures the parent class's initialization logic is executed before the child class's
specific initialization.
Example
<?php
class ParentClass
{
Destructor
• In PHP, a destructor is a special method that gets called when an object is
destroyed or when the script finishes execution. The destructor method is defined
using the __destruct() magic method..
Example
<?php
class MyClass
{
public function __construct()
{
echo "Constructor called.<br>";
}
public function __destruct()
{
echo "Destructor called.<br>";
}
}
// Create an instance of MyClass
$obj = new MyClass();
// Object is destroyed when script finishes execution
echo "Script finished.<br>";
?>
Output
Form Handling:
2. Form Elements:
• Within the <form> tag, you place various form elements to collect user input. Here
are some common elements:
• <input>: This versatile element comes with various subtypes for different input
types:
o text: Single-line text input (e.g., name, email).
o password: Hidden character password input.
o radio: Radio buttons for mutually exclusive choices (e.g., gender).
o checkbox: Checkboxes for multiple selections (e.g., interests).
o submit: Creates a submit button to trigger form submission.
o Many more subtypes exist for specific data types like dates, numbers,
URLs, etc.
• <textarea>: Creates a multi-line text input field for longer messages or
descriptions.
• <select>: Defines a dropdown menu for selecting options from a list.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GET Form Example</title>
</head>
<body>
<h1>Enter your name and age</h1>
<form action="partB2.php" method="post">
<table>
<tr><td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"required><br></td></tr>
<tr><td><label for="age">Age:</label></td>
<td><input type="number" id="age" name="age" min="1" required></td></tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
Example
eg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GET Form Example</title>
</head>
<body>
<h1>Enter your name and age</h1>
<form action="eg.php" method="post">
<table>
<tr><td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"required><br></td></tr>
<tr><td><label for="age">Age:</label></td>
<td><input type="number" id="age" name="age" min="1" required></td></tr>
</table>
Introduction to MySQL :
Database terms
• Data: - Data is a collection of a distinct small unit of information. It can be used in a
variety of forms like text, numbers, media, bytes, etc. it can be stored in pieces of
paper or electronic memory, etc.
• Database (DB): A collection of structured data organized for easy access, storage,
and manipulation.
• Database Management System (DBMS): Software that allows users to interact with
databases, including creating, managing, and querying data. Popular DBMS
examples include MySQL, PostgreSQL, Oracle Database, Microsoft SQL Server, and
SQLite.
• Schema: The overall structure of a database, defining tables, columns, data types,
keys, and relationships between them.
• Table: A fundamental unit of organization within a database, similar to a spreadsheet
with rows and columns. Each table stores data about a specific subject or entity (e.g.,
customers, products, orders).
• Row (Record): A single horizontal entry in a table, representing a complete instance
of an entity (e.g., a customer record).
• Column (Field): A vertical section within a table that holds a specific type of data for
each row (e.g., customer name, email address).
• Data Type: Defines the kind of data a column can store (e.g., text, numbers, dates,
booleans).
• SQL (Structured Query Language): A standardized language used to interact with
relational databases. It allows you to perform tasks like creating tables, inserting
data, querying data, and updating data.
• Query: A specific request made to a database to retrieve or manipulate data. SQL
queries use SELECT, INSERT, UPDATE, and DELETE statements for various
operations.
• Join: A way to combine data from multiple tables based on a shared relationship,
allowing you to retrieve data from connected tables in a single query.
• Primary Key: A unique identifier for each row in a table, ensuring no duplicate
records exist. A table can only have one primary key.
• Foreign Key: A column in one table that references the primary key of another table,
establishing a link between related data.
• Data Integrity: Maintaining the accuracy and consistency of data within a database.
Constraints (rules) can be applied to enforce data integrity, such as requiring specific
data types or preventing invalid entries.
Data Types
• In programming languages data types specifies the size and type of the value, which
an variable can hold.
• In DBMS data types specifies the size and type of domain values which for a
attribute’s in table or relation.
• Choosing correct data types results in proper computer memory utilization and
minimize the wastage of computer memory.
• MySQL uses many different data types, broken into three categories
o Numeric
o Date and time
o String types
1. INT
• A normal-sized integer that can be signed or unsigned.
• If signed, the allowable range is from –2147483648 to 2147483647.
• If unsigned, the allowable range is from 0 to 4294967295.
• You can specify a width of up to 11 digits.
2. TINYINT
• A small integer that can be signed or unsigned.
• If signed, the allowable range is from –128 to 127. If unsigned, the allowable
range is from 0 to 255.
• You can specify a width of up to 4 digits.
3. SMALLINT
• A small integer that can be signed or unsigned.
• If signed, the allowable range is from 32768 to 32767.
• If unsigned, the allowable range is from 0 to 65535.
• You can specify a width of up to 5 digits.
4. MEDIUMINT
• A medium-sized integer that can be signed or unsigned.
• If signed, the allowable range is from –8388608 to 8388607.
• If unsigned, the allowable range is from 0 to 16777215.
• You can specify a width of up to 9 digits.
5. BIGINT
• A large integer that can be signed or unsigned.
• If signed, the allowable range is from –9223372036854775808 to
9223372036854775807.
• If unsigned, the allowable range is from 0 to 18446744073709551615.
• You can specify a width of up to 11 digits.
6. FLOAT(M,D)
• A floating-point number that cannot be unsigned.
• You can define the display length (M) and the number of decimals (D).
• This is not required and defaults to 10,2, where 2 is the number of decimals and
10 is the total number of digits (including decimals).
• Decimal precision can go to 24 places for a FLOAT.
7. DOUBLE(M,D)
• A double-precision floating-point number that cannot be unsigned.
• You can define the display length (M) and the number of decimals (D).
• This is not required and will default to 16,4, where 4 is the number of decimals.
Decimal precision can go to 53 places for a DOUBLE.
• REAL is a synonym for DOUBLE.
8. DECIMAL(M,D)
• An unpacked floating-point number that cannot be unsigned.
• In unpacked decimals, each decimal corresponds to 1 byte.
• Defining the display length (M) and the number of decimals (D) is required.
• NUMERIC is a synonym for DECIMAL.
1. DATE
• A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31.
• For example, December 30, 1973, is stored as 1973-12-30.
2. DATETIME
• A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-
01-01 00:00:00 and 9999-12-31 23:59:59.
• For example, 3:30 in the afternoon on December 30, 1973, is stored as 1973-12-
30 15:30:00.
3. TIMESTAMP
• A timestamp between midnight, January 1, 1970, and sometime in 2037.
• You can define multiple lengths to the TIMESTAMP field, which directly
correlates to what is stored in it.
• The default length for TIMESTAMP is 14, which stores YYYYMMDDHHMMSS.
• This looks like the previous DATETIME format, only without the hyphens between
numbers; 3:30 in the afternoon on December 30, 1973, is stored as
19731230153000.
• Other definitions of TIMESTAMP are 12 (YYMMDDHHMMSS), 8 (YYYYMMDD),
and 6 (YYMMDD).
• TIME Stores the time in HH:MM:SS format. data type.
4. YEAR(M)
• Stores a year in two-digit or four-digit format.
• If the length is specified as 2 (for example, YEAR(2)), YEAR can be 1970 to 2069
(70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155.
• The default length is 4.
• You will likely use DATETIME or DATE more often than any other date- or time-
related data type
String Types
• Although numeric and date types are fun, most data you’ll store will be in string
format.
• This list describes the common string data types in MySQL
1. CHAR(M)
• A fixed-length string between 1 and 255 characters in length (for example,
CHAR(5)), right-padded with spaces to the specified length when stored.
• Defining a length is not required, but the default is 1.
2. VARCHAR(M)
• A variable-length string between 1 and 255 characters in length;
• For example, VARCHAR(25).
• You must define a length when creating a VARCHAR field.
3. BLOB or TEXT
• A field with a maximum length of 65,535 characters.
• BLOBs are Binary Large Objects and are used to store large amounts of binary
data, such as images or other types of files.
• Fields defined as TEXT also hold large amounts of data; the difference between
the two is that sorts and comparisons on stored data are case sensitive on
BLOBs and are not case sensitive in TEXT fields.
• You do not specify a length with BLOB or TEXT.
4. TINYBLOB or TINYTEXT
• A BLOB or TEXT column with a maximum length of 255 characters.
• You do not specify a length with TINYBLOB or TINYTEXT.
5. MEDIUMBLOB or MEDIUMTEXT
• A BLOB or TEXT column with a maximum length of 16,777,215 characters.
• You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
6. LONGBLOB or LONGTEXT
• A BLOB or TEXT column with a maximum length of 4,294,967,295 characters.
• You do not specify a length with LONGBLOB or LONGTEXT.
7. ENUM
• An enumeration, which is a fancy term for list. When defining an ENUM, you are
creating a list of items from which the value must be selected (or it can be NULL).
• For example, if you want your field to contain A or B or C, you would define your
ENUM as ENUM (‘A’, ‘B’, ‘C’), and only those values (or NULL) could ever
populate that field. ENUMs can have 65,535 different values.
• ENUMs use an index for storing items.
Accessing MySQL
• There are two main ways to access and interact with a MySQL database:
1. Using MySQL Client
2. Using php MyAdmin
8. If the connection is successful, you'll see the MySQL welcome message and
the mysql> prompt, indicating you're connected.
9. From here, you can execute various SQL statements at the mysql> prompt
1. Ensure XAMPP is installed and running on your system. You can verify this by
opening your web browser and going to http://localhost/. You should see the XAMPP
welcome page
2. In your web browser, navigate to the following URL: http://localhost/phpmyadmin/
This will launch the phpMyAdmin interface for managing your MySQL databases
within XAMPP.
3. You might be prompted for a username and password.
By default, XAMPP uses the following credentials for phpMyAdmin access:
Username: root
Password: (Blank by default - Not recommended for production)
4. Once logged in, you'll see the phpMyAdmin dashboard. This interface provides
various functionalities for managing MySQL databases:
• Left panel: Lists available databases and allows you to create new ones.
• Central panel: Displays information about the currently selected database (tables,
users, etc.).
• Right panel: Provides options for working with the selected database object (e.g.,
creating/editing tables, browsing data, running queries).
Basic Operations:
• Browse Databases: Click on a database name in the left panel to see its tables.
• Browse Tables: Click on a table name to see its structure (columns and data types)
and existing data entries.
• Create Databases: Use the "New" option in the left panel to create a new database.
• Create Tables: Within a database, use the "Create table" option to define a new table
structure with columns and data types.
• Insert/Update Data: You can directly insert or update data within tables using the
provided forms.
• Run SQL Queries: phpMyAdmin also allows you to execute SQL queries in the
"SQL" tab for more advanced tasks.
MySQL Commands
1. CREATE Command
• The table-creation command requires
• Name of the table
• Names of fields
• Definitions for each field.
• The generic table-creation syntax is
2. INSERT Command
• After you have created some tables, you use the SQL command INSERT for
adding new records to these tables.
• The basic syntax of INSERT is
• A statement that uses all columns but does not explicitly name them
('BCA202101','Balaji','2002-05-05','BCA');
3. SELECT Command
• SELECT is the SQL command used to retrieve records from your tables
• The basic SELECT Syntax is
• If you want to order results a specific way, such as by date, ID, name, and so on,
specify your requirements using the ORDER BY clause.
• You can use the LIMIT clause to return only a certain number of records from your
SELECT query result
• The WHERE Clause is used to specify a particular condition
Example
SELECT *from icca_student;
4. DELETE Command
• If you want to delete a record from any MySQL table then you can use the
SQL command DELETE
• The basix of DELETE is
5. UPDATE Command
• UPDATE is the SQL command used to modify the contents of one or more
columns in an existing record or set of records.
• The most basic UPDATE syntax looks like this
• Making a conditional UPDATE means that you are using WHERE clauses to match
specific records.
• Using a WHERE clause in an UPDATE statement is just like using a WHERE clause
in a SELECT statement. All the same comparison and logical operators can be used,
such as equal to, greater than, OR, and AND.
Example
UPDATE icca_student SET Branch ="MCA";
1. Connection Functions:
• mysqli_connect(): Opens a new connection to the MySQL server.
• mysqli_close(): Closes a previously opened database connection.
3. Result Functions:
• mysqli_fetch_assoc(): Fetches a result row as an associative array.
• mysqli_fetch_row(): Fetches a result row as a numeric array.
• mysqli_fetch_array(): Fetches a result row as an associative array, a numeric array,
or both.
• mysqli_fetch_object(): Fetches a result row as an object.
7. Other Functions:
• mysqli_real_escape_string(): Escapes special characters in a string for use in an
SQL statement.
• mysqli_insert_id(): Returns the auto-generated id used in the last query.
• mysqli_num_rows(): Returns the number of rows in a result set.
1. mysqli_connect():
• Establishes a connection to a MySQL server.
Syntax: -
mysqli_connect(servername, username, password, [database]);
Where,
• servername: The hostname or IP address of the MySQL server. (e.g., "localhost" if
it's on the same machine as your PHP script)
• username: A valid MySQL username with access to the database you want to
connect to.
• password: The password associated with the username.
• database (optional): The specific database you want to connect to initially.
2. mysqli_select_db()
• Selects the specific database you want to work with within a connection established
by mysqli_connect.
Syntax:-
mysqli_select_db(connection, database);
Where,
• connection: The link identifier resource returned by mysqli_connect.
• database: The name of the database you want to use within the connection
Note:- mysqli_close()
• Closes a previously opened connection to a MySQL database using the MySQLi
extension.
Syntax: -
mysqli_close(connection)
Where,
o connection: The MySQLi connection object that you want to close.
Example
<?php
$conn = mysqli_connect("localhost","root","");
if($conn)
{
echo "Successfully connected to localhost";
}
else
{
die("Could not connect");
}
$newdb = mysqli_select_db($conn,"icca");
if($newdb)
{
echo "<br/>Successfully Selected Specified Database";
}
else
{
die("Sorry! Database could not be selected");
}
mysqli_close($conn);
?>
Output
4. Handle any errors that may occur during the database interaction using error
handling mechanisms provided by PHP, such as mysqli_error().
5. Close the connection using mysqli_close() function.
Example
<?php
$conn = mysqli_connect("localhost","root","","icca") or die("Could not connect");
$query = "CREATE TABLE IF NOT EXISTS icca_student(
Regno varchar(10) NOT NULL PRIMARY KEY,
Name varchar(20) NOT NULL,
DOB date NOT NULL,
Branch varchar(10) not null)";
$result = mysqli_query($conn, $query);
if($result)
{
echo"Table Created successfully";
}
else
{
echo "Something went wrong";
}
mysqli_close($conn);
?>
Output
1. mysqli_fetch_row()
• This function fetches a row from the result set returned by a database query as a
numeric array only.
• It returns a numeric array where each element corresponds to the value of a
column in the order they appear in the SELECT statement.
Example
<?php
$conn = mysqli_connect("localhost","root","","icca") or die("Could not connect");
$query = "SELECT *from icca_student";
$result = mysqli_query($conn, $query) or die("Could not fetch result");
if($result)
{ echo "<table border=1>";
echo"<tr><th>RegNo</th><th>Name</th><th>DOB</th><th>Course</th>";
echo"<tr>";
while($row = mysqli_fetch_row($result))
{
foreach($row as $display)
{
echo "<td>$display</td>";
}
echo "</tr>";
}
}
mysqli_close($conn);
?>
Output
2. mysqli_fetch_array
• The mysqli_fetch_array( ) function fetches a result row as an associative array, a
numeric array or both.
Syntax:-
mysqli_fetch_array(result,resulttype);
Where,
result -> Specifies a result set.
resulttype -> Specifies what type of array that should be produced. Can be one of the
following values: MYSQLI_ASSOC, MYSQLI_NUM or MYSQL_BOTH.
Example
<?php
$conn = mysqli_connect("localhost","root","","icca") or die("Could not connect");
$query = "SELECT *from icca_student";
$result = mysqli_query($conn, $query) or die("Could not fetch result");
if($result)
{
88 INTERFACE BCA COLLEGE, DVG (Site: www.iccadvg.org , Phone no:
8884768574)
PHP
1. Using mysqli_num_rows()
• This method is specifically designed for counting rows in a MySQLi result set.
Syntax: - mysqli_num_rows(result)
Example
<?php
$conn = mysqli_connect("localhost","root","","icca") or die("Could not connect");
$query = "SELECT *from icca_student";
$result = mysqli_query($conn, $query) or die("Could not fetch result");
if($result)
{
$no_of_rows = mysqli_num_rows($result);
echo "Result set has $no_of_rows number of rows";
}
mysqli_close($conn);
?>
Output