Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

MODULE: APPLYING PHP PROGRAMMING

LEVEL 4 SOD, APPLYING PHP PROGRAMMING NOTE

UNIT 1: Apply PHP Fundamentals

What is PHP?

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

What is a PHP File?

 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

Scripting Vs. Programming Languages

Scripting languages: help in automating various software apps, web pages in a browser

One needs to compile the programming languages to machine code so as to run them on the
hardware of an underlying OS (operating system). A user needs to deploy a certain Integrated
Development Environment (IDE) for using programming languages. A programmer needs to
provide an instruction set for the computers for achieving certain goals. One can also implement
certain algorithms by writing the programs
Parameters Scripting Language Programming Language

Language Type The scripting languages are The programming languages are
interpreter-based languages. compiler-based languages.

Use The scripting languages help in The programming languages help in


combining the existing components of developing anything from scratch.
an application.

Running of A user needs to run scripting Programming languages are program-


Language languages inside an existing program. independent.
Thus, it’s program-dependent.

Conversion Scripting languages convert high-level Programming languages help in


instructions into machine language. converting the full program into the
machine language (at once).

Compilation You don’t need to compile these These languages first need a compilation.
languages.

Design These make the coding process simple These provide full usage of the
and fast. languages.

File Type Scripting languages don’t create any Programming languages create .exe files.
file types.

Complexity These are very easy to use and easy to These are pretty complex in terms of
write. writing and usage.

Type of Coding Scripting languages help write a small Programming languages help write the
piece of an entire code. full code concerning a program.
Developing These take less time because they These take more time because a
Time involve lesser code. programmer must write the entire code.

Interpretation We usually interpret a scripting The compile results of a programming


language in another program. language are stand-alone. No other
program needs to interpret it.

Requirement of Scripting languages require hosts for Programming languages are self-
Host execution. executable. They don’t require any host.

Length of These involve very few and short These require numerous lines of coding
Codes coding lines. for a single function.

Support These provide limited support to data These provide rich support for graphic
types, user interface design, and design, data types, and user interface
graphic design. design.

Maintenance These involve very low maintenance. These involve high maintenance.

Cost It is easier and cheaper to maintain a Maintaining a programming language is


scripting language. comparatively more expensive.

Example VB Script, Perl, Ruby, PHP, C, C++, COBOL, Basic, VB, C#, Pascal,
JavaScript, etc. Java, etc.

 PHP script is executed on the server, and the plain HTML result is sent back to the
browser.

A compiler translates the entire source code into machine code before execution, resulting in
faster execution since no translation is needed during runtime.
An interpreter is a software tool that directly executes high-level programming code without
prior translation into machine code. It reads and executes the code line by line, translating each
line into machine instructions on the fly, making it easier to identify errors and debug the code.

Basic PHP Syntax

 A PHP script can be placed anywhere in the document.


 A PHP script starts with <?php and ends with ?>

1.2: Describe PHP Syntax, Data types, Variables, Operators and Arrays.

Variables

Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

EXAMPLE:

$x = 5;

$y = "John"

PHP echo and print Statements

Wth PHP, there are two basic ways to get output: echo and print.

In this tutorial we use echo or print in almost every example. So, this chapter contains a little
more info about those two output statements.

PHP echo and print Statements

echo and print are more or less the same. They are both used to output data to the screen.

The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.

The PHP echo Statement


The echo statement can be used with or without parentheses: echo or echo().

Display Text

The following example shows how to output text with the echo command (notice that the text
can contain HTML markup):

Example
echo "<h2>PHP is Fun!</h2>";

echo "Hello world!<br>";

echo "I'm about to learn PHP!<br>";

echo "This ", "string ", "was ", "made ", "with multiple parameters.";

Display Variables

The following example shows how to output text and variables with the echo statement:

Example
$txt1 = "Learn PHP";

$txt2 = "W3Schools.com";

$x = 5;

$y = 4;

echo "<h2>" . $txt1 . "</h2>";

echo "Study PHP at " . $txt2 . "<br>";

echo $x + $y;

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. resource
2. NULL

