PHP Complete Notes
PHP Complete Notes
Lecture Notes on
PHP & MYSQL
Prepared by
Department
Computer Science B.C.A.
UNIT -1
Introduction
PHP started out as a small open source project that evolved as more and more people found out how
useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
History of PHP
PHP, originally standing for “Personal Home Page,” was created by Rasmus Lerdorf in 1994.
Initially, PHP was a set of Common Gateway Interface (CGI) binaries written in the C programming
language for managing his personal website. Over time, it evolved into a more robust scripting
language, with the release of PHP/FI (Forms Interpreter) 2.0 in 1997.
In 1997, two Israeli developers, Zeev Suraski and Andi Gutmans, rewrote the parser for PHP,
leading to the birth of PHP 3. This version introduced the parser written in C and brought significant
improvements to the language’s performance and capabilities.
PHP 4, released in 2000, was a major milestone that included support for object-oriented
programming (OOP) and introduced many features that laid the foundation for modern PHP
development.
PHP 5, launched in 2004, brought substantial improvements, including better support for OOP with
the introduction of features like interfaces and exception handling.
PHP 7, released in 2015, marked a significant leap in performance, boasting up to twice the speed of
PHP 5.x versions, along with many new features and enhancements.
PHP 8, released in 2020, introduced JIT (Just-In-Time) compilation, which further improved
performance and brought new language features, enhancements, and optimizations.
Throughout its history, PHP has become one of the most popular server-side scripting languages,
powering a vast majority of websites on the internet, including some of the most popular ones like
PHP Features
1. Performance:
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
2. Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
3. Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
4. Embedded: PHP code can be easily embedded within HTML tags and script.
5. Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily executed in other OS also.
6. Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC,
etc.
7. Error Reporting –PHP has predefined error reporting constants to generate an error notice
or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
8. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It
will be taken automatically at the time of execution based on the type of data it contains on
its value.
9. Web servers Support: PHP is compatible with almost all local servers used today like
Apache, Netscape, Microsoft IIS, etc.
10. Security: PHP is a secure language to develop the website. It consists of multiple layers of
security to prevent threads and malicious attacks.
11. Control: Different programming languages require long script or code, whereas PHP can do
the same work in a few lines of code. It has maximum control over the websites like you can
make changes easily whenever you want.
Installation:
1. Update Package Index: Ensure your package index is up to date:
sudo apt update
2. Install PHP: Install PHP and common PHP extensions:
sudo apt install php
3. Verify Installation: After installation, verify PHP installation by checking the version:
php -v
Configuration:
1. Configuration Files: PHP configuration files are usually located in
/etc/php/{version}/apache2/php.ini or /etc/php/{version}/cli/php.ini for Apache and
command line respectively.
2. Edit Configuration: Use your preferred text editor to modify the PHP configuration file. You
might need sudo privileges:
sudonano /etc/php/{version}/apache2/php.ini
3. Adjust Settings: Modify settings like max_execution_time, memory_limit, and
error_reporting according to your requirements.
4. Restart Apache: After making changes, restart the Apache server for changes to take effect:
sudosystemctl restart apache2
Common Extensions:
You might also need to install additional PHP extensions based on your requirements. For
example, to install MySQL extension:
sudo apt install php-mysql
Configuration Testing:
Create a test PHP file in your web server’s root directory (usually /var/www/html/) with the
following content:
<?php
phpinfo();
?>
Commenting in PHP :
Single-line comments:
1. Single-line comments are generally used for short explanations or notes relevant to the local
code.
2. There are two syntaxes for single-line comments in PHP:
Using #:
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
Multi-line comments:
1. Multi-line comments are generally used to provide pseudocode algorithms and more detailed
explanations when necessary.
2. The syntax for multi-line comments in PHP is the same as in C.
Variables
Variables are used to store some values or data that can be used later in a program.
The variables are also like containers that store character values, numeric values, memory
addresses, and strings.
const Keyword
PHP introduced a keyword const to create a constant.
The const keyword defines constants at compile time.
The constant defined using const keyword are case-sensitive.
Example
<?php
const MESSAGE="Hello World";
echo MESSAGE;
String
Integer
Boolean
Array
Object
NULL
Resources
Getting the Data Type
You can get the data type of any object by using the var_dump() function. The var_dump()
function returns the data type and the value.
Example:
$x = 5;
Integers
They are whole numbers, without a decimal point, like 4195.
They are the simplest type .they correspond to simple whole numbers, both positive and
negative.
Integers can be assigned to variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading
0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest
(most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Float
A float (floating point number) is a number with a decimal point.
Example: $x = 10.365;
var_dump($x);
Boolean
A Boolean represents two possible states: TRUE or FALSE.
Example: $x = true;
var_dump($x);
Array
An array stores multiple values in one single variable.
Example: $colors= array(“Red",“Blue",“Yellow");
var_dump($colors);
NULL
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Note: If a variable is created without a value, it is automatically assigned a value of NULL.
Example: $x = "Hello world!";
$x = null;
var_dump($x);
Resources
Resources are special variables that hold references to resources external to PHP (such as
database connections).
Operators in PHP
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators
are used to perform operations on variables or values.
For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable. PHP
Operators can be categorized in following forms:
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
1. Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
2. Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
3. Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
5. Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
7. Array Operators
The array operators are used in case of array. Basically, these operators are used to compare
the values of arrays.
8. Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a
shell command. Execution operator and shell_exec() give the same result.
Expressions in PHP:
Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a
typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=)
Example:
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
UNIT -2
Conditional Statements
Conditional statements are used to perform different actions based on different
conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false
• if...elseif....else statement - use this statement to select one of several blocks of code to be
executed
Page 14 of 34 PHP NOTES / DEPT.OF COMPUTER APPLICATION
• switch statement - use this statement to select one of many blocks of code to be executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax:
if (condition) code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the
specified condition is true.
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it
will
output "Have a nice day!":
<?php
$d=date("D");
if ($d=="Fri")
If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:
<?php
$d=date("D");
if ($ d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a
nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
The ? operator:
In PHP, the ? operator is called the ternary operator. It's a shorthand way to write an if-else
statement in a single line.
Syntax:
$variable = (condition) ?value_if_true :value_if_false;
Here's how it works:
If the condition evaluates to true, the value before the colon (:) is assigned to the variable.
If the condition evaluates to false, the value after the colon (:) is assigned to the variable.
For example:
$age = 20;
$message = ($age >= 18) ? "You are an adult" : "You are not an adult";
echo $message; // Outputs: "You are an adult"
It's a concise way to write conditional assignments.
PHP Looping :
Loops execute a block of code a specified number of times, or while a specified condition
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each time the loop runs:
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
Output:
For Loop
Loops execute a block of code a specified number of times, or while a specified condition
is true.
for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:
• init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the
loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at the end of
the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each time the loop runs:
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
foreach Loop
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>
Output:
one
two
three
Creating an array:
In PHP, you can create an array using the array() function or by using square brackets [] since PHP
5.4. Here are examples of both methods:
Using the array() function:
$array1 = array(1, 2, 3, 4, 5); // Numeric array
$array2 = array("apple", "banana", "orange"); // Associative array
$array3 = array("a" => 1, "b" => 2, "c" => 3); // Associative array with keys
This prevents PHP from throwing a notice if the element doesn't exist.
Types of arrays:
In PHP, there are three kind of arrays:
• Numeric/indexed array - An array with a numeric index
• Associative array - An array where each ID key is associated with a value
• Multidimensional array - An array containing one or more arrays
Numeric/indexed Arrays:
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
Example
In the following example you access the variable values by referring to the array name and index:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
The code above will output:
Saab and Volvo are Swedish cars.
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do
it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
Multidimensional Arrays
In a multidimensional 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
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example 2
Displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
Manipulating arrays:
In PHP, you can manipulate arrays in various ways. Here are some common operations you can
perform:
Creating an Array: You can create an array in PHP using square brackets [] or the array()
function.
$array = [1, 2, 3, 4, 5]; // Using square brackets
$array = array(1, 2, 3, 4, 5); // Using array() function
Adding Elements to an Array: You can add elements to an array using square bracket
notation or by using the array_push() function.
$array[] = 6; // Adding element using square bracket notation
array_push($array, 7); // Using array_push() function
Removing Elements from an Array: You can remove elements from an array using the
unset() function or by using array functions like array_pop(), array_shift(), or array_splice().
unset($array[0]); // Removing element by index
array_pop($array); // Removing the last element
array_shift($array); // Removing the first element
array_splice($array, 2, 1); // Removing elements from a specific index
Accessing Array Elements: You can access array elements by their index.
echo $array[0]; // Accessing the first element
Iterating Through an Array: You can iterate through arrays using loops like foreach, for,
while, etc.
foreach ($array as $value) {
echo $value . ' ';
}
Merging Arrays: You can merge arrays using the array_merge() function.
$mergedArray = array_merge($array1, $array2);
Sorting Arrays: You can sort arrays using functions like sort(), rsort(), asort(), arsort(),
ksort(), krsort(), etc.
Using print_r(): The print_r() function is commonly used to display the contents of an array
in a human-readable format.
$array = [1, 2, 3, 4, 5];
print_r($array);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using var_dump(): The var_dump() function provides more detailed information about the
array, including data types and lengths.
$array = [1, 2, 3, 4, 5];
var_dump($array);
Output:
array(5) {
[0]=>int(1)
[1]=>int(2)
[2]=>int(3)
[3]=>int(4)
[4]=>int(5)
}
Using foreach Loop: You can iterate through the array using a foreach loop and display each
element individually.
footer.php
<footer>All Rights Reserved. Do not reproduce this page.</footer>
In our main file, we’ll use require for the header.php and include for the footer.php file:
index.php
<?php require ’header.php’; ?>
<body>
<h2>Main Content Goes Here</h2>
</body>
<?php include ’footer.php’ ?>
Explicit Casting: Explicit casting, also known as manual type conversion, occurs when the
programmer explicitly instructs PHP to convert data from one type to another using casting
functions or type-casting syntax.
For example:
$str = "10"; // string
$num = (int)$str; // Explicitly cast $str to an integer
echo $num; // Output: 10
Here, (int) is used to explicitly cast the string $str to an integer. Similarly, you can use (float),
(string), (array), (object), and (bool) for explicit casting to float, string, array, object, and boolean
respectively.
Function definition:
In PHP, you can define functions using the function keyword. Here's the basic
syntax for defining a function:
In this example, the addNumbers function takes two parameters, adds them
together, and returns the result. The function is then called with the arguments 3
and 4, and the result is echoed to the screen.
Remember that function names in PHP are not case-sensitive, but it's a good
practice to follow a consistent naming convention for functions.
Output:
My name is Kai Jim Refsnes
<?php
// Define a function
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
?>
In this example, the addNumbers function is defined to take two parameters
$num1 and $num2. When you invoke the function with addNumbers(3, 4), it
adds 3 and 4 together, and the result (7) is stored in the variable $result. Finally,
the result is echoed to the screen.
You can also call a function without any parameters if the function doesn't
require them:
<?php
?>
In this example, the sayHello function does not have any parameters, so you can
call it without providing any values inside the parentheses.
Remember that functions in PHP must be defined before they are called. If you
try to invoke a function that hasn't been defined yet, PHP will throw an error.
Actual Parameters:
Actual parameters, on the other hand, are the values or expressions that are
passed to a function or method during its invocation.
These are the concrete values that are used in place of the formal parameters
when calling the function.
Actual parameters are provided when calling the function.
Example:
Variable Scope:
1. Global Scope:
Variables declared outside of any function or class have global scope.
They can be accessed from anywhere in the script, including within functions.
Example:$globalVar = 10;
function exampleFunction() {
echo $GLOBALS['globalVar']; // Accessing global variable
}
exampleFunction(); // Output: 10
2. Local Scope:
Variables declared inside a function have local scope.
They are only accessible within that function.
Example:
function exampleFunction() {
$localVar = 5;
echo $localVar;
}
exampleFunction(); // Output: 5
// This will result in an error, as $localVar is not defined outside the function
// echo $localVar;
3. Static Scope:
Variables declared as static inside a function retain their value between function
calls.
They have function scope but persist across multiple invocations.
Example:
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // Output: 1
counter(); // Output: 2
Function Scope:
4. Global Scope:
Functions declared outside of any other function or class are in the global scope.
They can be called from anywhere in the script.
Example:
function globalFunction() {
echo "This is a global function.";
}
function outerFunction() {
$outerVar = "Outer";
function innerFunction() {
global $outerVar;
echo $outerVar; // Accessing variable from outer function
}
innerFunction();
}
outerFunction(); // Output: Outer
Understanding variable and function scope is crucial for writing maintainable
and bug-free code in PHP. Properly managing scope helps prevent unintended
variable clashes and ensures that functions can access the data they need.
Recursion:
PHP also supports recursive function call like C/C++. In such case, we call
current function within function. It is also known as recursion.
Library functions:
Library functions in PHP refer to built-in functions that are provided by the PHP
language and can be used for a variety of tasks. These functions cover a wide
range of functionalities, from string manipulation to array operations, file
handling, and more. Here are some categories of library functions commonly
used in PHP:
1. String Functions:
strlen: Returns the length of a string.
strpos: Finds the position of the first occurrence of a substring in a string.
str_replace: Replaces all occurrences of a search string with a replacement
string.
2. Array Functions:
count: Counts the number of elements in an array.
array_push: Pushes one or more elements onto the end of an array.
array_pop: Pops the element off the end of an array.
3. Math Functions:
abs: Returns the absolute value of a number.
round: Rounds a floating-point number to the nearest integer.
rand: Generates a random number.
4. File Functions:
file_get_contents: Reads entire file into a string.
file_put_contents: Write a string to a file.
fopen, fclose, fwrite: Functions for opening, closing, and writing to files.
5. Database Functions (for database interactions):
mysqli_connect, mysqli_query, mysqli_fetch_assoc: Functions for MySQL
database interactions.
PDO: PHP Data Objects provide a uniform method of access to multiple
databases.
6. Other Common Functions:
isset: Determines if a variable is set and is not NULL.
empty: Checks if a variable is empty.
explode: Splits a string by a specified delimiter into an array.
These are just a few examples, and PHP provides a rich set of functions for
various tasks. You can find the complete list of PHP functions in the official
PHP documentation
Strings in php:
What is string?
In PHP, a string is a sequence of characters, where a character is a single unit of
information. Strings can contain letters, numbers, symbols, and spaces. PHP
provides various functions and features for working with strings, making it
versatile for tasks like text processing, manipulation, and output.
In PHP, you can define strings using either single quotes (') or double quotes (").
Here are examples of string declarations:
$singleQuotedString = 'This is a string with single quotes.';
$doubleQuotedString = "This is a string with double quotes.";
Both single-quoted and double-quoted strings can contain variables, and
variables will be expanded (interpreted) inside double-quoted strings but not
within single-quoted strings. Here's an example:
$name = "John";
$greeting1 = 'Hello, $name!'; // Output: Hello, $name!
$greeting2 = "Hello, $name!"; // Output: Hello, John!
In the example above, variable interpolation (expanding variables within the
string) only occurs in the double-quoted string.
PHP also provides numerous string functions for tasks such as concatenation,
finding substrings, replacing text, converting case, and more. Here are a few
examples:
$string1 = "Hello";
$string2 = "World";
// Concatenation
$result = $string1 . " " . $string2; // Output: Hello World
// String length
$length = strlen($result); // Output: 11
Creating a string:
In PHP, you can create strings using either single quotes (') or double quotes (").
Here are examples of both:
• Single-Quoted String:
$singleQuotedString = 'This is a string with single quotes.';
In single-quoted strings, variables are not expanded (interpreted). For example:
$name = "John";
$greeting = 'Hello, $name!'; // Output: Hello, $name!
• Double-Quoted String:
$doubleQuotedString = "This is a string with double quotes.";
Double-quoted strings allow variable interpolation, meaning variables are
expanded inside the string. For example:
$name = "John";
$greeting = "Hello, $name!"; // Output: Hello, John!
• Heredoc and Nowdoc Syntax:
PHP also provides two additional syntaxes for creating strings:
➢ Heredoc Syntax:
Heredoc is useful for creating multiline strings:
$heredocString = <<<EOT
This is a heredoc string.
It can span multiple lines.
Variables, like $name, are expanded.
EOT;
➢ Nowdoc Syntax:
Nowdoc is similar to heredoc but treats the contents as a plain string without
variable expansion:
$nowdocString = <<<'EOT'
This is a nowdoc string.
It can also span multiple lines.
Variables, like $name, are not expanded.
EOT;
Choose the string syntax that suits your needs. Single quotes are often used
when there is no need for variable expansion, while double quotes are used
when variables need to be interpolated. Heredoc and nowdoc are useful for
creating multiline strings in a clean and readable way.
String functions:
PHP provides a variety of built-in string functions that allow you to manipulate
and work with strings. Here are some commonly used string functions in PHP:
• strlen - String Length:
Returns the length of a string.
$string = "Hello, World!";
$length = strlen($string);
echo $length; // Output: 13
• strpos - Find Position of First Occurrence:
Finds the position of the first occurrence of a substring in a string.$string =
"Hello, World!";
$position = strpos($string, "World");
echo $position; // Output: 7
• str_replace - Replace All Occurrences of a String:
Replaces all occurrences of a substring with another substring.
$string = "Hello, World!";
$newString = str_replace("World", "PHP", $string);
echo $newString; // Output: Hello, PHP!
• strtolower and strtoupper - Convert Case:
strtolower converts a string to lowercase.
strtoupper converts a string to uppercase.
$string = "Hello, World!";
$lowercase = strtolower($string);
$uppercase = strtoupper($string);
echo $lowercase; // Output: hello, world!
echo $uppercase; // Output: HELLO, WORLD!
• substr - Substring:
Returns a part of a string starting from a specified position.
$string = "Hello, World!";
$substring = substr($string, 7, 5);
echo $substring; // Output: World
• trim - Remove Whitespace:
Removes whitespace (or other characters) from both ends of a string.
$string = " Hello, World! ";
$trimmedString = trim($string);
echo $trimmedString; // Output: Hello, World!
• explode - Split a String by a Delimiter:
Splits a string into an array of substrings based on a delimiter.
$string = "apple,orange,banana";
$fruits = explode(",", $string);
print_r($fruits); // Output: Array ( [0] => apple [1] => orange [2] => banana )
• implode - Join Array Elements with a String:
Joins array elements with a string to create a single string.
$fruits = array("apple", "orange", "banana");
$string = implode(", ", $fruits);
echo $string; // Output: apple, orange, banana
These are just a few examples of the many string functions available in PHP.
You can find more functions and details in the official PHP documentation
UNIT - IV
Like C++ and Java, PHP also supports object oriented programming.
Classes are the blueprints of objects. Class is a programmer-defined data type, which includes
local methods and local variables. Class is a collection of objects.
Object has properties and behavior.
Define a class
A class is defined by using the class keyword, followed by the name of the class and a
pair of curly braces ({}).
Syntax
<? Php
Class MyClass
{
// Class properties and methods go here
}
?>
Creating an Object
A class defines an individual instance of the data structure. We define a class once
and then make many objects that belong to it.
Objects are also known as an instance.
An object is something that can perform a set of related activities.
Syntax: $obj = new MyClass;
<?Php
Class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
1
}
$obj = new demo();
$obj->display();
?>
2
function sub()
{
echo $s = $this->x - $this->y ;
}
}
$obj = new child;
$obj->add() ; // It will return the addition result
$obj->sub() ; /* It's a derived class of the main class, which has a public object and therefore
can be accessed, returning the subtracted result. */
?>
$obj->div(); /* It's a derived class of the main class, which's accessing the private data
which again will lead to fatal error.*/
$obj->mul();
?>
3
echo $d = $this->x / $this->y ;
echo " ";
}
}
class child extends Arithmetic
{
function sub()
{
echo $s = $this->x - $this->y ;
}
}
class derived # Outside Class
{
function mul()
{
echo $m = $this->x * $this->y ;
}
}
$obj= new child; // It will return the division result
$obj->div(); // Since it's a derived class of the main class,
$obj->sub(); // Since it's an outside class, therefore it will produce a fatal error.
$obj->mul();
?>
4
We can also create a property without a default value. See the property $comp in the
above example.
Overloading
What is function overloading?
Function overloading is the ability to create multiple functions of the same name with
different implementations.
Function overloading in PHP?
Function overloading in PHP is used to dynamically create properties and methods.
Function overloading contains same function name and that function performs different task
according to number of arguments. For example, find the area of certain shapes where radius
are given then it should return area of circle if height and width are given then it should give
area of rectangle and others. In PHP function overloading is done with the help of function
__call(). This function takes function name and arguments.
Property and Rules of overloading in PHP:
All overloading methods must be defined as Public.
After creating the object for a class, we can access a set of entities that are properties
or methods not defined within the scope of the class.
Such entities are said to be overloaded properties or methods, and the process is called
as overloading.
For working with these overloaded properties or functions, PHP magic methods are
used.
Most of the magic methods will be triggered in object context except __callStatic()
method which is used in a static context.
Types of Overloading in PHP: There are two types of overloading in PHP.
Property Overloading
Method Overloading
Property Overloading:
PHP property overloading is used to create dynamic properties in the object context.
For creating these properties no separate line of code is needed. A property associated with a
class instance, and if it is not declared within the scope of the class, it is considered as
overloaded property. Following operations are performed with overloaded properties in PHP.
Setting and getting overloaded properties.
Evaluating overloaded properties setting.
5
Undo such properties setting.
Before performing the operations, we should define appropriate magic methods. which are,
__set(): triggered while initializing overloaded properties.
__get(): triggered while using overloaded properties with PHP print statements.
__isset(): This magic method is invoked when we check overloaded properties with
isset() function
__unset(): Similarly, this function will be invoked on using PHP unset() for
overloaded properties.
Example:
<?php
class Toys
{
private $str;
public function __set($name, $value)
{
$this->str[$name] = $value;
}
public function __get($name)
{
echo "Overloaded Property name = " . $this->str[$name] . "<br/>";
}
public function __isset($name)
{
if (isset($this->str[$name]))
{
echo "Property \$$name is set.<br/>";
}
else
{
echo "Property \$$name is not set.<br/>";
}
}
public function __unset($name)
{
unset($this->str[$name]);
echo "\$$name is unset <br/>";
}
}
$objToys = new Toys();
/* setters and getters on dynamic properties */
$objToys->overloaded_property = "new";
echo $objToys->overloaded_property . "\n\n";
/* Operations with dynamic properties values */
isset($objToys->overloaded_property);
unset($objToys->overloaded_property);
6
isset($objToys->overloaded_property);
?>
Method Overloading
It is a type of overloading for creating dynamic methods that are not declared within
the class scope. PHP method overloading also triggers magic methods dedicated to the
appropriate purpose. Unlike property overloading, PHP method overloading allows function
call on both object and static context. The related magic functions are:
__call() – triggered while invoking overloaded methods in the object context.
__callStatic() – triggered while invoking overloaded methods in static context.
Example:
<?php
class Toys
{
public function __call($name, $param)
{
echo "Magic method invoked while method overloading with object
reference<br/>";
}
public static function __callStatic($name, $param)
{
echo "Magic method invoked while method overloading with static
access<br/>";
}
}
$objToys = new Toys();
$objToys->overloaded_method();
Toys::overloaded_property();
?>
Constructor
A constructor allows you to initialize an object's properties upon creation of the
object.
If you create a construct() function, PHP will automatically call this function when
you create an object from a class.
Notice that the construct function starts with two underscores ( __ )
Following example will create one constructor for Books class and it will initialize price and
title for the book at the time of object creation.
7
$this->title = $par1;
$this->price = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these
two member variables at the time of object creation only. Check following example below –
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );
Example:
<?Php
class Example
{
public function __construct()
{
echo "Hello javatpoint";
}
}
$obj = new Example();
$obj = new Example();
?>
Example
<?php
class BankAccount
{
private $accountNumber;
private $balance;
Types of Constructor
Default Constructor: It has no parameters, but the values to the default constructor can be
passed dynamically.
Parameterized Constructor: It takes the parameters, and also you can pass different values
to the data members.
Copy Constructor: It accepts the address of the other objects as a parameter.
8
Default Constructor
Parameterized Constructor
A parameterized constructor is explicitly defined within a class and accepts
parameters to customize the initialization process. It allows you to pass values during object
creation and use those values to set properties or perform other tasks. This type of constructor
is useful when objects require specific information to function correctly.
Example:
<?php
class Example
{
//defining constructor
function __construct($name)
{
echo "Hello ".$name."<br>";
}
}
$obj1= new Example("World");
$obj2= new Example("Owlbuddy");
?>
9
Copy Constructor
The copy constructor is used to create a duplicate of an already existing object. It accepts the
address of another object as a parameter, allowing for the creation of an identical copy.
Example:
<?php
class Example
{
public $name;
public $age;
//default constructor
public function __construct( )
{
}
// This is a copy constructor
public function copyCon(Example $o)
{
$this->name = $o->name;
$this->age = $o->age;
}
function show( )
{
echo "Name = ".$this->name.'<br>';
echo "Age = ".$this->age.'<br>';
}
}
$obj1 = new Example();
$obj1->name = 'Aman';
$obj1->age = '21';
$obj1->show();
$obj2 = new Example();
//calling copyCon method
$obj2->copyCon($obj1);
$obj2->show();
?>
Destructor
Like a constructor function you can define a destructor function using function
__destruct( ). You can release all the resources with-in a destructor.
Example:
<?php
class demo
{
public function demo( )
{
10
echo "constructor1...";
}
}
class demo1 extends demo
{
public function __construct( )
{
echo parent::demo();
echo "constructor2...";
}
public function __destruct()
{
echo "destroy.....";
}
}
$obj= new demo1();
?>
Inheritance
Inheritance is a way of extending the existing class functionality in the newly created
class. We can also add functionality to the newly created class apart from extending the base
class functionalities. When we inherit one class, we say an inherited class is a child class
(sub-class), which is called the parent class from which we inherit it. The parent class is also
known as the base class. The idea behind using inheritance is all about the code reusability.
Types of Inheritance in PHP
PHP supports various types of inheritance they are
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Single Inheritance
Single inheritance is a concept in PHP in which only one class can be inherited by a
single class. We need to have two classes in between this process. One is the base (parent)
class, and the other is the child class.
11
Example:
<?php
class MyAccess
{
var $var = "This is first var";
protected $fist_name;
function returnVar()
{
echo $this->fist_name;
}
function set_fist_name($set_this)
{
$this->fist_name = $set_this;
}
}
class child extends MyAccess
{
function setVal($set_this)
{
$this->fist_name = $set_this;
}
function getVal()
{
echo $this->fist_name;
}
}
$obj1 = new child();
$obj1->setVal("Jai Shre");
$obj1->getVal();
?>
Multilevel Inheritance
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more
than 2 classes. A parent class will be inherited by a child class then that child class will be
inherited by the child class.
12
Example:
<?php
class ParentClass
{
var $var = "This is first var";
public $fist_name;
function returnVar()
{
echo $this->fist_name;
}
function set_fist_name($set_this)
{
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass
{
function setVal($set_this)
{
$this->fist_name = $set_this;
}
function getVal()
{
echo "Extended By Parent Class -". $this->fist_name;
}
}
class child_2 extends child_1
{
function setVal($set_this)
{
$this->fist_name = $set_this;
}
function getVal()
{
echo "Extended By child 1 - ".$this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first inherited class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second inherited class");
$obj2->getVal();
?>
13
Hierarchical Inheritance
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of
inheritance in which a program consists of a single parent and more than one child class.
Let’s understand the same with an example.
Example:
<?php
class ParentClass
{
var $var = "This is first var";
public $fist_name;
function returnVar()
{
echo $this->fist_name;
}
function set_fist_name($set_this)
{
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass
{
function setVal($set_this)
{
$this->fist_name = $set_this;
}
function getVal()
{
echo $this->fist_name;
}
}
class child_2 extends ParentClass
{
function setVal($set_this)
{
$this->fist_name = $set_this." - ".$set_this;;
}
14
function getVal()
{
echo $this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first child class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second child class");
$obj2->getVal();
?>
Form Handling
Creating HTML Form
When we develop a website or a web application, we often have to create forms to
take input from users, like a Login form or a Registration form.
Creating a form on the webpage is accomplished using HTML, while PHP serves as a
transport for those values from the webpage to the server and then in further processing those
values.
PHP provides two superglobals $_GET and $_POST for collecting form-data for processing.
In the code above, we have used the <form> tag to create an HTML form, with input fields
for Name and Email along with submit button to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are
for?
action: Using this attribute, we can specify the name of the file which will collect and handle
the form-data. In the example above, we have provided name of a Php file.
15
method: This attribute specify the means of sending the form-data, whether it will be
submitted via POST method or GET method.
Below we have the same form with method as GET
<html>
<body>
<form action="form-handler.php" method="GET">
Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>
</body>
</html>
16
GET vs. POST:
GET and POST are used for the same purpose but they work differently. When a user
submits a form, the values from the input fields are stored in an array, like
array(key1=>value1, key2=>value2,...) and then passed on to the destination(Php file)
specified in the action attribute of the <form> tag.
Using GET method
In case of GET method, form-data is submitted as URL parameters, i.e. all the values
entered in the form fields by the user are sent to the action script, appended in the URL. Let's
take a simple example to understand, below we have a simple HTML form.
<html>
<body>
<form action="form-handler.php" method="GET">
Name: <input type="text" name="name"> <br/>
Age: <input type="text" name="age"> <br/>
<input type="submit">
</form>
</body>
</html>
We have two input fields in above form, one is name and the other one is age. When
we click on submit, we will be redicrected to the following URL, form-
handler.php?name=Studytonight&age=5, with the form-data appended to the URL.
Sending the form-data as URL parameters proves out useful at times as you can easily
bookmark links with form-data, but for appending parameters in a URL there is a limit of
2000 characters, hence for forms with large number of fields, it is not suggested, as some data
might get lost or the form submission may lead to error.
The Php file form-handler.php will look like
<?php
// name attribute of the input field goes inside the
// square brackets of $_GET superglobal
$name = $_GET["name"];
$age = $_GET["age"];
echo "Your name is ". $name . " and you are ". $age . " years old".
?>
As the form-data is visible to everyone because it sent as URL parameters, hence we should
not use GET method for a form with sensitive data, like passwords etc.
17
Using POST method
When we use the POST method, the array of key-value pair(the form-data), coming
from the HTML form are sent as part of the HTTP request, hence they are invisible to the
user. Also, there is no character limit for the information/data being transmitted.
POST method also supports multipart form-data upload which is used for file upload. Its
recommend, that you use the POST method while working on any PHP web
application/project. Let's take a simple example to understand, below we have a simple
HTML form.
<html>
<body>
<form action="form-handler.php" method="POST">
Name: <input type="text" name="name"> <br/>
Age: <input type="text" name="age"> <br/>
<input type="submit">
</form>
</body>
</html>
18
Database Terminology
Database
A collection of information organized in such a way that a computer program can
quickly select desired pieces of data.
DBMS (Database Management System)
A collection of programs that enables you to store, modify, and extract information
from a database.
RDBMS (Relational Database Management System)
A type of DBMS that stores data in the form of related tables.
Powerful because they require few assumptions about how data is related or how it
will be extracted from the database.
The same database can be viewed in many different ways.
Table
A collection of data that relates to each other.
Record
A complete set of information. Records are composed of fields, each of which
contains one item of information. It is also called a tuple.
Field
A space allocated for a particular item of information.
The smallest units of information you can access.
Data
Distinct pieces of information, usually formatted in a special way.
Metadata
Describes how and when and by whom a particular set of data was collected, and how
the data is formatted.
Attribute
A particular piece of information about a field.
19
We can determine the data type in MySQL with the following characteristics:
The type of values (fixed or variable) it represents.
The storage space it takes is based on whether the values are a fixed-length or variable
length.
Its values can be indexed or not.
How MySQL performs a comparison of values of a particular data type.
Numeric Data Type
MySQL has all essential SQL numeric data types. These data types can include the
exact numeric data types (For example, integer, decimal, numeric, etc.), as well as the
approximate numeric data types (For example, float, real, and double precision). It also
supports BIT datatype to store bit values. In MySQL, numeric data types are categories into
two types, either signed or unsigned except for bit data type.
Data Type Description
It is a very small integer that can be signed or unsigned. If signed, the
allowable range is from -128 to 127. If unsigned, the allowable range is
TINYINT
from 0 to 255. We can specify a width of up to 4 digits. It takes 1 byte for
storage.
It is 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
SMALLINT
to 65535. We can specify a width of up to 5 digits. It requires 2 bytes for
storage.
It is a medium-sized integer that can be signed or unsigned. If signed, the
allowable range is from -8388608 to 8388607. If unsigned, the allowable
MEDIUMINT
range is from 0 to 16777215. We can specify a width of up to 9 digits. It
requires 3 bytes for storage.
It is a normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the
INT
allowable range is from 0 to 4294967295. We can specify a width of up to
11 digits. It requires 4 bytes for storage.
It is a large integer that can be signed or unsigned. If signed, the allowable
range is from -9223372036854775808 to 9223372036854775807. If
BIGINT
unsigned, the allowable range is from 0 to 18446744073709551615. We
can specify a width of up to 20 digits. It requires 8 bytes for storage.
20
It is 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
FLOAT(m,d) and will default 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 type. It requires 2 bytes for storage.
It is a double-precision floating-point number that cannot be unsigned.
You can define the display length (m) and the number of decimals (d).
DOUBLE(m,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. It requires 8 bytes for storage.
An unpacked floating-point number that cannot be unsigned. In unpacked
decimals, each decimal corresponds to one byte. Defining the display
DECIMAL(m,d)
length (m) and the number of decimals (d) is required. Numeric is a
synonym for decimal.
It is used for storing bit values into the table column. Here, M determines
BIT(m)
the number of bit per value that has a range of 1 to 64.
It is used only for the true and false condition. It considered numeric value
BOOL
1 as true and 0 as false.
BOOLEAN It is Similar to the BOOL.
21
String Data Types:
The string data type is used to hold plain text and binary data, for example, files,
images, etc. MySQL can perform searching and comparison of string value based on the
pattern matching such as LIKE operator, Regular Expressions, etc. The following table
illustrates all string data types that support in MySQL
22
Binary Large Object Data Types (BLOB)
BLOB in MySQL is a data type that can hold a variable amount of data. They are
categories into four different types based on the maximum length of values can hold.
23
Spatial Data Types
It is a special kind of data type which is used to hold various geometrical and geographical
values. It corresponds to OpenGIS classes. The following table shows all spatial types that
support in MySQL:
24
UNIT – V
Accessing MySQL
SQL Commands
SELECT - extracts data from a database
25
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table. The datatype
parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
26
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want
to list the different (distinct) values.
Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
FROM table_name
WHERE condition;
Example
SELECT * FROM Customers
WHERE Country = 'Mexico';
The following operators can be used in the WHERE clause:
27
The MySQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators. The AND
and OR operators are used to filter records based on more than one condition
The AND operator displays a record if all the conditions separated by AND are
TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
28
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query. However, make sure the order of the values is in
the same order as the columns in the table. Here, the INSERT INTO syntax would be as
follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
In PHP Scripting language many functions are available for MySQL Database
connectivity and executing SQL queries.
29
MySQLi is extension in PHP scripting language which gives access to the MYSQL
database. MySQLi extension was introduced version 5.0.0
The MySQLi extension contains the following important functions which are related
to MySQL database connectivity and management.
Mysqli_connect() Function
Mysqli_close() Function
Mysqli_query()Function
Database Connections
Before accessing MySQL Database, connect to Database Server machine via PHP
scripting language using Mysqli_connect() Function.
Syntax
mysqli_connect(“Server Name “,”User Name”,”Password”,”DB Name”);
This function requires four parameters to connect to database server. Database Server name,
Database username, password and Database Name.
In the above code, four variables are used to connect to the Database server. They are
$servername -> Database Server Server IP address
$username -> Database Server User Name
$password -> Database Server Password
$DB_Name -> Database Name
30
The mysqli_connect function uses these variables to connect Database server to PHP.
If connection gets fail, output will be printed with MySQL error code. Otherwise connection
is success.
Performing Queries
The main goal of MySQL and PHP connectivity is to retrieve and manipulate the data
from MySQL database server. The SQL query statements help in PHP MySQL extension to
achieve the objective of MySQL and PHP connection. “mysqli_query” is a function, that
helps to execute the SQL query statements in PHP scripting language.
Syntax
mysqli_query(“Connection Object”, “SQL Query”)
Example
$con=mysqli_connect(“localhost”, “my_user”, “my_password”, “Student_DB”);
$sql=”SELECT student_name,student_age FROM student”;mysqli_query($con,$sql);
Closing Connection:
mysqli_close() Function is used to close an existing opened database connection
between PHP scripting and MySQL Database Server.
Syntax
mysqli_close(“Connection Object”);
Example
<?php
$con=mysqli_connect(“localhost”,”$user”,”$password”,”SCHOOL_DB”);
mysqli_close($con);
?>
Example:
<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “school_DB”;
$connection = mysqli_connect(‘$servername ‘, ‘$username’, ‘$password’,’$dbname’);
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: “ . mysqli_connect_error();
}
sql_stmt = “SELECT * FROM my_contacts”; //SQL select query
$result = mysqli_query($connection,$sql_stmt);//execute SQL statement
31
$rows = mysqli_num_rows($result);// get number of rows returned
if ($rows)
{
while ($row = mysqli_fetch_array($result))
{
echo ‘ID: ‘ . $row[‘id’] . ‘<br>’;
echo ‘Full Names: ‘ . $row[‘full_names’] . ‘<br>’;
echo ‘Gender: ‘ . $row[‘gender’] . ‘<br>’;
echo ‘Contact No: ‘ . $row[‘contact_no’] . ‘<br>’;
echo ‘Email: ‘ . $row[‘email’] . ‘<br>’;
echo ‘City: ‘ . $row[‘city’] . ‘<br>’;
echo ‘Country: ‘ . $row[‘country’] . ‘<br><br>’;
}
}
mysqli_close($connection); //close the database connection
?>
32
<span>Address:</span> <?php echo $row1['employee_address']; ?>
Closing connection with server.
mysql_close($connection);
33
updates, PHP's support for SQL statements makes the process straightforward and ensures
optimal performance.
Example
<?php
// Step 1: Create a database connection
$servername = "localhost"; // Replace with your database server name
$username = "username"; // Replace with your database username
$password = "password"; // Replace with your database password
$dbname = "database"; // Replace with your database name
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// Step 2: Prepare and execute the update query
$sql = "UPDATE table_name SET column1 = 'new_value1', column2 = 'new_value2'
WHERE condition";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . $conn->error;
}
// Step 3: Close the database connection
$conn->close();
?>
In the above code, you need to replace the following placeholders with your actual database
credentials and query details:
$servername: Your database server name or IP address.
$username: Your database username.
$password: Your database password.
$dbname: Your database name.
table_name: The name of the table you want to update.
column1, column2: The columns in the table you want to update.
new_value1, new_value2:The new values you want to set for the respective columns.
condition: The condition that specifies which rows to update. For example, id = 1 to
update a row with the ID of 1.
34