Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Web Appilications Development using PHP & MYSQL

PHP INTRODUCTION:

PHP, which stands for Hypertext Preprocessor, is a popular programming language used for web
development. Here are some key points about PHP in simple terms:
1. Purpose: PHP is mainly used to create dynamic and interactive websites.
It can generate dynamic page content, interact with databases, handle forms, manage
cookies, and more.

2. Server-Side Scripting: PHP is a server-side scripting language.


This means the PHP code is executed on the server where your website is hosted, not on the
user's browser.
The server processes the PHP code and sends the resulting HTML to the user's browser, which the
browser then displays.

3. Integration: PHP can be integrated with various databases like MySQL, PostgreSQL, SQLite,
etc., to store and retrieve data. It can also be used with other technologies such as HTML, CSS, and
JavaScript to create complete web applications.

4. Syntax: PHP syntax is similar to C, Java, and Perl, making it relatively easy to learn if you're
familiar with any of these languages.
It uses <?php ... ?> tags to enclose its code, which can be embedded directly into HTML or used to
generate HTML dynamically.

5. Open Source: PHP is open-source, meaning it's free to use and widely supported by a large
community of developers.

Overall, PHP is valued for its simplicity, flexibility, and capability to handle a wide range of web
development tasks, from small personal websites to large-scale enterprise applications.

Charactersitics of php:
Five important characteristics make PHP's practical nature possible:
 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

Variables:
Variables are used allows programmers to store, manipulate, and retrieve values or information
within a program. Variables can hold different types of data such as numbers, text, boolean values
(true or false), arrays (collections of data), and more complex structures.
* A variable in PHP is denoted with a dollar sign ($) followed by the variable name.
For example: $name or $age.
* In php you don't need to declare the data type when you create a variable. PHP automatically
assigns the data type based on the value assigned to it.
* Must start with a letter or underscore
Example:
$name = "John";
$age = 30;
$isStudent = true;
PHP variables can be one of four scope types:
 Local variables
 Function parameters
 Global variables
 Static variables
Local variable
The variables that are declared within a function are called local variables for that function. These
local variables have their scope only in that particular function in which they are declared. This
means that these variables cannot be accessed outside the function, as they have local scope.
EXAMPLE:
<?php

function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output;
Local variable declared inside the function is: 45
Global variable
The global variables are the variables that are declared outside the function. These variables can be
accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to access
a global variable outside the function.
Example:
<?php

$name = "Sanaya Sharma"; //global variable


function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
output:
Variable inside the function: Sanaya Sharma
Static variable:
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
example:
function myTest() {
static $x = 0;
echo $x; $x++;
}
myTest();
myTest();
myTest();
output:0
1
2

PHP Data Types


Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:

•String
•Integer
•Float (floating point numbers - also called double)
•Boolean
•Array
•Object
•NULL
•Resource

PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes
exapmle:$x = "Hello world!";
$y = 'Hello world!';

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.


Rules for integers:
•An integer must have at least one digit
•An integer must not have a decimal point
•An integer can be either positive or negative
In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:

Example

$x = 5985;

var_dump($x);

PHP Float
• A float (floating point number) is a number with a decimal point or a number in exponential
form.
• In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
example: $x = 10.365;
var_dump($x);
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing
example: $x = true;
var_dump($x);
PHP Array:
• An array stores multiple values in one single variable.
• In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
example:$cars = array("Volvo","BMW","Toyota");
var_dump($cars);A

Object:
An object type is an instance of a programmer-defined class, which can package up both other kinds
of values and functions that are specific to the class.
To create a new object, use the new statement to instantiate a class −
class foo
{
function bar()
{
echo "Hello World.";
}
}
$obj = new foo;
$obj->bar();
NULL Value:
• 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.
• If a variable is created without a value, it is automatically assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:
$x = "Hello world!";
$x = null;
var_dump($x);

output:NULL

Resource Data Type in PHP