PHP Boolean

Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.

Example:

1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>

Output:

This condition is TRUE.


PHP Integer

Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31
to 2^31.

Example:

1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>

Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.

Example:

1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:

Addition of floating numbers: 73.812


PHP String

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.

String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:

Example:<?php

1. $company = "Javatpoint";
2. //both single and double quote statements will treat different
3. echo "Hello $company";
4. echo "</br>";
5. echo 'Hello $company';
6. ?>

Output:

Hello Javatpoint
Hello $company
PHP Array

An array is a compound data type. It can store multiple values of same data type in a single
variable.

Example:

1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

You will learn more about array in later chapters of this tutorial.

PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.

Example:

1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>

Output:

Bike Model: Royal Enfield


PHP Null

Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>

PHP Operators

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y


% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.

Assignment Same as... Description

x=y x=y The left operand gets set to the value of the expression
on the right

x += y x=x+y Addition

x -= y x=x–y Subtraction

x *= y x=x*y Multiplication
x /= y x=x/y Division

x %= y x=x%y Modulus

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to


$y

=== Identical $x === $y Returns true if $x is equal to


$y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not equal


to $y

<> Not equal $x <> $y Returns true if $x is not equal


to $y

!== Not identical $x !== $y Returns true if $x is not equal


to $y, or they are not of the
same type
> Greater than $x > $y Returns true if $x is greater
than $y

< Less than $x < $y Returns true if $x is less than


$y

>= Greater than or equal to $x >= $y Returns true if $x is greater


than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than


or equal to $y

<=> Spaceship $x <=> $y Returns an integer less than,


equal to, or greater than zero,
depending on if $x is less than,
equal to, or greater than $y.
Introduced in PHP 7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description

++$x Pre-increment Increments $x by one, then returns $x


$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

And And $x and $y True if both $x and $y are true

Or Or $x or $y True if either $x or $y is true

Xor Xor $x xor $y True if either $x or $y is true, but


not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true


! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and


$txt2

.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the


same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the
same key/value pairs in the same
order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to


$y

<> Inequality $x <> $y Returns true if $x is not equal to


$y

!== Non-identity $x !== $y Returns true if $x is not identical


to $y

Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.

Syntax for comments in PHP code:

// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

Unit 2: Implement PHP logic

2.1: Use PHP control structures


PHP If Else

PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

 if
 if-else
 if-else-if
 nested if

PHP If Statement

PHP if statement allows conditional execution of code. It is executed if condition is true.

If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax

1. if(condition){
2. //code to be executed
3. }

Flowchart
Example

1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>

Output:

12 is less than 100


PHP If-else Statement

PHP if-else statement is executed whether condition is true or false. If-else statement is slightly
different from if statement. It executes one block of code if the specified condition is true and
another block of code if the condition is false.

Syntax

1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

Example

1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

Output:

12 is even number
PHP If-else-if Statement

The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.

Syntax

1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }

Flowchart

Example

1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>

Output:

B Grade
PHP nested if Statement

The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.

Syntax

1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }

Flowchart
Example

1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian")
6. {
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>

 SWITCH

PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.

Syntax
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must always be
the last statement.
2. There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch
expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart

PHP Switch Example


1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>

PHP For Loop (Iterative statements)

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means for
loop is used when you already know how many times you want to execute a block of code.

Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }

initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.

condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.

Increment/decrement - It increments or decrements the value of the variable.


Flowchart

Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
PHP While Loop

PHP while loop can be used to traverse set of code like for loop. The while loop executes a block
of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from
the body of loop.

PHP While Loop Flowchart

PHP While Loop Example


1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
PHP do-while loop

PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the
code.

The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.

Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart

Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>

Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as entry control The do-while loop is also named as exit control loop.
loop.

The body of the loop does not execute if the The body of the loop executes at least once, even if the
condition is false. condition is false.

Condition checks first, and then block of Block of statements executes first and then condition
statements executes. checks.

This loop does not use a semicolon to Do-while loop use semicolon to terminate the loop.
terminate the loop.

2.2 : Use PHP Functions


2.2.1 Built-in functions
 PHP Math Functions

Function Description

abs() It is used to find the absolute (positive) value of a number.

sin() It is used to return the sine of a number.

sinh() It is used to return the hyperbolic sine of a number.

asin() It is used to find the arc sine of a number.

asinh() It is used to find the inverse hyperbolic sine of a number.


cos() It is used to find the cosine of a number.

cosh() It is used to return the cosh of a number.

acos() It is used to return the arc cosine of a number.

acosh() It is used to return the inverse hyperbolic cosine of a number.

tan() It is used to return the tangent of a number.

tanh() It is used to return the hyperbolic tangent of a number.

atan() It is used to return the arc tangent of a number in radians.

atan2() It is used to return the arc tangent of two variables x and y.

atanh() It is used to return the inverse hyperbolic tangent of a number.

base_convert() It is used to convert a number from one number base to another.

bindec() It is used to convert a binary number to a decimal number.

ceil() It is used to find round a number up to the nearest integer.

pi() It returns the approximation value of PI.

decbin() It converts a decimal number to a binary number.

dechex() It converts a decimal number to a hexadecimal number.

decoct() It converts a decimal number to an octal number

deg2rad() It converts a degree value to a radian value.


rad2deg() It converts a radian value to a degree value.

exp() It is used to calculate the exponent of e.

expm1() It is used to return exp(x) - 1.

floor() It converts round a number down to the nearest integer.

fmod() It returns the remainder of x/y.

getrandmax() It returns the largest possible value returned by rand().

hexadec() It is used to convert a hexadecimal number to a decimal number.

hypot() It is used to calculate the hypotenuse of a right-angle triangle.

is_finite() To check whether a value is finite or not.

is_infinite() It is used to check whether a value is infinite or not.

is_nan() It is used to check whether a value is 'not-a-number'.

lcg_value() It is used to return a pseudo random number in a range between 0 and 1.

log() It is used to return the natural logarithm of a number.

log10() It is used to return the base-10 logarithm of a number.

log1p() It is used to return log(1+number).

max() It is used to return the highest value in an array, or the highest value of several
specified values.

min() It returns the lowest value in an array, or the lowest value of several specified
values.
getrandmax() It is used to return the maximum value by using rand().

mt_getrandmax() Returns the largest possible value returned by mt_rand().

mt_rand() Generates a random integer using Mersenne Twister algorithm.

mt_srand() Seeds the Mersenne Twister random number generator.

octdec() It is used to converts an octal number to a decimal number.

pow() It is used to return x raised to the power of y.

intdiv It returns the integer quotient of the division of dividend by divisor.

rand() It is used to generates a random integer.

round() It is used to round a floating-point number.

fmod() It is used to return the floating point remainder of the division of the argument.

sqrt() It is used to return the square root of a number.

 PHP String Function


1) PHP strtolower() function

The strtolower() function returns string in lowercase letter.

Syntax

1. string strtolower ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>

Output:

my name is khan
2) PHP strtoupper() function

The strtoupper() function returns string in uppercase letter.

Syntax

1. string strtoupper ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>

Output:

MY NAME IS KHAN
3) PHP ucfirst() function

The ucfirst() function returns string converting first character into uppercase. It doesn't change
the case of other characters.

Syntax

1. string ucfirst ( string $str )

Example

1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>

Output:

My name is KHAN
4) PHP lcfirst() function

The lcfirst() function returns string converting first character into lowercase. It doesn't change the
case of other characters.

Syntax

1. string lcfirst ( string $str )

Example

1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>

Output:

mY name IS KHAN
5) PHP ucwords() function

The ucwords() function returns string converting first character of each word into uppercase.

Syntax

1. string ucwords ( string $str )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:

My Name Is Sonoo Jaiswal


6) PHP strrev() function

The strrev() function returns reversed string.

Syntax

1. string strrev ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>

Output:

lawsiaj oonoS si eman ym


7) PHP strlen() function

The strlen() function returns length of the string.

Syntax

1. int strlen ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>

Output:
24

2.2 User-defined functions