Resources are special variables that hold references to resources external to PHP (such as a file
stream or database connections).
Here is an example of file resource −

example:$fp = fopen("foo.txt", "w");


Data belonging to any of the above types is stored in a variable. However, since PHP is a
dynamically typed language, there is no need to specify the type of a variable, as this will be
determined at runtime.

Operators:

What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands
and + is called operator. PHP language supports following type of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
ArithmeticOperators
The following arithmetic operators are supported by PHP language: Assume variable A holds 10
and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand A - B will give -10
from the first
Multiply both operands
* A * B will give 200
Divide the numerator by
denominator
/ B / A will give 2

Modulus Operator and


% B % A will give 0
remainder
of after an integer division

Increment operator,
++ A++ will give 11
increases integer value by one

Decrement operator, decreases


integer value by one
-- A-- will give 9

Example:

<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>d able has not been assigned any value yet. Example: $variable =
Comparsion operator:::

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
Returns true if $x is equal to $y, and they are of the same
=== Identical $x === $y
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
Returns true if $x is not equal to $y, or they are not of the
!== Not identical $x !== $y
same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
Greater than
>= $x >= $y Returns true if $x is greater than or equal to $y
or equal to
Less than or
<= $x <= $y Returns true if $x is less than or equal to $y
equal to
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero,
depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.

Example:
<?php
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");

switch ("a") {
case 0:
echo "0";
break;
case "a":
echo "a";
break;
}
?>

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

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
Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result


Returns the value of $x.
$x
?: Ternary The value of $x is expr2 if expr1 = TRUE.
= expr1 ? expr2 : expr3
The value of $x is expr3 if expr1 = FALSE
Returns the value of $x.
The value of $x is expr1 if expr1 exists, and is
Null not NULL.
?? $x = expr1 ?? expr2
coalescing If expr1 does not exist, or is NULL, the value of
$x is expr2.
Introduced in PHP 7

Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Create a constant with the const keyword:


const MYCAR = "Volvo";
echo MYCAR;
FLOW CONTROL FUNCTIONS:
Flow control functions in PHP are used to manage the execution flow of a program based on certain
conditions. flow control functions in PHP are classified as followed
1.Conditional Statements:
if condition
The if statement executes some code if one condition is true.
Example
If (5 > 3) {
echo "Have a good day!";
}

• if...else: Executes different blocks of code based on whether a condition is true or


false.
Example:
$t = 30;
if ($t < 20)
{echo "Have a good day!";
} else
{ echo "Have a good night!";
}
• if..elseif..if condition
$t = 30;
if ($t < 10)
{
echo "Have a good morning!";
}
elseif ($t < 20)
{
echo"Haveagoodday!";
}
else
{
echo "Have a good night!";
}

Branching statment:
• switch: Evaluates an expression against multiple possible values and executes the
corresponding block of code for the first match.
• The switch statement is used to perform different actions based on different
conditions
This is how it works:
i. The expression is evaluated once
ii. The value of the expression is compared with the values of each case
iii. If there is a match, the associated block of code is executed
iv. The break keyword breaks out of the switch block
v. The default code block is executed if there is no match
example:

$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break; case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}

2. Looping Statements:
Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script, we
can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is
true.
In PHP, we have the following loop types:
• while: Executes a block of code as long as a specified condition is true.
Example: $i = 1;
while ($i < 6)
{
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true.

• do...while: Similar to while, but guarantees the block of code is executed at least
once before checking the condition.
The do...while loop - Loops through a block of code once, and then repeats the loop
as long as the specified condition is true.
Example;$i = 1;
do
{
echo $i;
$i++;
}
while ($i < 6);
• for: Executes a block of code a specified number of times, with control over
initialization, condition, and incrementation.
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iteration
• expression3 is evaluated after each iteration
example:for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
• foreach: Iterates over arrays and objects, executing a block of code for each element.
The most common use of the foreach loop, is to loop through the items of
an array.
Loop through the items of an indexed array
example:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x)
{
echo "$x <br>";
}