User-defined functions in PHP allow you to encapsulate reusable code into named blocks that
can be invoked whenever needed. Functions help in organizing and modularizing your code,
making it easier to manage and maintain. Here’s an overview of how to define and use functions
in PHP, along with some practical examples.
Defining a Function
A function in PHP is defined using the function keyword, followed by the function name,
parentheses for parameters (if any), and curly braces to enclose the function body.
Syntax
php
function functionName($param1, $param2, ...) {
// Code to be executed
}
Example
php
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("John");
?>
Function Parameters
Functions can take parameters (also called arguments), which allow you to pass values into the
function. Parameters are specified within the parentheses after the function name.

Example
php
<?php
function add($a, $b) {
return $a + $b;
}

echo add(3, 4); // Outputs: 7


?>
Default Parameters
You can provide default values for parameters. If no argument is provided for a parameter with a
default value, the function will use the default.

Example
php
<?php
function greet($name = "Guest") {
return "Hello, " . $name . "!";
}

echo greet(); // Outputs: Hello, Guest!


echo greet("John"); // Outputs: Hello, John!
?>
Returning Values
Functions can return values using the return keyword. Once a return statement is executed, the
function terminates, and the returned value is passed back to the calling code.
Example
php
<?php
function multiply($a, $b) {
return $a * $b;
}

$result = multiply(3, 4); // $result is 12


echo $result;
?>
Variable Scope
Variables defined inside a function are local to that function. To access global variables inside a
function, you need to use the global keyword.
Example
php
<?php
$globalVar = 10;
function test() {
global $globalVar;
$localVar = 5;
return $globalVar + $localVar;
}

echo test(); // Outputs: 15


?>
Example Use Cases
Example 1: Calculating Factorial
php
<?php
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}

echo factorial(5); // Outputs: 120


?>
Example 2: String Manipulation
php
Copy code
<?php
function makeTitle($str) {
return ucwords(strtolower($str));
}

echo makeTitle("hELLO wORLD!"); // Outputs: Hello World!


?>
Example 3: Working with Arrays
php
Copy code
<?php
function arrayAverage($arr) {
$sum = array_sum($arr);
$count = count($arr);
return ($count > 0) ? ($sum / $count) : 0;
}

$numbers = [1, 2, 3, 4, 5];


echo arrayAverage($numbers); // Outputs: 3
?>
2.3: Implement PHP File processing
Description and Examples of File Operations in PHP
PHP provides a variety of functions to handle file operations such as creating, reading, writing,
appending, renaming, zipping, and copying files. Below are detailed descriptions and examples
of each operation:

 Create File
To create a new file, you can use the fopen() function with the w or w+ mode. If the file does not
exist, it will be created.
<?php
$filename = 'example.txt';
$file = fopen($filename, 'w'); // Open file for writing
if ($file) {
echo "File '$filename' created successfully.";
fclose($file);
} else {
echo "Error creating file '$filename'.";
}
?>
 Append Data to File
To append data to an existing file, use the fopen() function with the a mode and then write data
using the fwrite() function.
<?php
$filename = 'example.txt';
$file = fopen($filename, 'a'); // Open file for appending
if ($file) {
$data = "Appending this data to the file.\n";
fwrite($file, $data);
echo "Data appended to file '$filename'.";
fclose($file);
} else {
echo "Error opening file '$filename' for appending.";
}
?>
 Read File
To read the contents of a file, use the fread() function after opening the file with the fopen()
function in r mode. Alternatively, you can use file_get_contents() for simplicity.

php
<?php
$filename = 'example.txt';
$file = fopen($filename, 'r'); // Open file for reading
if ($file) {
$contents = fread($file, filesize($filename));
echo "File contents:\n$contents";
fclose($file);
} else {
echo "Error opening file '$filename' for reading.";
}

// Using file_get_contents()
$contents = file_get_contents($filename);
echo "File contents:\n$contents";
?>
 Write File
To write data to a file, use the fopen() function with the w mode and then write data using the
fwrite() function. This will overwrite the existing content.