3. Jump Statements:
• break: Terminates the current loop or switch statement and transfers control to the
statement immediately following the terminated statement.
Example:
for ($x = 0; $x <= 10; $x++)
{
if($x= =3) break;
echo "The number is: $x <br>";
}

• continue: Skips the rest of the current loop iteration and continues with the next
iteration.
Example:
for ($x = 0; $x <= 10; $x++)
{
if($x= =3) continue;
echo "The number is: $x <br>";
}
CODE BLOCK:
In PHP, a code block refers to a group of statements that are enclosed within curly braces {}.
These blocks are used to group together multiple statements that should be treated as a single unit
for control structures like functions, loops, conditional statements, classes, and more. Here's a
simple and clear explanation of code blocks in PHP
Key Points:
• Syntax: Code blocks in PHP are enclosed within curly braces {}.
• Purpose: They group multiple statements into a single unit for control structures like
functions, loops, conditional statements, and classes.
• Execution: The statements within a code block are executed sequentially whenever the
enclosing structure (function, loop, etc.) is executed.
Understanding code blocks in PHP is fundamental to organizing and controlling the flow of
execution within your scripts, making them clearer and easier to maintain.
FUNCTIONS:
• The real power of PHP comes from its functions.
• PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.
• a function is a block of reusable code that performs a specific task
• They encapsulate a set of instructions that can be called multiple times within a PHP script,
promoting code reusability and modularity.
• Functions are defined using the function keyword followed by a name and parentheses
()

• Key Concepts of Functions in PHP


1. Reusability: Functions allow you to define logic once and reuse it throughout your
application, reducing code duplication.
2. Modularity: Functions promote modular programming by encapsulating specific tasks or
operations into manageable units.
3. Parameters: Functions can accept input values (parameters) which allow them to be more
flexible and customizable based on different inputs.
4. Return Values: Functions can optionally return a value back to the calling code using the
return statement. This value can be assigned to variables or used directly in the script.
5. Scope: Variables declared inside a function are local to that function by default, meaning
they cannot be accessed outside the function unless explicitly returned.
Functions are fundamental building blocks in PHP programming, enabling developers to organize
code effectively, improve maintainability, and create more scalable applications.
Types of functions:
PHP Built-in Functions
• PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.
• Please check out our PHP reference for a complete overview of the PHP
built-in functions.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.
•A function is a block of statements that can be used repeatedly in a program.
•A function will not execute automatically when a page loads.
•A function will be executed by a call to the function.

Create a Function
A user-defined function declaration starts with the keyword function, followed by the name
of the function.
EXAMPLE:
function myMessage()
{
echo "Hello world!";
}

Call a Function
To call the function, just write its name followed by parentheses ():
EXAMPLE:
function myMessage()
{
echo "Hello world!";
}
myMessage() //calling function
Arguments:
In PHP, arguments (also referred to as parameters) are values that you pass to a function when you
call it. They allow you to provide input to the function, which the function can then use to perform
its tasks or calculations. Understanding how arguments work in PHP is crucial for creating flexible
and reusable functions.
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When
the familyName() function is called, we also pass along a name, e.g. ("Jani"), and the name is used
inside the function, which outputs several different first names, but an equal last name:
example:
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("KaiJim");

Default Argument Value


The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:
example:
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default valueof 50
setHeight(135);
setHeight(80);
NULL: Represents a variable with no value. It is typically used to indicate that a variable has not
been assigned any value yet. Example: $variable = NULL; Objects are also known as instances.
An Object is an individual instance of the data structure defined by a class. We
define a class once and then make many objects that belong to it. Objects are
also known as instances
An Object is an individual instance of the data structure defined by a class. We
define a class once and then make many objects that belong to it. Objects are
also known as instances.
An Object is an individual instance of the data structure defined by a class. We
define a class once and then make many objects that belong to it. Objects are
also known as instances.

You might also like