php
<?php
$filename = 'example.txt';
$file = fopen($filename, 'w'); // Open file for writing
if ($file) {
$data = "Writing new data to the file.\n";
fwrite($file, $data);
echo "Data written to file '$filename'.";
fclose($file);
} else {
echo "Error opening file '$filename' for writing.";
}
?>
 Rename File
To rename a file, use the rename() function.

php
<?php
$oldName = 'example.txt';
$newName = 'new_example.txt';
if (rename($oldName, $newName)) {
echo "File renamed from '$oldName' to '$newName'.";
} else {
echo "Error renaming file '$oldName'.";
}
?>
 ZIP File
To create a ZIP file and add files to it, use the ZipArchive class.
php
<?php
$zip = new ZipArchive();
$filename = "example.zip";

if ($zip->open($filename, ZipArchive::CREATE) === TRUE) {


$zip->addFile("example.txt");
$zip->close();
echo "ZIP file '$filename' created successfully.";
} else {
echo "Error creating ZIP file '$filename'.";
}
?>
Copy File
To copy a file, use the copy() function.
php
<?php
$source = 'example.txt';
$destination = 'copy_of_example.txt';
if (copy($source, $destination)) {
echo "File copied from '$source' to '$destination'.";
} else {
echo "Error copying file from '$source' to '$destination'.";
}
?>
Summary of File Operations
Create File: fopen($filename, 'w')
Append Data to File: fopen($filename, 'a') + fwrite()
Read File: fopen($filename, 'r') + fread(), or file_get_contents()
Write File: fopen($filename, 'w') + fwrite()
Rename File: rename($oldName, $newName)
ZIP File: ZipArchive class
Copy File: copy($source, $destination)
These examples provide a comprehensive guide to performing common file operations in PHP

UNIT 3: PERFORM PHP MYSQLI BATABASE INTERACTION


3.1 CONNECT AND ACCESS MYQSLI DATABASE
 MYSQLI_CONNECTION
PHP mysqli_connect()

PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if
connection is established or null.

Syntax
1. resource mysqli_connect (server, username, password)

PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.

Syntax
mysqli_close() ;

 MYSQLi CREATE DB

PHP MySQLi Create Database Example

Example
1. <?php
2. $host = 'localhost';
3. $user = ' ';
4. $pass = ' ';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>

PHP MySQLi Create Table Example

Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NU
LL, emp_salary INT NOT NULL,primary key (id))";
14. if(mysqli_query($conn, $sql)){
15. echo "Table emp5 created successfully";
16. }else{
17. echo "Could not create table: ". mysqli_error($conn);
18. }
19. mysqli_close($conn);
20. ?>

PHP MySQLi Insert Record Example

Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>

PHP MySQLi Update Record Example

Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>

PHP MySQLi Delete Record Example

Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20. mysqli_close($conn);
21. ?>

There are two other MySQLi functions used in select query.

 mysqli_num_rows(mysqli_result $result): returns number of rows.

 mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each


key of the array represents the column name of the table. It return NULL if there are no
more rows.

PHP MySQLi Select Query Example


Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6. $conn = mysqli_connect($host, $user, $pass,$dbname);
7. if(!$conn){
8. die('Could not connect: '.mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'SELECT * FROM emp4';
13. $retval=mysqli_query($conn, $sql);
14.
15. if(mysqli_num_rows($retval) > 0){
16. while($row = mysqli_fetch_assoc($retval)){
17. echo "EMP ID :{$row['id']} <br> ".
18. "EMP NAME : {$row['name']} <br> ".
19. "EMP SALARY : {$row['salary']} <br> ".
20. "--------------------------------<br>";
21. } //end of while
22. }else{
23. echo "0 results";
24. }
25. mysqli_close($conn);
26. ?>

3.2 : Implement database CRUD operations


 PHP MYSQLI INSERT

MySQL INSERT statement is used to store or add data in MySQL table within the database. We
can perform insertion of records in two ways using a single query in MySQL:
1. Insert record in a single row
2. Insert record in multiple rows

PHP MySQLi Insert Record Example

Example
22. <?php
23. $host = 'localhost';
24. $user = ' ';
25. $pass = ' ';
26. $dbname = 'test';
27.
28. $conn = mysqli_connect($host, $user, $pass,$dbname);
29. if(!$conn){
30. die('Could not connect: '.mysqli_connect_error());
31. }
32. echo 'Connected successfully<br/>';
33.
34. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
35. if(mysqli_query($conn, $sql)){
36. echo "Record inserted successfully";
37. }else{
38. echo "Could not insert record: ". mysqli_error($conn);
39. }
40.
41. mysqli_close($conn);
42. ?>
 PHP MYSQLI UPDATE

MySQL UPDATE Query

MySQL UPDATE query is a DML statement used to modify the data of the MySQL table within
the database. In a real-life scenario, records are changed over a period of time. So, we need to
make changes in the values of the tables also. To do so, it is required to use the UPDATE query.

The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to
change the values of the specified column. We can update single or multiple columns at a time.
PHP MySQLi Update Record Example

Example
25. <?php
26. $host = 'localhost';
27. $user = ' ';
28. $pass = ' ';
29. $dbname = 'test';
30.
31. $conn = mysqli_connect($host, $user, $pass,$dbname);
32. if(!$conn){
33. die('Could not connect: '.mysqli_connect_error());
34. }
35. echo 'Connected successfully<br/>';
36.
37. $id=2;
38. $name="Rahul";
39. $salary=80000;
40. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
41. if(mysqli_query($conn, $sql)){
42. echo "Record updated successfully";
43. }else{
44. echo "Could not update record: ". mysqli_error($conn);
45. }
46.
47. mysqli_close($conn);
48. ?>

 PHP MYSQLI DELETE

MySQL DELETE Statement

MySQL DELETE statement is used to remove records from the MySQL table that is no longer
required in the database. This query in MySQL deletes a full row from the table and
produces the count of deleted rows. It also allows us to delete more than one record from the
table within a single query, which is beneficial while removing large numbers of records from a
table. By using the delete statement, we can also remove data based on conditions.
PHP MySQLi Delete Record Example

Example
22. <?php
23. $host = 'localhost';
24. $user = ' ';
25. $pass = ' ';
26. $dbname = 'test';
27.
28. $conn = mysqli_connect($host, $user, $pass,$dbname);
29. if(!$conn){
30. die('Could not connect: '.mysqli_connect_error());
31. }
32. echo 'Connected successfully<br/>';
33.
34. $id=2;
35. $sql = "delete from emp4 where id=$id";
36. if(mysqli_query($conn, $sql)){
37. echo "Record deleted successfully";
38. }else{
39. echo "Could not deleted record: ". mysqli_error($conn);
40. }
41. mysqli_close($conn);
42. ?>
 PHP MYSQLSELECT

MySQL SELECT Statement

The SELECT statement in MySQL is used to fetch data from one or more tables. We can
retrieve records of all fields or specified fields that match specified criteria using this statement.

There are two other MySQLi functions used in select query.

 mysqli_num_rows(mysqli_result $result): returns number of rows.


 mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each
key of the array represents the column name of the table. It return NULL if there are no
more rows.

PHP MySQLi Select Query Example

Example
27. <?php
28. $host = 'localhost';
29. $user = ' ';
30. $pass = ' ';
31. $dbname = 'test';
32. $conn = mysqli_connect($host, $user, $pass,$dbname);
33. if(!$conn){
34. die('Could not connect: '.mysqli_connect_error());
35. }
36. echo 'Connected successfully<br/>';
37.
38. $sql = 'SELECT * FROM emp4';
39. $retval=mysqli_query($conn, $sql);
40.
41. if(mysqli_num_rows($retval) > 0){
42. while($row = mysqli_fetch_assoc($retval)){
43. echo "EMP ID :{$row['id']} <br> ".
44. "EMP NAME : {$row['name']} <br> ".
45. "EMP SALARY : {$row['salary']} <br> ".
46. "--------------------------------<br>";
47. } //end of while
48. }else{
49. echo "0 results";
50. }
51. mysqli_close($conn);
52. ?>

You might also like