0% found this document useful (0 votes)
6 views179 pages

PHP Notes Detailed

The document provides a comprehensive overview of variables in PHP, including how to declare them, the rules governing their usage, and the various types of variables such as strings, integers, and arrays. It also discusses automatic type conversion, variable assignment by value and reference, and the scope of variables. Additionally, it explains the differences between the echo and print statements for outputting data, as well as the classification of data types in PHP.

Uploaded by

senore6051
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views179 pages

PHP Notes Detailed

The document provides a comprehensive overview of variables in PHP, including how to declare them, the rules governing their usage, and the various types of variables such as strings, integers, and arrays. It also discusses automatic type conversion, variable assignment by value and reference, and the scope of variables. Additionally, it explains the differences between the echo and print statements for outputting data, as well as the classification of data types in PHP.

Uploaded by

senore6051
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 179

Variables in PHP

Variables in PHP are used to store data that can be accessed and modified across the
program. A variable can store a wide range of values, like numbers, text, arrays and even
objects. One of PHP's unique features is that it is a loosely typed language, which means
you are not required to declare the data type of a variable when you create it. PHP
defines the variable's type based on the value assigned to it.

This freedom makes PHP easier to use, particularly for beginners, because it allows you to
store and manage a variety of data types without having to design them yourself.

Table of Content
 How to Declare a Variable in PHP?
 PHP Variable Rules
 Variable Types in PHP
 Automatic Type Conversion of Variables
 Variables are Assigned by Value
 Assigning Values to PHP Variables by Reference
 Variable Scope

How to Declare a Variable in PHP?


To declare a variable in PHP, just assign a value by typing the $ symbol followed by the
variable name. PHP variables are case-sensitive and should begin with a letter or an
underscore, followed by any number of letters, numbers or underscores.

Syntax

$variable_name = value;

Example
Here is an example showing how to declare variables in PHP −

// A string value
$name = "John";

// A number (integer)
$age = 25;

// A decimal number (float)


$price = 12.50;

PHP Variable Rules


Here is the list of rules to define a variable in PHP −

 A variable must start with a $ symbol, then its name.


 The variable name must start with a letter or underscore (_).
 A variable name cannot start with a number.
 The variable name can contain letters, digits or underscores.
 PHP is case sensitive, so $Name and $name are distinct variables.

Example
See the below example showing how both the variables $Name and $name are different
to each other and see the output of the code.

$Name = "Amit";
$name = "Samay";
echo $Name;
echo $name;

Output
Following is the result of the above code −

Amit
Samay

Variable Types in PHP


In PHP, the primary variable types are string, integer, float (also known as double),
Boolean, array, object, null, and resource. Below is the example of each type of variable.

 String : A sequence of characters.


 Integer : A whole number (without decimals).
 Float (Double) : A decimal number.
 Boolean : Represents true or false values.
 Array : Stores multiple values in one variable.
 NULL : Represents a variable with no value.

Automatic Type Conversion of Variables


PHP does a good job of automatically converting types from one to another when
necessary. In the following code, PHP converts a string variable "y" to "int" to perform
addition with another integer variable and print 30 as the result.

Take a look at this following example −

Open Compiler
<?php
$x = 10;
$y = "20";

echo "x + y is: ", $x+$y;


?>
Output
It will generate the following outcome −

x + y is: 30

Variables are Assigned by Value


In PHP, variables are always assigned by value. If an expression is assigned to a variable,
the value of the original expression is copied into it. If the value of any of the variables in
the expression changes after the assignment, it doesnt have any effect on the assigned
value.

Open Compiler
<?php
$x = 10;
$y = 20;
$z = $x+$y;
echo "(before) z = ". $z . "\n";

$y=5;
echo "(after) z = ". $z . "";
?>

Output
It will produce the below result −

(before) z = 30
(after) z = 30

Assigning Values to PHP Variables by Reference


You can also use the way to assign values to PHP variables by reference. In this case, the
new variable simply references or becomes an alias for or points to the original variable.
Changes to the new variable affect the original and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable
which is being assigned (the source variable).

Take a look at this following example −

Open Compiler
<?php
$x = 10;
$y = &$x;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "\n";
$y=20;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "";
?>

Output
It will produce the following output −

x=10 y=10 z = 20
x=20 y=20 z = 40

Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it
is declared. PHP variables can be one of four scope types −

 Local Variables
 Global Variables
 Static Variables
 Function Parameters

PHP echo and print statements

PHP uses the echo and print statements to display output in the browser or the PHP
console. Both are language structures rather than functions, indicating that they are part
of the PHP language. As a result, using parentheses is optional. These instructions are
commonly used to display text, numbers, variables and even HTML content directly on a
website. While they serve the same purpose there are some small differences between
them. Echo can accept several parameters and is faster than print, which returns a result
of 1, making it suitable to use in expressions.

What is Echo?
Echo is a PHP statement that displays data. It does not return a value but can produce
multiple values at once.

Syntax
The echo statement is used with following syntax −
echo(string ...$expressions): void

The echo statement outputs one or more expressions, with no additional newlines or
spaces.

Basic Usage of echo in PHP


Here is an example of how the echo statement works in PHP −
Open Compiler
<?php
$name = "Rahul";
echo "Hello " . $name . " How are you?"
?>

Output
It will produce the below outcome −

Hello Rahul How are you?

Using Single-Quoted String in echo


Since a double quoted string is similar to a single quoted string in PHP, the following
statement produces the same output.

Open Compiler
<?php
echo 'Hello ' . $name . ' How are you?';
?>

Using Double-Quoted String in echo


A double quoted string outputs the value of the variable. Hence, the following statement
inserts the value of "$name" variable before printing the output.

Open Compiler
<?php
$name = "Rahul";
echo "Hello $name How are you?";
?>

Output
It will produce the following result −

Hello Rahul How are you?

Single-Quoted String Treats Variables as Plain Text


But, a single-quoted string will output "$name" as it is.

Open Compiler
<?php
$name = "Rahul";
echo 'Hello $name How are you?';
?>
Output
It will produce the following output −

Hello $name How are you?

Passing Multiple Arguments in echo


A string passed to an echo statement can either be passed individually as multiple
arguments or concatenated together and passed as a single argument. So, both the
following statements are valid −

Open Compiler
<?php
echo 'Hello ', 'how ', 'are ', 'you?', "\n";
echo 'Hello ' . 'how ' . 'are ' . 'you?' . "\n";
?>

Output
Here is the output of the above example −

Hello how are you?


Hello how are you?

Successive echo Statements Without a Newline


Note that output of the two successive echo statements will be rendered in the same line
if the newline character is not used. Take a look at the following example −

Open Compiler
<?php
echo "hello";
echo "world";
?>

Output
It will generate the below result −

helloworld
Advertisement

-
Advertisement: 0:16

What is Print?
The PHP print statement is the same as the echo statement and can be used to replace it
several times. It is also a language construct, thus we can not use parenthesis, like print
or print().

The major difference is that the print statement in PHP accepts a single argument only
and always returns 1.

Syntax
The print statement is similar to echo, but it outputs an expression. Check the syntax
below −

print(string $expression): int

Basic Usage of print in PHP


Take a look at the basic usage of the print in PHP −

Open Compiler
<?php
$name = "Rajesh";

print "Hello " . $name . " How are you?\n";


print "Hello $name How are you?";
?>

Output
Following is the output of the above code −

Hello Rajesh How are you?


Hello Rajesh How are you?

Output Multiline Strings Using Print


Both echo and print statements can output multiline strings spanning over more than one
lines in the editor. Take a look at the following example −

Open Compiler
<?php
print "
Multi-line
string can be output
by echo as well as
print statement in PHP
";
?>
Output
This will create the below output −

Multi-line
string can be output
by echo as well as
print statement in PHP

The output will remain the same if we replace print with echo.

Echo vs Print: Key Differences


Below are the key differences of echo and print in a tabular form −

Feature Echo Print

Speed Faster Slower

Return Value No Yes (1)

Multiple Arguments Yes No

When to Use Echo or Print?


In most cases, use "echo" over "print" in PHP as it is considered to be faster, can output
multiple strings at once separated by commas and does not return a value, making it
more efficient for simple text display; whereas "print" is better suited for situations where
a return value is required within an expression because of its "1" return value and can
only output a single string at a time.

Conclusion
Both echo and print are effective methods for presenting data in PHP. Echo is frequently
preferred for faster performance, but print is useful when a return value is necessary.

The term "Data Types" refers to the classification of data in distinct categories in PHP.
Data types define the types of data that a variable can store.

PHP supports a wide range of data types, like string, integer, float etc. Data types make it
easier to store and handle information in programs. Knowing data types is important for
writing correct and clear code.

List of Data Types


PHP has a total of eight data types that we use to construct our variables −
 Integers − Whole numbers, without a decimal point, like 4195.
 Doubles − Floating-point numbers like 3.14159 or 49.1.
 Booleans − Have only two possible values, either true or false.
 NULL − Special type that only has one value: NULL.
 Strings − Sequences of characters, like 'PHP supports string operations.'
 Arrays − Named and indexed collections of other values.
 Objects − Instances of programmer-defined classes, which can package up both
other kinds of values and functions that are specific to the class.
 Resources − Special variables that hold references to resources external to PHP
(such as database connections).

The first five are simple types, and the next two (arrays and objects) are compound types.
The compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.

In this chapter, let's discuss in detail about these built-in data types of PHP.

Advertisement

-
PauseSkip backward 5 secondsSkip forward 5 seconds
Mute

Fullscreen

Integer Data Type in PHP


A whole number without a decimal point (like 4195) is of int type in PHP. Integer data
types are the simplest type. They correspond to simple whole numbers, both positive and
negative.

 An int is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.


 An int can be represented in a decimal (base 10), hexadecimal (base 16), octal
(base 8) or binary (base 2) notation.

To use octal notation, a number is preceded with "0o" or "0O". To use hexadecimal
notation, precede the number with "0x". To use binary notation, precede the number with
"0b".

Given below are some examples −

 Decimal Integer − 201, 4195, -15


 Octal Integer − 0o10, 0o12, -0o21
 Hexadecimal Integer − 0x10, -0x100
 Binary Integer − 0b10101, -0b100

Integers can be assigned to variables, or they can be used in expressions, like so −

$int_var = 12345;
$another_int = -12345 + 12345;

Double Data Type in PHP


Double variables represent floating point numbers (also known as "floats", "doubles", or
"real numbers") that are the numbers with a fractional component. The fractional
component follows after the integer component separated by the decimal symbol (.)

Note − A double variable can be positive, negative, or zero.

$var1 = 1.55;
$var2 =-123.0;

Scientific Float Notation


PHP also allows the use of scientific notation to represent a floating point number with
more digits after the decimal point. The symbol "E" or "e" is used to separate the integer
and fractional part.

- 1.2e3, 2.33e-4, 7E-10, 1.0E5

By default, doubles print with the minimum number of decimal places needed. Take a
look at the following example −

Open Compiler
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;

print("$many + $many_2 = $few");


?>

It produces the following output −

2.28888 + 2.21112 = 4.5

Boolean Data Type in PHP


The bool type has only two values; it can either be True or False. The bool type is used
to express a truth value.

$bool1 = true;
$bool2 = false;

You can also use the integer values "1" and "0" to represent True and False Boolean
values −

$bool3 = 1;
$bool4 = 0;

Typically, the result of an operator which returns a bool value is passed on to a control
structure such as if, while or do-while. For example,

if (TRUE)
print("This will always print.");

else
print("This will never print.");
Interpreting Other Data Types as Booleans
Here is a set of rules that you can use to interpret other data types as Booleans −

 If the value is a number, then it is False only if the value is equal to zero, otherwise
the value is True.
 If the value is a string, it is False if the string is empty (has zero characters) or is the
string "0", and is True otherwise.
 The values of type NULL are always False.
 If the value is an array, it is False if it contains no other values; True otherwise. For
an object, containing a value means having a member variable that has been
assigned a value.
 Valid resources are true (although some functions that return resources when they
are successful will return FALSE when unsuccessful).

Note − Do not use floating-point numbers (doubles) as Boolean values.

Each of the following variables has the truth value embedded in its name when it is used
in a Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

String Data Type in PHP


A string is a sequence of characters, for example, 'PHP supports string operations.'

In PHP, a character is the same as a byte. It means PHP only supports a 256 character set,
and hence does not offer native Unicode support.

PHP supports single-quoted as well as double-quoted string formation. Both the following
representations are valid in PHP −

$string_1 = "This is a string in double quotes";


$string_2 = 'This is a somewhat longer, singly quoted string';

Here are some more examples of string type −

$string_39 = "This string has thirty-nine characters";


$string_0 = ""; // a string with zero characters

Single-quoted strings are treated almost literally, whereas double-quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

Open Compiler
<?php
$variable = "name";
$literally = 'My $variable will not print!';

print($literally);
print "\n";

$literally = "My $variable will print!";


print($literally);
?>

When you run this code, it will produce the following output −

My $variable will not print!


My name will print

There are no artificial limits on string length. Within the bounds of available memory, you
ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −

 Certain character sequences beginning with backslash (\) are replaced with special
characters.
 Variable names (starting with $) are replaced with string representations of their
values.

The escape-sequence replacements are −

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

PHP also has Heredoc and Nowdoc representations of string data type.

Heredoc Representation of String Data Type


You can assign multiple lines to a single string variable using heredoc −

<?php
$channel =<<<XML

<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/ </link>
<description>Choose what to eat tonight.</description>
</channel>
XML;

echo <<< END


This uses the "here document" syntax to output multiple lines with
variable interpolation. Note that the here document terminator must
appear on a line with just a semicolon. no extra whitespace!
END;

print $channel;
?>

When you run this code, it will produce the following output −

This uses the "here document" syntax to output


multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/ </link>
<description>Choose what to eat tonight.</description>
</channel>

Nowdoc Representation of String Data Type


All the rules for heredoc identifiers also apply to nowdoc identifiers. A nowdoc is
specified just like a heredoc, but there is no parsing inside a nowdoc. You can use the
nowdoc construct for embedding large blocks of text without having to use any escape
characters.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier
is enclosed in single quotes, e.g. <<<'EOT'. Nowdocs apply to single-quoted strings just
the way heredocs apply to double-quoted strings.

Take a look at the following example −

Open Compiler
<?php
echo <<<'IDENTIFIER'
As the cat cleared its throat with a refined "Meow",
the squirrel chirped excitedly about its latest
discovery of a hidden stash of peanut treasure!
IDENTIFIER;
?>

Run the code and check its output −


As the cat cleared its throat with a refined "Meow",
the squirrel chirped excitedly about its latest
discovery of a hidden stash of peanut treasure!

Null Data Type in PHP


In PHP, null represents a special type that only has one value: NULL. Undefined and
unset() variables will have the value NULL.

Programmers normally use the Null data type in PHP to initialize variables or to indicate
that a value is missing.

To give a variable the NULL value, simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case


insensitive; you could just as well have typed −

$my_var = null;

A variable that has been assigned NULL has the following properties −

 It evaluates to FALSE in a Boolean context.


 It returns FALSE when tested with IsSet() function.

Note − The data types of variables in PHP are determined at runtime based on the values
that are assigned to them.

Array Data Type in PHP


An array in PHP is an ordered map, a key is associated with one or more values. A PHP
array is defined using the array() function, or with the use of a short notation where the
data is put in square brackets.

Take a look at the following examples of associative arrays −

Using the array() Function

$arr = array(
"foo" => "bar",
"bar" => "foo",
);

Using the Short Notation

$arr = [
"foo" => "bar",
"bar" => "foo",
];

An array in PHP can also be defined with the "key-value pair" syntax. It is called
an indexed array.

$arr = array("foo", "bar", "hello", "world");

In a multi-dimensional array, each element in the main array can also be an array.
And, each element in the sub-array can be an array, and so on. Values in the multi-
dimensional array are accessed using multiple index.

Note − In PHP, compound data types are used to store collections of data, including
arrays and objects.

Object Data Type in PHP


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();

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 −

$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.

Example: The gettype() Function


The gettype() function is helpful to find out the type of data stored in a variable −

Open Compiler
<?php
$x = 10;
echo gettype($x) . "\n";
$y = 10.55;
echo gettype($y) . "\n";

$z = [1,2,3,4,5];
echo gettype($z);
?>

When you run this code, it will produce the following output −

integer
double
array

Type Casting
The term "Type Casting" refers to conversion of one type of data to another. Since PHP is
a weakly typed language, the parser coerces certain data types into others while
performing certain operations. For example, a string having digits is converted to integer
if it is one of the operands involved in the addition operation.

Table of Content
 Implicit Type Casting
 Type Casting Operators
 Casting to Integer
 Casting to Float Type
 Casting to String Type
 Casting to Bool Type
 Type Casting Functions
Advertisement

-
PauseSkip backward 5 secondsSkip forward 5 seconds
Mute

Fullscreen

Implicit Type Casting


Here is an example of coercive or implicit type casting −

Open Compiler
<?php
$a = 10;
$b = '20';
$c = $a+$b;
echo "c = " . $c;
?>
In this case, $b is a string variable, cast into an integer to enable addition. It will produce
the following output −

c = 30

Let's take another example. Here, an integer variable $a is converted to a string so that it
is concatenated with a string variable.

Open Compiler
<?php
$a = 10;
$b = '20';
$c = $a.$b;
echo "c = " . $c;
?>

It will produce the following output −

c = 1020

In addition to such coercive type conversion, there are other ways to explicitly cast one
type of data to other. You can use PHPs type casting operators or type casting functions
for this purpose.

Type Casting Operators


To convert an expression of one type to another, you need to put the data type of the
latter in parenthesis before the expression.

$var = (type)expr;

Some of the type casting operators in PHP are −

 (int) or (integer) casts to an integer


 (bool) or (boolean) casts to a boolean
 (float) or (double) or (real) casts to a float
 (string) casts to a string
 (array) casts to an array
 (object) casts to an object

Casting to Integer
You can easily convert a float value to an integer. Take a look at the following example −

Open Compiler
<?php
$a = 9.99;
$b = (int)$a;
var_dump($b);
?>
It will produce the following output −

int(9)

Note that the float value is not rounded to the nearest integer; instead it just returns the
integer part.

String to Integer Conversion


The (int) operator also coverts a string to integer. The conversion is straightforward if the
string consists of just digits.

Open Compiler
<?php
$a = "99";
$b = (int)$a;
var_dump($b);
?>

Here, you will get the following output −

int(99)

Even if the string contains a floating point number, the (int) operator returns just the
integer part.

Now let's take another example to understand a special case. If the string is
alphanumeric, casting with (int) works differently.

 If the string starts with digits followed by non-numeric characters, only the initial
digits are considered.
 If the string starts with non-numeric characters and the digits are in the middle, the
csting operator returns "0".

Take a look at the following example −

Open Compiler
<?php
$a = "10 Rs.";
$b = (int)$a;
var_dump($b);

$a = "$100";
$b = (int)$a;
var_dump($b);
?>

It will produce the following output −

int(10)
int(0)

Casting to Float Type


You can use either the (float) or (double) casting operator to explicitly convert a variable
or expression to a float.

Open Compiler
<?php
$a = 100;
$b = (double)$a;
var_dump($b);
?>

It will produce the following output −

float(100)

A string containing any valid numeric representation may be cast to a float type by using
a casting operator.

Open Compiler
<?php
$a = "100";
$b = (double)$a;
var_dump($b);

$a = "9.99";
$b = (float)$a;
var_dump($b);
?>

Here, you will get the following output −

float(100)
float(9.99)

The string gets converted to float even when it embeds a scientific notation of float. Take
a look at the following example −

Open Compiler
<?php
$a = "1.23E01";
$b = (double)$a;
var_dump($b);
$a = "5.5E-5";
$b = (float)$a;
var_dump($b);
?>

It will produce the following output −

float(12.3)
float(5.5E-5)

All the non-numeric characters after the floating point numbers are ignored. Similarly, the
string converts to "0" if it starts with any non-numeric character. See the
following example −

Open Compiler
<?php
$a = "295.95 only";
$b = (double)$a;
var_dump($b);

$a = "$2.50";
$b = (float)$a;
var_dump($b);
?>

It will produce the following output −

float(295.95)
float(0)

Casting to String Type


By using a casting operator, any expression evaluating to a floating-point or integer may
be cast to a string type. Few examples are given below −

Open Compiler
<?php
$a = 100;
$b = (string)$a;
var_dump($b);

$x = 55.50;
$y = (string)$x;
var_dump($y);
?>

You will get the following output −

string(3) "100"
string(4) "55.5"
Casting to Bool Type
Any non-zero number, either integer or float, is cast to true with (bool) operator. An
expression evaluating to "0" returns false. A string is always cast to true.

Take a look at the following example −

Open Compiler
<?php
$a = 100;
$b = (bool)$a;

$x = 0;
$y = (bool)$x;

$m = "Hello";
$n = (bool)$m;

var_dump($b);
var_dump($y);
var_dump($n);
?>

It will produce the following output −

bool(true)
bool(false)
bool(true)

Type Casting Functions


PHP includes the following built-in functions for performing type casting −

 intval()
 floatval()
 strval()

Let's discuss these built-in functions in detail.

The intval() Function


This function gets the integer value of a variable.

intval(mixed $value, int $base = 10): int

The $base parameter is 10 by default, which means the value is converted to decimal
number.
 If the value is a float, the intval() function returns an integer, discarding the
fractional part.
 A string representation of a number returns a corresponding integer, discarding the
fractional part, if any.
 If the value is a string with a valid octal number and the base is 8, the intval()
function returns a corresponding octal number.

When the base is "0", the conversion of value takes place on the basis of character
prefix.

 If the value starts with 0X or 0x, a hexadecimal number is returned.


 If the value starts with 0B or 0b, a binary number is returned
 If the value starts with 0, the function returns an octal number.

The intval() function returns 1 for true, 0 for false Boolean values.

Example
The following example shows how the intval() function works −

Open Compiler
<?php
echo intval(42). PHP_EOL;
echo intval(4.2). PHP_EOL;
echo intval('42') . PHP_EOL;

echo intval(042) . PHP_EOL; # 0ctal number


echo intval('042', 0) . PHP_EOL; # 0ctal number
echo intval('42', 8) . PHP_EOL; # octal

echo intval(0x1A) . PHP_EOL; # Hexadecimal


echo intval('0x1A', 16) . PHP_EOL; # Hexadecimal
echo intval('0x1A', 0) . PHP_EOL; # Hexadecimal

echo intval(false) . PHP_EOL;


echo intval(true) . PHP_EOL;
?>

It will produce the following output −

42
4
42
34
34
34
26
26
26
0
1

The floatval() Function


The floatval() function gets the float value of an expression.

floatval(mixed $value): float

The value may be any scalar variable. String with non-numeric characters returns "0". A
string with a numeric representation or with the starting substring with a numeric
representation returns the corresponding number. The following example shows how the
floatval() function works −

Open Compiler
<?php
echo floatval(42). PHP_EOL;
echo floatval(4.2). PHP_EOL;
echo floatval('42') . PHP_EOL;

echo floatval('99.90 Rs') . PHP_EOL;


echo floatval('$100.50') . PHP_EOL;
echo floatval('ABC123!@#') . PHP_EOL;

echo (true) . PHP_EOL; ;


echo (false) . PHP_EOL;
?>

It will produce the following output −

42
4.2
42
99.9
0
0
1

The doubleval() function is an alias of floatval() function, and hence returns similar
results.

The strval() Function


The strval() function gets the string value of a variable. This function performs no
formatting on the returned value.
strval(mixed $value): string

The value that is being converted to a string may be any scalar type, null, or an object
that implements the __toString() method. Take a look at the following example −

Open Compiler
<?php
echo strval(42). PHP_EOL;
echo strval(4.2). PHP_EOL;
echo strval(4.2E5) . PHP_EOL;

echo strval(NULL) . PHP_EOL;

echo (true) . PHP_EOL;


echo (false) . PHP_EOL;
?>

It will produce the following output −

42
4.2
420000

The following example defines a class that implements the _toString() method.

Open Compiler
<?php
class myclass {
public function __toString() {
return __CLASS__;
}
}
echo strval(new myclass);
?>

Here, you will get the following output −

myclass

PHP - Type Juggling


Previous
Quiz
Next

PHP is a dynamically typed language, which means the type of a variable can be changed
based on the value sent to it at runtime. This automatic type conversion in PHP is called
type juggling.

In languages like C, C++ and Java, a variable's type must be defined before it can be
used and it can only hold values of that type. But PHP handles type conversions
automatically, allowing variables to carry a wide range of values without the need for
explicit type declaration.

No Explicit Type Declaration in PHP


Explicit type declaration of a variable is neither needed nor supported in PHP. Hence the
type of PHP variable is decided by the value assigned to it, and not the other way around.
Further, when a variable is assigned a value of different type, its type too changes.

Example 1
Look at the following variable assignment in PHP.

Open Compiler
<?php
$var = "Hello";
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;

$var = 10;
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;

$var = true;
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;

$var = [1,2,3,4];
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
?>

Output
It will produce the following output −

The variable $var is of string type


The variable $var is of integer type
The variable $var is of boolean type
The variable $var is of array type

You can see the type of "$var" changes dynamically as per the value assigned to it. This
feature of PHP is called "type juggling".
Example 2
Type juggling also takes place during calculation of expression. In this example, a string
variable containing digits is automatically converted to integer for evaluation of addition
expression.

Open Compiler
<?php
$var1=100;
$var2="100";
$var3=$var1+$var2;
var_dump($var3);
?>

Output
Here is its output −

int(200)

Example 3
If a string starts with digits, trailing non-numeric characters if any, are ignored while
performing the calculation. However, PHP parser issues a notice as shown below −

Open Compiler
<?php
$var1=100;
$var2="100 days";
$var3=$var1+$var2;
var_dump($var3);
?>

Output
You will get the following result −

int(200)

PHP Warning: A non-numeric value encountered in


/home/cg/root/53040/main.php on line 4

Type Casting vs Type Juggling


In PHP, type juggling is the automatic changing of a variable's data type when necessary.
For example, adding an integer value to a variable makes it an integer. PHP handles this
automatically, with no user action required.
On the other hand, type casting occurs when a user actively changes a variable's data
type. This means that the user decides what type the variable should be and then
converts it using a specific method.

In simple terms, PHP automatically performs type juggling, while the programmer
performs type casting.

Example
Type casting forces a variable to be used as a certain type. The following script shows an
example of different type cast operators −

Open Compiler
<?php
$var1=100;
$var2=(boolean)$var1;
$var3=(string)$var1;
$var4=(array)$var1;
$var5=(object)$var1;
var_dump($var2, $var3, $var4, $var5);
?>

Output
It will generate the following outcome −

bool(true)
string(3) "100"
array(1) {
[0]=>
int(100)
}
object(stdClass)#1 (1) {
["scalar"]=>
int(100)
}

Example
Casting a variable to a string can also be done by enclosing in double quoted string −

Open Compiler
<?php
$var1=100.50;
$var2=(string)$var1;
$var3="$var1";
var_dump($var2, $var3);
?>

Output
Here, you will get the following result −

string(5) "100.5"
string(5) "100.5"

PHP Type Juggling Vulnerability


PHP Type Juggling vulnerability occurs when PHP automatically changes data types, which
can lead to security vulnerabilities. When comparing values, PHP tries to transform them
so they match, which can be dangerous if not done correctly.

For example, see the below code in PHP −

// It will be true as PHP ignores non-numeric part.


"123abc" == 123

This means that if your code checks a password or security token using == (double
equals), PHP can view two different responses as the same because of to type juggling.
Hackers can use this to get unauthorized access to your computer.

How to resolve This?


To avoid this issue we need to always use strict comparison (===), which checks both
value and type −

// This is false as the type is different.


"123abc" === 123

This makes sure that PHP does not change data types and makes your code more secure.

PHP Operators
Last Updated : 14 Jun, 2025


In PHP, operators are special symbols used to perform operations on


variables and values. Operators help you perform a variety of tasks, such as
mathematical calculations, string manipulations, logical comparisons, and
more. Understanding operators is essential for writing effective and efficient
PHP code. PHP operators are categorized into several types:
Let us now learn about each of these operators in detail.
1. Arithmetic Operators
Arithmetic operators are used to perform basic arithmetic operations like
addition, subtraction, multiplication, division, and modulus.
Operato
r Name Syntax Operation

+ Addition $x + $y Sum the operands

- Subtraction $x - $y Differences in the Operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Note: The exponentiation has been introduced in PHP 5.6.


Example: This example explains the arithmetic operators in PHP.
<?php
// Define two numbers
$x = 10;
$y = 3;

// Addition
echo "Addition: " . ($x + $y) . "\n";

// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";

// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";

// Division
echo "Division: " . ($x / $y) . "\n";

// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";

// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>

Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1

2. Logical Operators
Logical operators are used to operate with conditional statements. These
operators evaluate conditions and return a boolean result (true or false).
Operator Name Syntax Operation

Logical
and $x and $y True if both the operands are true else false
AND

or Logical OR $x or $y True if either of the operands is true otherwise, it is false

True if either of the operands is true and false if both are


xor Logical XOR $x xor $y
true

Logical
&& $x && $y True if both the operands are true else false
AND

|| Logical OR $x || $y True if either of the operands is true otherwise, it is false

! Logical NOT !$x True if $x is false

Example: This example describes the logical & relational operators in PHP.
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";

if ($x == 50 or $y == 20)
echo "or Success \n";

if ($x == 50 xor $y == 20)


echo "xor Success \n";

if ($x == 50 && $y == 30)


echo "&& Success \n";

if ($x == 50 || $y == 20)
echo "|| Success \n";

if (!$z)
echo "! Success \n";
?>

Output
and Success
or Success
xor Success
&& Success
|| Success
! Success

3. Comparison Operators
Comparison operators are used to compare two values and return a Boolean
result (true or false).
Operato
r Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal

!= Not Equal To $x != $y Returns True if both the operands are not equal

<> Not Equal To $x <> $y Returns True if both the operands are unequal

$x === Returns True if both the operands are equal and are
=== Identical
$y of the same type

Returns True if both the operands are unequal and


!== Not Identical $x == $y
are of different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

Less Than or Equal


<= $x <= $y Returns True if $x is less than or equal to $y
To

Greater Than or
>= $x >= $y Returns True if $x is greater than or equal to $y
Equal To

Example: This example describes the comparison operator in PHP.


<?php
$a = 80;
$b = 50;
$c = "80";

// Here var_dump function has been used to


// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) . "\n";
var_dump($a != $b) . "\n";
var_dump($a <> $b) . "\n";
var_dump($a === $c) . "\n";
var_dump($a !== $c) . "\n";
var_dump($a < $b) . "\n";
var_dump($a > $b) . "\n";
var_dump($a <= $b) . "\n";
var_dump($a >= $b);
?>

Output
bool(true)

Warning: A non-numeric value encountered in


/home/guest/sandbox/Solution.php on line 10
bool(true)

Warning: A non-numeric value encountered in


/home/guest/sandbox/Solution.php on line 11
...

4. Conditional or Ternary Operators


These operators are used to compare two values and take either of the
results simultaneously, depending on whether the outcome is TRUE or
FALSE. These are also used as a shorthand notation for
the if...else statement that we will read in the article on decision making.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either be evaluated as true or false. If the condition
evaluates to True, then value1 will be assigned to the variable $var;
otherwise, value2 will be assigned to it.
Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the condition is
Ternar
?: true, then the left result of the colon is accepted otherwise, the result is on the
y
right.

Example: This example describes the Conditional or Ternary operators in


PHP.
<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>

Output
The number is negative

5. Assignment Operators
Assignment operators are used to assign values to variables. These
operators allow you to assign a value and perform operations in a single
step.
Operator Name Syntax Operation

Operand on the left obtains the value of the


= Assign $x = $y
operand on the right

$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x - $y

*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y

Divide, then assign


/= $x /= $y Simple division same as $x = $x / $y
(quotient)

Divide, then assign $x %=


%= Simple division same as $x = $x % $y
(remainder) $y

Example: This example describes the assignment operator in PHP.


<?php
// Simple assign operator
$y = 75;
echo $y, "\n";

// Add then assign operator


$y = 100;
$y += 200;
echo $y, "\n";

// Subtract then assign operator


$y = 70;
$y -= 10;
echo $y, "\n";

// Multiply then assign operator


$y = 30;
$y *= 20;
echo $y, "\n";

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";

// Divide then assign(remainder) operator


$y = 50;
$y %= 5;
echo $y;
?>
Output
75
300
60
600
20
0

6. Array Operators
These operators are used in the case of arrays. Here are the array operators,
along with their syntax and operations, that PHP provides for the array
operation.
Operator Name Syntax Operation

+ Union $x + $y Union of both, i.e., $x and $y

== Equality $x == $y Returns true if both have the same key-value pair

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in the same
=== Identity
$y order and of the same type

Non- $x !==
!== Returns True if both are not identical to each other
Identity $y

<> Inequality $x <> $y Returns True if both are unequal

Example: This example describes the array operation in PHP.


<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");

var_dump($x + $y);
var_dump($x == $y) . "\n";
var_dump($x != $y) . "\n";
var_dump($x <> $y) . "\n";
var_dump($x === $y) . "\n";
var_dump($x !== $y) . "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
7. Increment/Decrement Operators
These are called the unary operators as they work on single operands. These
are used to increment or decrement values.
Operator Name Syntax Operation

++ Pre-Increment ++$x First, increment $x by one, then return $x

-- Pre-Decrement --$x First, decrement $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one

Post-
-- $x-- First, return $x, then decrement it by one
Decrement

Example: This example describes the Increment/Decrement operators in


PHP.
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";

$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";

$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";

$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>

Output
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1

8. String Operators
This operator is used for the concatenation of 2 or more strings using the
concatenation operator ('.'). We can also use the concatenating assignment
operator ('.=') to append the argument on the right side to the argument on
the left side.
Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First, it concatenates then assigns, the same as $x


.= $x.=$y
assignment = $x.$y

Example: This example describes the string operator in PHP.


<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>

Output
GeeksforGeeks!!!
GeeksforGeeks!!!

PHP | Decision Making

Decision-making is an important part of programming, allowing the program to execute different actions based on
conditions. In PHP, decision-making helps control the flow of a program by executing different blocks of code
depending on certain conditions or expressions. PHP provides several constructs for decision-making, including if,
else, elseif, and switch. These control structures can be used to make logical decisions in a program.

This article covers the decision-making structures in PHP and explains how to use them effectively. Let us now look at
each one of these in detail:

1. if Statement

The if statement is the simplest form of decision making. It executes a block of code if the specified condition
evaluates to true. If the condition evaluates to false, the block of code is skipped.

Syntax:

if (condition){
// if TRUE then execute this code
}
Example:

<?php

$x = 12;

if ($x > 0) {

echo "The number is positive";

?>

Output

The number is positive

Flowchart

2. if...else Statement

The if-else statement is an extension of the if statement. It allows you to specify an alternative block of code that is
executed when the condition is false. This is useful when there are two mutually exclusive conditions.

Syntax:

if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:

<?php

$x = -12;

if ($x > 0) {

echo "The number is positive";

else{

echo "The number is negative";

?>

Output

The number is negative

Flowchart

3. if...elseif...else Statement

In scenarios where you need to evaluate multiple conditions, you can use the if-elseif-else ladder. This construct
allows you to check multiple conditions in sequence. The first condition that evaluates to true will execute its
corresponding block of code, and all other conditions will be skipped.

Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}

Example:

<?php

$x = "August";

if ($x == "January") {

echo "Happy Republic Day";

elseif ($x == "August") {

echo "Happy Independence Day!!!";

else{

echo "Nothing to show";

?>

Output

Happy Independence Day!!!

Flowchart
4. switch Statement

The "switch" performs in various cases i.e., it has various cases to which it matches the condition and appropriately
executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a
case matches then the same case is executed. To use switch, we need to get familiar with two different keywords
namely, break and default.

 The break statement is used to stop the automatic control flow into the next cases and exit from the switch
case.

 The default statement contains the code that would execute if none of the cases match.

Syntax

switch (variable) {
case value1:
// Code to be executed if the variable equals value1
break;
case value2:
// Code to be executed if the variable equals value2
break;
default:
// Code to be executed if no cases match
}

Example:

<?php

$day = "Monday";

switch ($day) {

case "Monday":

echo "Start of the week!";

break;

case "Friday":

echo "End of the week!";

break;

case "Saturday":

case "Sunday":

echo "Weekend!";

break;

default:

echo "Mid-week!";

?>

Output

Start of the week!

Note:

 The switch statement compares the variable’s value strictly (both type and value).

 If no case matches, the default block is executed (if provided).

 The break statement is crucial; without it, the program will continue to execute subsequent case blocks (a
behavior known as "fall-through").

Flowchart
5. Ternary Operators

PHP also provides a shorthand way to perform conditional checks using the ternary operator (?:). This operator
allows you to write simple if-else conditions in a compact form.

Syntax

(condition) ? if TRUE execute this : otherwise execute this;

Example:

<?php
$age = 20;

echo ($age >= 18) ? "You are an adult." : "You are a minor.";

?>

Output

You are an adult.

PHP Loops
Last Updated : 10 Apr, 2025


In PHP, Loops are used to repeat a block of code multiple times based on a
given condition. PHP provides several types of loops to handle different
scenarios, including while loops, for loops, do...while loops, and foreach
loops.
In this article, we will discuss the different types of loops in PHP, their
syntax, and examples.
Types of Loops in PHP
Below are the following types of loops in PHP:
 for loop
 while loop
 do-while loop
 foreach loop
1. PHP for Loop
PHP for loop is used when you know exactly how many times you want to
iterate through a block of code. It consists of three expressions:
 Initialization: Sets the initial value of the loop variable.
 Condition: Checks if the loop should continue.
 Increment/Decrement: Changes the loop variable after each
iteration.
Syntax
for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}
Example: Printing numbers from 1 to 5 using a for loop.
<?php

// Code to illustrate for loop


for ($num = 1; $num <= 5; $num += 1) {
echo $num . "\n";
}

?>

Output
1
2
3
4
5

2. PHP while Loop


The while loop is also an entry control loop like for loops. It first checks the
condition at the start of the loop, and if it's true then it enters into the loop
and executes the block of statements and goes on executing it as long as
the condition holds true.
Syntax
while ( condition ) {
// Code is executed
}

Example: Printing numbers from 1 to 5.


<?php
$num = 1;
while ($num <= 5) {
echo $num . "\n";
$num++;
}
?>

Output
1
2
3
4
5

3. PHP do-while Loop


The do-while loop is an exit control loop, which means, it first enters the
loop, executes the statements, and then checks the condition. Therefore, a
statement is executed at least once using the do...while loop. After
executing once, the program is executed as long as the condition holds
true.
Syntax
do {
// Code is executed
} while ( condition );

Example: Printing numbers from 1 to 5.


<?php
$num = 1;
do {
echo $num . "\n";
$num++;
} while ($num <= 5);
?>

Output
1
2
3
4
5

4. PHP foreach Loop


This foreach loop is used to iterate over arrays. For every counter of loop,
an array element is assigned, and the next counter is shifted to the next
element. It simplifies working with arrays and objects by automatically
iterating through each element.
Syntax:
foreach ( $array as $value ) {
// Code to be executed
}
or
foreach ($array as $key => $value) {
// Code to be executed
}
$array: The array to iterate over.

 $value: The current value of the array element during each
iteration.
Example: Iterating through an array
<?php
// foreach loop over an array
$arr = array (10, 20, 30, 40, 50, 60);

foreach ($arr as $val) {


echo $val . " ";
}
echo "\n";
// foreach loop over an array with keys
$ages = array(
"Anjali" => 25,
"Kriti" => 30,
"Ayushi" => 22
);
foreach ($ages as $name => $age) {
echo $name . " => " . $age . "\n";
}
?>

Output
10 20 30 40 50 60
Anjali => 25
Kriti => 30
Ayushi => 22

Why Use Loops?


Loops allow you to execute a block of code multiple times without rewriting
the code. This is useful when working with repetitive tasks, such as:
 Iterating through arrays or data structures
 Acting a specific number of times
 Waiting for a condition to be met before proceeding
Conclusion
Loops are an important feature in PHP that help developers repeat tasks
automatically. Whether you need to go through items in an array, run a
block of code multiple times, or wait until a condition is true, PHP offers
different types of loops to make these tasks easier and more efficient.
PHP Arrays


Arrays are one of the most important data structures in PHP. They allow you
to store multiple values in a single variable. PHP arrays can hold values of
different types, such as strings, numbers, or even other arrays.
Understanding how to use arrays in PHP is important for working with data
efficiently.
 PHP offers many built-in array functions for sorting, merging,
searching, and more.
 PHP Arrays can store values of different types (e.g., strings, integers,
objects, or even other arrays) in the same array.
 They are dynamically sized.
 They allow you to store multiple values in a single variable, making
it easier to manage related data.
Types of Arrays in PHP
There are three main types of arrays in PHP:
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal
when you need to store a list of items where the order matters.
Now, let us understand with the help of the example:
<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>

Output
apple
You can also explicitly define numeric keys in an indexed array:
<?php
$fruits = array(0 => "apple", 1 => "banana", 2 => "cherry");
?>
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store
data with meaningful identifiers instead of numeric indexes.
Now, let us understand with the help of the example:
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York");
echo $person["name"];
?>

Output
GFG

3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements.
These are used to represent more complex data structures, such as matrices
or tables.
Now, let us understand with the help of the example:
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>

Output
22

Creating Array in PHP


In PHP, arrays can be created using two main methods:
1. Using the array() function
The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
2. Using short array syntax ([])
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
You can also create associative arrays by specifying custom keys:
$person = ["name" => "GFG", "age" => 30];
Note: Both methods are valid, but the shorthand syntax is preferred for its
simplicity and readability.

Accessing and Modifying Array Elements


1. Accessing Array Elements
You can access individual elements in an array using their index (for indexed
arrays) or key (for associative arrays).
 Accessing Indexed Array:
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple
 Accessing Associative Array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // Outputs: GFG
2. Modifying Array Elements
You can modify an existing element by assigning a new value to a specific
index or key.
 Modifying Indexed Array Element:
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Mango"; // Changes "Banana" to "Mango"
echo $fruits[1]; // Outputs: Mango
 Modifying Associative Array Element:
$person = ["name" => "GFG", "age" => 25];
$person["age"] = 26; // Updates the age to 26
echo $person["age"]; // Outputs: 26
Adding and Removing Array Items
1. Adding Array Elements
You can add new elements to an array using the following methods:
 array_push(): Adds elements to the end of an indexed array.
$fruits = ["apple", "banana"];
array_push($fruits, "cherry"); // Adds "cherry" to the end
 array_unshift(): Adds elements to the beginning of an indexed
array.
array_unshift($fruits, "pear"); // Adds "pear" to the beginning
 Direct assignment: Adds an element to an associative array.
$person["city"] = "New York";
2. Removing Array Elements
To remove items from an array, you can use several functions:
 array_pop(): Removes the last element from an indexed array.
array_pop($fruits);
 array_shift(): Removes the first element from an indexed array.
array_shift($fruits);
 unset(): Removes a specific element from an array by key or index.
unset($fruits[2]); // Removes the element with index 2
Array Functions
PHP provides a wide range of built-in functions to work with arrays. Here are
some common array functions:
 Array Merge: The array_merge() function combines two or more
arrays into one.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]
 Array Search: The in_array() function checks if a specific value
exists in an array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}
 Array Sort: The sort() function sorts an indexed array in ascending
order.
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers); // Outputs: [1, 1, 3, 4, 5]
Array Iteration
You can loop through arrays using loops such as foreach or for.
 Using foreach Loop:
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
 Using for Loop:
$numbers = [1, 2, 3, 4];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}
PHP sort() Function

The sort() function is an inbuilt function in PHP and is used to sort an array in ascending order i.e, smaller to greater.
It sorts the actual array and hence changes are reflected in the original array itself. The function provides us with 6
sorting types, according to which the array can be sorted.

Syntax:

bool sort($array, sorting_type)

Parameters:

1. $array - The parameter specifies the array which we want to sort. It is a mandatory parameter

2. sorting_type - This is an optional parameter. There are 6 sorting types which are described below:

 SORT_REGULAR - When we pass 0 or SORT_REGULAR in the sorting_type parameter, the items in


the array are compared normally.

 SORT_NUMERIC - When we pass 1 or SORT_NUMERIC in the sorting_type parameter, the items in


the array are compared numerically

 SORT_STRING - When we pass 2 or SORT_STRING in the sorting_type parameter, the items in the
array are compared string-wise

 SORT_LOCALE_STRING - When we pass 3 or SORT_LOCALE_STRING in the sorting_type parameter,


the items in the array are compared as string based on current locale

 SORT_NATURAL - When we pass 4 or SORT_NATURAL in the sorting_type parameter, the items in


the array are compared as string using natural ordering

 SORT_FLAG_CASE - When we pass 5 or SORT_FLAG_CASE in the sorting_type parameter, the items


in the array are compared as strings. The items are treated as case-insensitive and then compared. It
can be used using | (bitwise operator) with SORT_NATURAL or SORT_STRING.

Return Value: It returns a boolean value, TRUE on success and False in failure. It sorts the original array in ascending
order which is passed as a parameter. Examples:

Input : $array = [3, 4, 1, 2]

Output :

Array

[0] => 1

[1] => 2

[2] => 3

[3] => 4

Input : $array = ["geeks2", "raj1", "striver3", "coding4"]

Output :

Array
(

[0] => coding4

[1] => geeks2

[2] => raj1

[3] => striver3

Below programs illustrate the sort() function in PHP:

Program 1: Program to demonstrate the use of sort() function.

<?php

// PHP program to demonstrate the use of sort() function

$array = array(3, 4, 2, 1);

// sort function

sort($array);

// prints the sorted array

print_r($array);

?>

Output:

Array

[0] => 1

[1] => 2

[2] => 3

[3] => 4

Program 2 : Program to demonstrate the use of sort() function to sort the string case-sensitively.

<?php

// PHP program to demonstrate the use of sort() function

// sorts the string case-sensitively

$array = array("geeks", "Raj", "striver", "coding", "RAj");

// sort function, sorts the string case-sensitively


sort($array, SORT_STRING);

// prints the sorted array

print_r($array);

?>

Output:

Array

[0] => RAj

[1] => Raj

[2] => coding

[3] => geeks

[4] => striver

Program 3 : Program to demonstrate the use of sort() function to sort the string case-insensitively.

<?php

// PHP program to demonstrate the use

// of sort() function sorts the string

// case-insensitively

$array = array("geeks", "Raj", "striver", "coding", "RAj");

// sort function, sorts the

// string case-insensitively

sort($array, SORT_STRING | SORT_FLAG_CASE);

// prints the sorted array

print_r($array);

?>

Output:

Array

[0] => coding

[1] => geeks

[2] => Raj


[3] => RAj

[4] => striver

PHP | asort() Function



The asort() function is an inbuilt function in PHP which is used to sort an


array according to values. It sorts in a way that relation between indices and
values is maintained. By default it sorts in ascending order of
values. Syntax:
bool asort( $array, $sorting_type )
Parameters: This function accepts two parameters as mentioned above
and described below:
 $array: This parameter specifies the array which to be sort. It is a
mandatory parameter.
 $sorting_type: This is an optional parameter. There are different
sorting types which are discussed below:
o SORT_REGULAR: The value of $sorting_type is
SORT_REGULAR then items are compare normally.
o SORT_NUMERIC: The value of $sorting_type is
SORT_NUMERIC then items are compares numerically.
o SORT_STRING: The value of $sorting_type is
SORT_STRING then items are compares as string.
o SORT_LOCALE_STRING: The value of $sorting_type is
SORT_STRING then items are compares as string,
based on current locale.
Return Value: This function returns True on success or False on failure.
Below programs illustrate the asort() function in PHP. Program 1:
<?php
// PHP program to illustrate
// asort() function

// Input different array elements


$arr = array("0" => "Web Technology",
"1" => "Machine Learning",
"2" => "GeeksforGeeks",
"3" => "Computer Graphics",
"4" => "Videos",
"5" => "Report Bug",
"6" => "Article",
"7" => "Sudo Placement",
"8" => "SContribute",
"9" => "Reset",
"10" => "Copy",
"11" => "IDE",
"12" => "Gate Note",
);
// Implementation of asort()
asort($arr);

// for-Loop for displaying result


foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}

?>
Output:
[6] = Article
[3] = Computer Graphics
[10] = Copy
[12] = Gate Note
[2] = GeeksforGeeks
[11] = IDE
[1] = Machine Learning
[5] = Report Bug
[9] = Reset
[8] = SContribute
[7] = Sudo Placement
[4] = Videos
[0] = Web Technology
Program 2:
<?php
// PHP program to illustrate
// asort() function

// Input different array elements


$arr = array("a" => 11,
"b" => 22,
"d" => 33,
"n" => 44,
"o" => 55,
"p" => 66,
"r" => 77,
"s" => 2,
"q" => -11,
"t" => 3,
"u" => 1000,
"z" => 1,

);
// Implementation of asort()
asort($arr);
// for-Loop for displaying result
foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}

?>
Output:
[q] = -11
[z] = 1
[s] = 2
[t] = 3
[a] = 11
[b] = 22
[d] = 33
[n] = 44
[o] = 55
[p] = 66
[r] = 77
[u] = 1000

PHP ksort() Function



The ksort() function is an inbuilt function in PHP which is used to sort an


array in ascending order according to its key values. It sorts in a way that
the relationship between the indices and values is maintained. Syntax:
bool ksort( $array, $sorting_type )
Parameters: This function accepts two parameters as mentioned above
and described below:
 $array: This parameter specifies the array which needs to be
sorted. It is a mandatory parameter.
 $sorting_type: This is an optional parameter. There are different
sorting types which are discussed below:
o SORT_REGULAR: The value of $sorting_type is
SORT_REGULAR then items are compare normally.
o SORT_NUMERIC: The value of $sorting_type is
SORT_NUMERIC then items are compared numerically.
o SORT_STRING: The value of $sorting_type is
SORT_STRING then items are compared as a string.
o SORT_LOCALE_STRING: The value of $sorting_type is
SORT_STRING then items are compare as strings,
based on the current locale.
Return Value: This function returns True on success or False on failure.
Below programs illustrate the ksort() function in PHP. Program 1:
<?php
// PHP program to illustrate
// ksort()function

// Input different array elements


$arr = array("13" =>"ASP.Net",
"12" =>"C#",
"11" =>"Graphics",
"4" =>"Video Editing",
"5" =>"Photoshop",
"6" =>"Article",
"4" =>"Placement",
"8" =>"C++",
"7" =>"XML",
"10" =>"Android",
"1" =>"SQL",
"2" =>"PL/Sql",
"3" =>"End",
"0" =>"Java",
);

// Implementation of ksort()
ksort($arr);

// for-Loop for displaying result


foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}

?>
Output:
[0] = Java
[1] = SQL
[2] = PL/Sql
[3] = End
[4] = Placement
[5] = Photoshop
[6] = Article
[7] = XML
[8] = C++
[10] = Android
[11] = Graphics
[12] = C#
[13] = ASP.Net
Program 2:
<?php
// PHP program to illustrate
// ksort function

// Input different array elements


$arr = array("z" => 11,
"y" => 22,
"x" => 33,
"n" => 44,
"o" => 55,
"b" => 66,
"a" => 77,
"m" => 2,
"q" => -11,
"i" => 3,
"e" => 56,
"d" => 1,
);

// Implementation of ksort
ksort($arr);

// for-Loop for displaying result


foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}

?>
Output:
[a] = 77
[b] = 66
[d] = 1
[e] = 56
[i] = 3
[m] = 2
[n] = 44
[o] = 55
[q] = -11
[x] = 33
[y] = 22
[z] = 11

PHP | Functions
Last Updated : 12 Jun, 2025


A function in PHP is a self-contained block of code that performs a specific


task. It can accept inputs (parameters), execute a set of statements, and
optionally return a value.
 PHP functions allow code reusability by encapsulating a block of
code to perform specific tasks.
 Functions can accept parameters and return values, enabling
dynamic behavior based on inputs.
 PHP supports both built-in functions and user-defined functions,
enhancing flexibility and modularity in code.
Creating a Function in PHP
A function is declared by using the function keyword, followed by the name
of the function, parentheses (possibly containing parameters), and a block of
code enclosed in curly braces.
Syntax
function functionName($param1, $param2) {
// Code to be executed
return $result; // optional
}
In this syntax:
 function is a keyword that starts the function declaration.
 functionName is the name of the function.
 $param1 and $param2 are parameters (optional) that can be passed
to the function.
 The return statement (optional) sends a value back to the caller.
Calling a Function in PHP
Once a function is declared, it can be invoked (called) by simply using the
function name followed by parentheses.
Now, let us understand with the help of example:
<?php
function sum($a, $b) {
return $a + $b;
}
echo sum(5, 3); // Outputs: 8
?>

Output
8
In this example:
 The function sum() is defined to take two parameters, $a and $b,
and return their sum.
 The function is called with 5 and 3 as arguments, and it returns the
result, which is 8.
Types of Functions in PHP
PHP has two types of functions:
1. User-Defined Functions
A user-defined function is created to perform a specific task as per the
developer's need. These functions can accept parameters, perform
computations, and return results.
Now, let us understand with the help of example:
<?php
function addNumbers($a, $b) {
return $a + $b;
}
echo addNumbers(5, 3); // Output: 8
?>

Output
8
In this example:
 The function addNumbers is defined by the user to take two
parameters, $a and $b, and returns their sum ($a + $b).
 The function is called with 5 and 3 as arguments, so it adds these
numbers together.
2. Built-in Functions
PHP comes with many built-in functions that can be directly used in your
code. For example, strlen(), substr(), array_merge(), date() and etc are built-
in PHP functions. These functions provide useful functionalities, such as
string manipulation, date handling, and array operations, without the need
to write complex logic from scratch.
Now, let us understand with the help of example:
<?php
$str = "Hello, World!";
echo strlen($str); // Output: 13
?>

Output
13
In this example:
 A string variable $str is defined with the value "Hello, World!".
 The strlen() function is the built-in function in PHP that is used to
calculate the length of the string $str.
PHP Function Parameters and Arguments
Functions can accept input values, known as parameters or arguments.
 Parameters are variables defined in the function declaration that
accept values.
 Arguments are the actual values passed to the function when it is
called.
These values can be passed to the function in two ways:
1. Passing by Value
When you pass a value by reference, the function works with a copy of the
argument. This means the original value remains unchanged.
Now, let us understand with the help of example:
<?php
function add($x, $y) {
$x = $x + $y;
return $x;
}

echo add(2, 3); // Outputs: 5


?>

Output
5
In this example:
 The function add() is defined with parameters $x and $y.
 The function adds $x and $y and returns the sum.
 The function is called with values 2 and 3, and the result 5 is printed.
2. Passing by Reference
By passing an argument by reference, any changes made inside the function
will affect the original variable outside the function.
Now, let us understand with the help of example:
<?php
function addByRef(&$x, $y) {
$x = $x + $y;
}
$a = 5;
addByRef($a, 3);
echo $a; // Outputs: 8
?>

Output
8
In this example:
 The function addByRef() is defined with $x passed by reference.
 The function modifies $x directly, adding $y to it.
 After calling the function with $a = 5 and 3, the value of $a becomes
8.
Returning Values in PHP Functions
Functions in PHP can return a value using the return statement. The return
value can be any data type such as a string, integer, array, or object. If no
return statement is provided, the function returns null by default.
Now, let us understand with the help of example:
<?php
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(4, 5); // $result will be 20
echo $result; // Output: 20
?>
Output
20
In this example:
 The function multiply() is defined to return the product of $a and $b.
 The function is called with 4 and 5 as arguments.
 The result 20 is returned and printed using echo.
Anonymous Functions (Closures)
PHP supports anonymous functions, also known as closures. These functions
do not have a name and are often used for passing functions as arguments
to other functions.
Now, let us understand with the help of example:
<?php
$greet = function($name) {
echo "Hello, " . $name . "!";
};
$greet("GFG");
?>

Output
Hello, GFG!
In this example:
 An anonymous function is defined and assigned to the variable
$greet.
 The function takes $name as a parameter and prints a greeting
message.
 The function is called with the argument "GFG", and the greeting
"Hello, GFG" is printed.
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in
situations where a task can be broken down into smaller, similar tasks.
Now, let us understand with the help of example:
<?php
function factorial($n) {
if ($n == 0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5);
?>

Output
120
In this example:
 The function factorial() is defined to calculate the factorial of a
number $n using recursion.
 If $n is 0, the function returns 1 (base case); otherwise, it calls itself
with $n - 1.
 When factorial(5) is called, the function recursively multiplies 5 * 4 *
3 * 2 * 1, returning 120.
What are the different scopes of variables in PHP ?
Last Updated : 06 May, 2022


Variable Scopes: The scope of a variable is defined as its extent in the


program within which it can be accessed, i.e. the scope of a variable is the
portion of the program within which it is visible or can be
accessed. Depending on the scopes, PHP has three variable scopes.
Local variables: The variables declared within a function are called local
variables to that function and have their scope only in that particular
function. In simple words, it cannot be accessed outside that function. Any
declaration of a variable outside the function with the same name as that of
the one within the function is a completely different variable. For now,
consider a function as a block of statements.
Example:
<?php

$num = 60;

function local_var() {

// This $num is local to this function


// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num <br>";
}

local_var();

// $num outside function local_var() is a


// completely different variable than that of
// inside local_var()
echo "Variable num outside local_var() function is $num \n";

?>
Output:
local num = 50
Variable num outside local_var() function is 60
Global variables: The variables declared outside a function are called
global variables. These variables can be accessed directly outside a
function. To get access within a function, we need to use the “global”
keyword before the variable to refer to the global variable.
Example:
<?php

$num = 20;

// Function to demonstrate use of global variable


function global_var() {

// We have to use global keyword before


// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}

global_var();
echo "Variable num outside function : $num \n";

?>
Output:
Variable num inside function : 20
Variable num outside function : 20
Static variable: It is the characteristic of PHP to delete the variable, once it
completes its execution and the memory is free. But sometimes we need to
store the variables even after the completion of function execution. To do
this, we use static keywords and the variables are called static variables.
PHP associates a data type depending on the value for the variable.
Example:
<?php

// Function to demonstrate static variables


function static_var() {

// Static variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";


echo $sum, "\n";
}

// First function call


static_var();

// second function call


static_var();

?>
Output:
6
3
7
3

$_GET and $_POST in PHP



In PHP, superglobals are built-in global arrays that provide access to certain
data types, such as form inputs, session data, and URL parameters. Among
the most commonly used superglobals in web development are $_GET and
$_POST. These superglobals are used to collect data from HTML forms and
URLs.
In this article, we will explore what $_GET and $_POST are, how they work,
and their use cases in PHP programming.
What is $_GET ?
The $_GET superglobal is used to collect form data sent via the GET method.
This method appends data to the URL as query parameters, which are
visible to users in the browser’s address bar. Some of the features of the
$_GET are:
 Retrieves data sent to the server as part of the URL query string.
 Useful for retrieving data that is visible to the user, such as search
queries or parameters in a URL.
 Data sent via $_GET is visible in the URL, making it less secure for
sensitive information.
 Accessed using associative array notation, e.g., $_GET['parameter'].
Syntax:
<?php
echo $_GET['username']; // Outputs the value of the 'username' parameter
from the URL
?>
Now, let us understand with the help of the example:
<html>
<body>
<form action="index.php" method="get">
<label>username:</label><br>
<input type="text" name="username"><br>
<input type="submit" value="Log in"><br>
</form>
</body>
</html>
<?php
echo "{$_GET["username"]} <br>" ;
?>
Output
$_GET Superglobals
In this example:
 A form asks the user for a username and submits it via the GET
method to index.php.
 The form submits the data to the same page (index.php), allowing
the same script to process the data.
 The form includes a text input field for the username.
 The submit button sends the form data when clicked.
 After submission, PHP retrieves and displays the entered username
using $_GET['username'].
 Since the form uses the GET method, the form data (like the
username) is appended to the URL as query parameters (e.g.,
index.php?username=anjali), making the username visible in the
browser’s URL bar.
What is $_POST?
The $_POST superglobal is used to collect form data sent via the POST
method. Unlike GET, the POST method sends data in the body of the HTTP
request, so the data is not visible in the URL. Some of the features of the
$_POST are:
 Retrieves data sent to the server in the body of an HTTP request,
typically from HTML forms submitted using the POST method.
 Suitable for handling sensitive or large amounts of data as it's not
visible in the URL.
 More secure than $_GET for handling sensitive information like
passwords.
 Accessed using associative array notation, e.g., $_POST['field_name'].
Syntax:
<?php
echo $_POST['username']; // Outputs the value of the 'username'
parameter submitted via POST
?>
Now, let us understand with the help of the example:
<html>
<body>
<form action="index.php" method="post">
<label>username:</label><br>
<input type="text" name="username"><br>
<input type="submit" value="Log in"><br>
</form>
</body>
</html>
<?php
echo "{$_POST["username"]} <br>" ;
?>
Output

$_POST Superglobals
In this example:
 A form asks the user for a username and submits it via the POST
method to index.php.
 The form submits the data to the same page (index.php), ensuring
the data is processed on the same script.
 The form includes a text input field for the username.
 The submit button sends the form data when clicked.
 After submission, PHP retrieves and displays the entered username
using $_POST['username'].
 Since the form uses the POST method, the form data is sent in the
HTTP request body, not in the URL, so the username is not visible in
the URL bar.
When to Use $_GET and $_POST
Use $_GET:
 For data like search terms or filter criteria that don't need security.
 Best for short data (due to URL length limits).
 Useful when you need to share or bookmark URLs with parameters
(e.g., search queries).
 Typically used for retrieving data without modifying the server (e.g.,
reading data from a database).
Use $_POST:
 Sensitive information (e.g., passwords, payment details) since it is
not visible in the URL.
 Suitable for forms with larger data, such as file uploads.
 Use for submitting forms that change server-side data (e.g.,
registration forms).
 Prevents data from being cached or stored in browser history.
$_GET vs $_POST
Both $_GET and $_POST are superglobals in PHP used to collect form data,
but they differ in how and where the data is transmitted.
$_GET $_POST

Data is visible in the URL Data is hidden in the HTTP request body

Limited by URL length Can handle large data sizes

Not secure (data is More secure, but still requires


visible) sanitization

Difference between HTTP GET and POST Methods


Last Updated : 16 Sep, 2024


HTTP (Hypertext Transfer Protocol) specifies a collection of request


methods to specify what action is to be performed on a particular resource.
The most commonly used HTTP request methods
are GET, POST, PUT, PATCH, and DELETE. This article covers the 2 most
common HTTP request methods, i.e. the GET & POST Methods among the
rest of the methods.
Table of Content
 HTTP GET
 HTTP POST
 Difference between HTTP GET and HTTP POST
HTTP GET
The HTTP GET method requests data from a server without altering its
state. It appends parameters to the URL, making it suitable for retrieving
non-sensitive data. Commonly used for viewing content, GET is ideal for
requests that don't involve data modification.
Example: In the following HTML code we have created a form with text
fields such as Username and City. we have also included a PHP
file getmethod.php where our data would be sent after we click the submit
button.
<!DOCTYPE html>
<html>

<body>
<form action="getmethod.php" method="GET">
Username:
<input type="text" name="username" /> <br>
City:
<input type="text" name="city" /> <br>
<input type="submit" />
</form>
</body>

</html>
In the following PHP code using the GET method we have displayed the
Username and city.

<!DOCTYPE html>
<html>

<body>
Welcome
<?php echo $_GET["username"]; ?> </br>
Your City is:
<?php echo $_GET["city"]; ?>
</body>

</html>
Output: Data passed in GET method is clearly visible in the address bar,
which can compromise the security.
HTTP POST
The HTTP POST method sends data from the client to the server to create
or update resources, storing data in the request body. It's suitable for
secure data transfer, like images or documents, with security relying on
encryption (HTTPS), authentication, and validation.
Example: In the following HTML code we have created a form with text
field as Username and Area of study. we have also included a PHP file
postmethod.php, where our data would be sent after we click the submit
button.
<!DOCTYPE html>
<html>

<body>
<form action="postmethod.php" method="post">
Username:
<input type="text" name="username" /> <br>
Area of Study:
<input type="text" name="area" /> <br>

<input type="submit" />


</form>
</body>

</html>
In the following PHP code using the POST method we have displayed the
Username and Area of study.
<!DOCTYPE html>
<html>

<body>
Welcome
<?php echo $_POST["username"]; ?> </br>
YOur Area of Study is:
<?php echo $_POST["area"]; ?>
</body>

</html>
Output: Data passed in POST method is not shown in the address bar,
which maintains the security.
Difference between HTTP GET and HTTP POST
HTTP GET HTTP POST

In GET method we can not send large


amount of data rather limited data of In POST method large amount of data
some number of characters is sent can be sent because the request
because the request parameter is parameter is appended into the body.
appended into the URL.

GET request is comparatively better POST request is comparatively less


than Post so it is used more than the better than Get method, so it is used
Post request. less than the Get request.

GET requests are only used to request POST requests can be used to create
data (not modify) and modify data.

GET request is comparatively less POST request is comparatively more


secure because the data is exposed in secure because the data is not
the URL bar. exposed in the URL bar.

Request made through GET method Request made through POST method
are stored in Browser history. is not stored in Browser history.

GET method request can be saved as POST method request can not be
bookmark in browser. saved as bookmark in browser.

Request made through GET method Request made through POST method
are stored in cache memory of are not stored in cache memory of
Browser. Browser.

Data passed through GET method can


Data passed through POST method
be easily stolen by attackers as the
can not be easily stolen by attackers
data is visible to everyone.GET
as the URL Data is not displayed in
requests should never be used when
the URL
dealing with sensitive data

In GET method only ASCII characters In POST method all types of data is
are allowed. allowed.

In POSTmethod, the encoding type


In GET method, the Encoding type is application/x-www-form-urlencoded
is application/x-www-form-urlencoded or multipart/form-data. Use multipart
encoding for binary data
📌 1️⃣ What is Input Validation?

Validation is checking that user input meets certain rules or requirements.

Examples:

 Email is in correct format

 Password is at least 8 characters

 Age is a number

Goal: Ensure the data is correct, complete, and safe before using it.

📌 2️⃣ What is Input Sanitization?

Sanitization is cleaning user input by removing unwanted or dangerous data.

Examples:

 Removing HTML tags to prevent XSS

 Escaping special characters in SQL queries

Goal: Make the input safe to store or display.

✅ 3️⃣ Why do we need Validation and Sanitization?

Because user input is untrusted! Attackers can:

 Submit malicious scripts (XSS)

 Attempt SQL injection

 Break your site with invalid data

📌 4️⃣ Common PHP Functions

✅ Validation Functions

 filter_var() with validation filters:

o FILTER_VALIDATE_EMAIL

o FILTER_VALIDATE_INT

o FILTER_VALIDATE_URL

✅ Sanitization Functions

 htmlspecialchars()

 strip_tags()

 filter_var() with sanitization filters:

o FILTER_SANITIZE_STRING (deprecated in newer PHP, use alternatives)

o FILTER_SANITIZE_EMAIL

o FILTER_SANITIZE_URL
✅ 5️⃣ Practical Example – Validating and Sanitizing a Form

Suppose you have a simple Contact Form:

html

CopyEdit

<form method="post" action="process.php">

Name: <input type="text" name="name"><br>

Email: <input type="text" name="email"><br>

Message:<br>

<textarea name="message"></textarea><br>

<input type="submit" value="Submit">

</form>

✅ PHP Code (process.php)

Let’s do validation and sanitization step by step.

php

CopyEdit

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// 1. Trim input (removes extra spaces)

$name = trim($_POST["name"]);

$email = trim($_POST["email"]);

$message = trim($_POST["message"]);

// 2. Sanitize input

$name = htmlspecialchars($name);

$email = filter_var($email, FILTER_SANITIZE_EMAIL);

$message = htmlspecialchars($message);

// 3. Validate email

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

die("Invalid email format!");

}
// 4. Validate that name and message are not empty

if (empty($name) || empty($message)) {

die("Name and message cannot be empty!");

// 5. Success! You can now use the input safely

echo "<h3>Thank you for your message!</h3>";

echo "<p>Name: $name</p>";

echo "<p>Email: $email</p>";

echo "<p>Message: $message</p>";

// Typically here you'd also:

// - Save to a database (with prepared statements!)

// - Send an email

?>

✅ Explanation of the Code

➜ 1️⃣ Trimming

php

CopyEdit

trim($input)

Removes leading/trailing spaces.


✅ Good for cleaning form data.

➜ 2️⃣ Sanitization

php

CopyEdit

htmlspecialchars($name)

 Converts <, >, &, and quotes to HTML entities.


✅ Prevents Cross-Site Scripting (XSS).

php

CopyEdit

filter_var($email, FILTER_SANITIZE_EMAIL)
 Removes illegal characters from email.

➜ 3️⃣ Validation

php

CopyEdit

filter_var($email, FILTER_VALIDATE_EMAIL)

 Checks if it's a valid email format.

php

CopyEdit

empty($name)

 Ensures required fields are filled.

✅ Result

Your PHP script will:


✔️Clean user input
✔️Reject invalid email
✔️Prevent HTML/JavaScript injection

📌 6️⃣ Advanced Example: Age Validation

Another small example with age field:

html

CopyEdit

<form method="post" action="age.php">

Name: <input type="text" name="name"><br>

Age: <input type="text" name="age"><br>

<input type="submit" value="Submit">

</form>

PHP Code (age.php)

php

CopyEdit

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = htmlspecialchars(trim($_POST["name"]));

$age = trim($_POST["age"]);
// Validate that age is an integer

if (!filter_var($age, FILTER_VALIDATE_INT)) {

die("Age must be an integer!");

// Further check for age range

if ($age < 1 || $age > 120) {

die("Age must be between 1 and 120!");

echo "Hello $name, your age is $age.";

?>

✅ Input is validated to be an integer


✅ Range-checked
✅ Name is sanitized

✅ 7️⃣ Best Practices

✔️Always validate and sanitize all user inputs


✔️Use prepared statements for database inserts
✔️Escape output when displaying to HTML
✔️Never trust client-side validation alone

✅ 8️⃣ Summary Table

Goal Function Example

Trim spaces trim() $name = trim($_POST["name"]);

Remove tags strip_tags() $safe = strip_tags($input);

Encode HTML htmlspecialchars() $safe = htmlspecialchars($input);

Sanitize filter_var($email, FILTER_SANITIZE_EMAIL) Removes bad chars in email

Validate filter_var($email, FILTER_VALIDATE_EMAIL) Checks if email is valid

Validate Int filter_var($age, FILTER_VALIDATE_INT) Checks if age is an integer

✅ 9️⃣ Extra: PHP Filter Example

PHP has a single function that can both sanitize and validate:
php

CopyEdit

$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Invalid email!";

If you want, I can also:


PHP Connect to MySQL

PHP 5 and later can work with a MySQL database using:

 MySQLi extension (the "i" stands for improved)


 PDO (PHP Data Objects)

Earlier versions of PHP used the MySQL extension. However, this extension was
deprecated in 2012.

Should I Use MySQLi or PDO?


If you need a short answer, it would be "Whatever you like".

Both MySQLi and PDO have their advantages:

PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases.

So, if you have to switch your project to use another database, PDO makes the process
easy. You only have to change the connection string and a few queries. With MySQLi, you
will need to rewrite the entire code - queries included.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL injection, and
are very important for web application security.

MySQL Examples in Both MySQLi and PDO


Syntax
In this, and in the following chapters we demonstrate three ways of working with PHP and
MySQL:

 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO

MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases,
when php5 mysql package is installed.

For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php

ADVERTISEMENT

Open a Connection to MySQL


Before we can access data in the MySQL database, we need to be able to connect to the
server:

Example (MySQLi Object-Oriented)Get your own PHP Server


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Note on the object-oriented example above:

$connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility
with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Note: In the PDO example above we have also specified a database (myDB). PDO
require a valid database to connect to. If no database is specified, an exception is thrown.

Tip: A great benefit of PDO is that it has an exception class to handle any problems that
may occur in our database queries. If an exception is thrown within the try{ } block, the
script stops executing and flows directly to the first catch(){ } block.

Close the Connection


The connection will be closed automatically when the script ends. To close the connection
before, use the following:

MySQLi Object-Oriented:
$conn->close();

MySQLi Procedural:
mysqli_close($conn);

PDO:
$conn = null;

PHP Create a MySQL Database

A database consists of one or more tables.

You will need special CREATE privileges to create or to delete a MySQL database.

Create a MySQL Database Using MySQLi


and PDO
The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":

Example (MySQLi Object-oriented)Get your own PHP Server


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>
Note: When you create a new database, you must only specify the first three arguments
to the mysqli object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-name
argument, like this: new mysqli("localhost", "username", "password", "", port)

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Tip: A great benefit of PDO is that it has exception class to handle any problems that may
occur in our database queries. If an exception is thrown within the try{ } block, the script
stops executing and flows directly to the first catch(){ } block. In the catch block above
we echo the SQL statement and the generated error message.

PHP MySQL Create Table

A database table has its own unique name and consists of columns and rows.

Create a MySQL Table Using MySQLi and


PDO
The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Notes on the table above:

The data type specifies what type of data the column can hold. For a complete reference
of all the available data types, go to our Data Types reference.

After the data type, you can specify other optional attributes for each column:

 NOT NULL - Each row must contain a value for that column, null values are not
allowed
 DEFAULT value - Set a default value that is added when no other value is passed
 UNSIGNED - Used for number types, limits the stored data to positive numbers and
zero
 AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each
time a new record is added
 PRIMARY KEY - Used to uniquely identify the rows in a table. The column with
PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value
must be unique for each record in the table.

The following examples shows how to create the table in PHP:

Example (MySQLi Object-oriented)Get your own PHP Server


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

// use exec() because no results are returned


$conn->exec($sql);
echo "Table MyGuests created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

PHP MySQL INSERT Query


In this tutorial you will learn how to insert records in a MySQL table using PHP.

Inserting Data into a MySQL Database


Table
Now that you've understood how to create database and tables in MySQL. In
this tutorial you will learn how to execute SQL query to insert records into a
table.

The INSERT INTO statement is used to insert new rows in a database table.

Let's make a SQL query using the INSERT INTO statement with appropriate
values, after that we will execute this insert query through passing it to the
PHP mysqli_query() function to insert data in table. Here's an example, which
insert a new row to the persons table by specifying values for
the first_name, last_name and email fields.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}

// Attempt insert query execution


try{
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('Peter', 'Parker', 'peterparker@mail.com')";
$pdo->exec($sql);
echo "Records inserted successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>
If you remember from the preceding chapter, the id field was marked with
the AUTO_INCREMENT flag. This modifier tells the MySQL to automatically assign a
value to this field if it is left unspecified, by incrementing the previous value by
1.
Inserting Multiple Rows into a Table
You can also insert multiple rows into a table with a single insert query at once.
To do this, include multiple lists of column values within the INSERT
INTO statement, where column values for each row must be enclosed within
parentheses and separated by a comma.

Let's insert few more rows into the persons table, like this:

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}

// Attempt insert query execution


try{
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('John', 'Rambo', 'johnrambo@mail.com'),
('Clark', 'Kent', 'clarkkent@mail.com'),
('John', 'Carter', 'johncarter@mail.com'),
('Harry', 'Potter', 'harrypotter@mail.com')";
$pdo->exec($sql);
echo "Records inserted successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>
Now, go to phpMyAdmin (http://localhost/phpmyadmin/) and check out
the persons table data inside demo database. You will find the value for
the id column is assigned automatically by incrementing the value of
previous id by 1.

Note: Any number of line breaks may occur within a SQL statement, provided
that any line break does not break off keywords, values, expression, etc.
Insert Data into a Database from an HTML
Form
In the previous section, we have learned how to insert data into database from
a PHP script. Now, we'll see how we can insert data into database obtained
from an HTML form. Let's create an HTML form that can be used to insert new
records to persons table.

Step 1: Creating the HTML Form


Here's a simple HTML form that has three text <input> fields and a submit
button.

Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>

Step 2: Retrieving and Inserting the Form Data


When a user clicks the submit button of the add record HTML form, in the
example above, the form data is sent to 'insert.php' file. The 'insert.php' file
connects to the MySQL database server, retrieves forms fields using the
PHP $_REQUEST variables and finally execute the insert query to add the records.
Here is the complete code of our 'insert.php' file:
Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}

// Attempt insert query execution


try{
// Create prepared statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
(:first_name, :last_name, :email)";
$stmt = $pdo->prepare($sql);

// Bind parameters to statement


$stmt->bindParam(':first_name', $_REQUEST['first_name']);
$stmt->bindParam(':last_name', $_REQUEST['last_name']);
$stmt->bindParam(':email', $_REQUEST['email']);

// Execute the prepared statement


$stmt->execute();
echo "Records inserted successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>
In the next chapter we will extend this insert query example and take it one
step further by implementing the prepared statement for better security and
performance.

Note: The mysqli_real_escape_string() function escapes special characters in


a string and create a legal SQL string to provide security against SQL injection.

This is very basic example of inserting the form data in a MySQL database
table. You can extend this example and make it more interactive by adding
validations to the user inputs before inserting it to the database tables. Please
check out the tutorial on PHP form validation to learn more about sanitizing and
validating user inputs using PHP.
PHP MySQL Prepared Statements
In this tutorial you will learn how to use prepared statements in MySQL using
PHP.

What is Prepared Statement


A prepared statement (also known as parameterized statement) is simply a
SQL query template containing placeholder instead of the actual parameter
values. These placeholders will be replaced by the actual values at the time of
execution of the statement.

MySQLi supports the use of anonymous positional placeholder ( ?), as shown


below:
INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?);
While, PDO supports both anonymous positional placeholder ( ?), as well as the
named placeholders. A named placeholder begins with a colon ( :) followed by
an identifier, like this:
INSERT INTO persons (first_name, last_name, email)
VALUES (:first_name, :last_name, :email);
The prepared statement execution consists of two stages: prepare and
execute.

 Prepare — At the prepare stage a SQL statement template is created and


sent to the database server. The server parses the statement template,
performs a syntax check and query optimization, and stores it for later
use.
 Execute — During execute the parameter values are sent to the server.
The server creates a statement from the statement template and these
values to execute it.

Prepared statements is very useful, particularly in situations when you execute


a particular statement multiple times with different values, for example, a
series of INSERT statements. The following section describes some of the major
benefits of using it.

Advantages of Using Prepared Statements


A prepared statement can execute the same statement repeatedly with high
efficiency, because the statement is parsed only once again, while it can be
executed multiple times. It also minimize bandwidth usage, since upon every
execution only the placeholder values need to be transmitted to the database
server instead of the complete SQL statement.

Prepared statements also provide strong protection against SQL injection,


because parameter values are not embedded directly inside the SQL query
string. The parameter values are sent to the database server separately from
the query using a different protocol and thus cannot interfere with it. The
server uses these values directly at the point of execution, after the statement
template is parsed. That's why the prepared statements are less error-prone,
and thus considered as one of the most critical element in database security.

The following example will show you how prepared statements actually work:

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Prepare an insert statement


$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?,
?)";

if($stmt = mysqli_prepare($link, $sql)){


// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name,
$email);

/* Set the parameters values and execute


the statement again to insert another row */
$first_name = "Hermione";
$last_name = "Granger";
$email = "hermionegranger@mail.com";
mysqli_stmt_execute($stmt);

/* Set the parameters values and execute


the statement to insert a row */
$first_name = "Ron";
$last_name = "Weasley";
$email = "ronweasley@mail.com";
mysqli_stmt_execute($stmt);

echo "Records inserted successfully.";


} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);
?>
As you can see in the above example we've prepared the INSERT statement just
once but executed it multiple times by passing the different set of parameters.

Explanation of Code (Procedural style)


Inside the SQL INSERT statement (line no-12) of the example above, the
question marks is used as the placeholders for
the first_name, last_name, email fields values.

The mysqli_stmt_bind_param() function (line no-16) bind variables to the


placeholders (?) in the SQL statement template. The placeholders ( ?) will be
replaced by the actual values held in the variables at the time of execution.
The type definition string provided as second argument i.e. the "sss" string
specifies that the data type of each bind variable is string.

The type definition string specify the data types of the corresponding bind
variables and contains one or more of the following four characters:

 b — binary (such as image, PDF file, etc.)


 d — double (floating point number)
 i — integer (whole number)
 s — string (text)

The number of bind variables and the number of characters in type definition
string must match the number of placeholders in the SQL statement template.

Using Inputs Received through a Web Form


If you remember from the previous chapter, we've created an HTML form
to insert data into database. Here, we're going to extend that example by
implementing the prepared statement. You can use the same HTML form to
test the following insert script example, but just make sure that you're using
the correct file name in the action attribute of the form.

Here's the updated PHP code for inserting the data. If you see the example
carefully you'll find we didn't use the mysqli_real_escape_string() to escape
the user inputs, like we've done in the previous chapter example. Since in
prepared statements, user inputs are never substituted into the query string
directly, so they do not need to be escaped correctly.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Prepare an insert statement


$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?,
?)";

if($stmt = mysqli_prepare($link, $sql)){


// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name,
$email);

// Set parameters
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];

// Attempt to execute the prepared statement


if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " .
mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);
?>
Note: Though escaping user inputs is not required in prepared statements, you
should always validate the type and size of the data received from external
sources and enforces appropriate limits to protect against system resources
exploitation.

PHP MySQL SELECT Query


In this tutorial you'll learn how to select records from a MySQL table using PHP.

Selecting Data From Database Tables


So far you have learnt how to create database and table as well as inserting
data. Now it's time to retrieve data what have inserted in the preceding
tutorial. The SQL SELECT statement is used to select the records from database
tables. Its basic syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;
Let's make a SQL query using the SELECT statement, after that we will execute
this SQL query through passing it to the PHP mysqli_query() function to retrieve
the table data.

Consider our persons database table has the following records:


+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all the data stored in
the persons table (using the asterisk character (*) in place of column name
selects all the data in the table).

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt select query execution


$sql = "SELECT * FROM persons";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

Explanation of Code (Procedural style)


In the example above, the data returned by the mysqli_query() function is stored
in the $result variable. Each time mysqli_fetch_array() is invoked, it returns the
next row from the result set as an array. The while loop is used to loops
through all the rows in the result set. Finally the value of individual field can be
accessed from the row either by passing the field index or field name to
the $row variable
like $row['id'] or $row[0], $row['first_name'] or $row[1], $row['last_name'] or $row[2],
and $row['email'] or $row[3].

If you want to use the for loop you can obtain the loop counter value or the
number of rows returned by the query by passing the $result variable to
the mysqli_num_rows() function. This loop counter value determines how many
times the loop should run.

PHP MySQL WHERE Clause


In this tutorial you will learn how to select the records from a MySQL database
table based on specific conditions using PHP.

Filtering the Records


The WHERE clause is used to extract only those records that fulfill a specified
condition.

The basic syntax of the WHERE clause can be given with:


SELECT column_name(s) FROM table_name WHERE column_name operator value
Let's make a SQL query using the WHERE clause in SELECT statement, after that
we'll execute this query through passing it to the PHP mysqli_query() function to
get the filtered data.

Consider we've a persons table inside the demo database that has following
records:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The following PHP code selects all the rows from the persons table where
first_name='john':

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt select query execution


$sql = "SELECT * FROM persons WHERE first_name='john'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+

| id | first_name | last_name | email |

+----+------------+-----------+---------------------+

| 2 | John | Rambo | johnrambo@mail.com |

| 4 | John | Carter | johncarter@mail.com |

+----+------------+-----------+---------------------+

PHP MySQL LIMIT Clause


In this tutorial you will learn how to fetch limited number of records from a
MySQL database table using PHP.

Limiting Result Sets


The LIMIT clause is used to constrain the number of rows returned by
the SELECT statement. This feature is very helpful for optimizing the page loading
time as well as to enhance the readability of a website. For example you can
divide the large number of records in multiple pages using pagination, where
limited number of records will be loaded on every page from the database
when a user request for that page by clicking on pagination link.
The basic syntax of the LIMIT clause can be given with:
SELECT column_name(s) FROM table_name LIMIT row_offset, row_count;
The LIMIT clause accepts one or two parameters which must be a nonnegative
integer:

 When two parameters are specified, the first parameter specifies the
offset of the first row to return i.e. the starting point, whereas the second
parameter specifies the number of rows to return. The offset of the first
row is 0 (not 1).
 Whereas, when only one parameter is given, it specifies the maximum
number of rows to return from the beginning of the result set.

For example, to retrieve the first three rows, you can use the following query:
SELECT * FROM persons LIMIT 3;
To retrieve the rows 2-4 (inclusive) of a result set, you can use the following
query:
SELECT * FROM persons LIMIT 1, 3;
Let's make a SQL query using the LIMIT clause in SELECT statement, after that we
will execute this query through passing it to the PHP mysqli_query() function to
get the limited number of records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The PHP code in the following example will display just three rows from
the persons table.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt select query execution


$sql = "SELECT * FROM persons LIMIT 3";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
After limiting the result set the output will look something like this:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

+----+------------+-----------+----------------------+

PHP MySQL ORDER BY Clause


In this tutorial you will learn how to sort and display the data from a MySQL
table in ascending or descending order using PHP.

Ordering the Result Set


The ORDER BY clause can be used in conjugation with the SELECT statement to see
the data from a table ordered by a specific field. The ORDER BY clause lets you
define the field name to sort against and the sort direction either ascending or
descending.

The basic syntax of this clause can be given with:


SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Let's make a SQL query using the ORDER BY clause in SELECT statement, after that
we will execute this query through passing it to the PHP mysqli_query() function
to get the ordered data. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all rows from the persons table
and sorts the result by the first_name column in the alphabetically ascending
order.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution with order by clause
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
After ordering the result, the result set will look something like this:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 3 | Clark | Kent | clarkkent@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 1 | Peter | Parker | peterparker@mail.com |

+----+------------+-----------+----------------------+

Tip: By default the ORDER BY clause sort the results in ascending order. If you
want to sort the records in a descending order, you can use the DESC keyword.
PHP MySQL UPDATE Query
In this tutorial you'll learn how to update the records in a MySQL table using
PHP.

Updating Database Table Data


The UPDATE statement is used to change or modify the existing records in a
database table. This statement is typically used in conjugation with
the WHERE clause to apply the changes to only those records that matches
specific criteria.

The basic syntax of the UPDATE statement can be given with:


UPDATE table_name SET column1=value,
column2=value2,... WHERE column_name=some_value
Let's make a SQL query using the UPDATE statement and WHERE clause, after that
we will execute this query through passing it to the PHP mysqli_query() function
to update the tables records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The PHP code in the following example will update the email address of a
person in the persons table whose id is equal to 1.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt update query execution


$sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+

| id | first_name | last_name | email |

+----+------------+-----------+--------------------------+

| 1 | Peter | Parker | peterparker_new@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+--------------------------+

Warning: The WHERE clause in the UPDATE statement specifies which record or
records should be updated. If you omit the WHERE clause, all records will be
updated.

PHP MySQL DELETE Query


In this tutorial you'll learn how to delete records from a MySQL table using PHP.

Deleting Database Table Data


Just as you insert records into tables, you can delete records from a table using
the SQL DELETE statement. It is typically used in conjugation with the WHERE clause
to delete only those records that matches specific criteria or condition.

The basic syntax of the DELETE statement can be given with:


DELETE FROM table_name WHERE column_name=some_value
Let's make a SQL query using the DELETE statement and WHERE clause, after that
we will execute this query through passing it to the PHP mysqli_query() function
to delete the tables records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 2 | John | Rambo | johnrambo@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 4 | John | Carter | johncarter@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

The PHP code in the following example will delete the records of those persons
from the persons table whose first_name is equal to John.

Example
Procedural Object Oriented PDO

Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt delete query execution


$sql = "DELETE FROM persons WHERE first_name='John'";
if(mysqli_query($link, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
After the deletion the persons table will look something like this:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | peterparker@mail.com |

| 3 | Clark | Kent | clarkkent@mail.com |

| 5 | Harry | Potter | harrypotter@mail.com |

+----+------------+-----------+----------------------+

As you can see the records has been deleted successfully from the persons
table.

Warning: The WHERE clause in the DELETE statement specifies which record or
records should be deleted. If you omit the WHERE clause, all records will be
deleted.

PHP MySQL CRUD Application


In this tutorial you'll learn how to build a CRUD application with PHP and
MySQL.

What is CRUD
CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations
are basic data manipulation for database. We've already learned how to
perform create (i.e. insert), read (i.e. select), update and delete operations in
previous chapters. In this tutorial we'll create a simple PHP application to
perform all these operations on a MySQL database table at one place.

Well, let's start by creating the table which we'll use in all of our example.

Creating the Database Table


Execute the following SQL query to create a table named employees inside
your MySQL database. We will use this table for all of our future operations.

Example
Download
CREATE TABLE employees (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
address VARCHAR(255) NOT NULL,
salary INT(10) NOT NULL
);
Creating the Config File
After creating the table, we need create a PHP script in order to connect to the
MySQL database server. Let's create a file named "config.php" and put the
following code inside it.

We'll later include this config file in other pages using the
PHP require_once() function.

Example
Procedural Object Oriented PDO

Download
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');

/* Attempt to connect to MySQL database */


try{
$pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME,
DB_USERNAME, DB_PASSWORD);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
If you've downloaded the Object Oriented or PDO code examples using the
download button, please remove the text "-oo-format" or "-pdo-format" from
file names before testing the code.

Note: Replace the credentials according to your MySQL server setting before
testing this code, for example, replace the database name 'demo' with your
own database name, replace username 'root' with your own database
username, specify database password if there's any.

Creating the Landing Page


First we will create a landing page for our CRUD application that contains a
data grid showing the records from the employees database table. It also has
action icons for each record displayed in the grid, that you may choose to view
its details, update it, or delete it.
We'll also add a create button on the top of the data grid that can be used for
creating new records in the employees table. Create a file named "index.php"
and put the following code in it:

Example
Procedural Object Oriented PDO

Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.j
s"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min
.js"></script>
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
table tr td:last-child{
width: 120px;
}
</style>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="mt-5 mb-3 clearfix">
<h2 class="pull-left">Employees Details</h2>
<a href="create.php" class="btn btn-success
pull-right"><i class="fa fa-plus"></i> Add New Employee</a>
</div>
<?php
// Include config file
require_once "config.php";
// Attempt select query execution
$sql = "SELECT * FROM employees";
if($result = $pdo->query($sql)){
if($result->rowCount() > 0){
echo '<table class="table table-bordered
table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Name</th>";
echo "<th>Address</th>";
echo "<th>Salary</th>";
echo "<th>Action</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = $result->fetch()){
echo "<tr>";
echo "<td>" . $row['id'] .
"</td>";
echo "<td>" . $row['name'] .
"</td>";
echo "<td>" . $row['address'] .
"</td>";
echo "<td>" . $row['salary'] .
"</td>";
echo "<td>";
echo '<a href="read.php?
id='. $row['id'] .'" class="mr-3" title="View Record" data-
toggle="tooltip"><span class="fa fa-eye"></span></a>';
echo '<a href="update.php?
id='. $row['id'] .'" class="mr-3" title="Update Record" data-
toggle="tooltip"><span class="fa fa-pencil"></span></a>';
echo '<a href="delete.php?
id='. $row['id'] .'" title="Delete Record" data-toggle="tooltip"><span
class="fa fa-trash"></span></a>';
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
unset($result);
} else{
echo '<div class="alert alert-danger"><em>No
records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try
again later.";
}

// Close connection
unset($pdo);
?>
</div>
</div>
</div>
</div>
</body>
</html>
Once employees table is populated with some records the landing page i.e. the
CRUD data grid may look something like the picture shown below:

Tip: We've used the Bootstrap framework to make this CRUD application layout
quickly and beautifully. Bootstrap is the most popular and powerful front-end
framework for faster and easier responsive web development. Please, checkout
the Bootstrap tutorial section to learn more about this framework.

Creating the Create Page


In this section we'll build the Create functionality of our CRUD application.

Let's create a file named "create.php" and put the following code inside it. It
will generate a web form that can be used to insert records in
the employees table.

Example
Procedural Object Oriented PDO

Download
<?php
// Include config file
require_once "config.php";

// Define variables and initialize with empty values


$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}

// Validate address
$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}

// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}

// Check input errors before inserting in database


if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an insert statement
$sql = "INSERT INTO employees (name, address, salary) VALUES
(:name, :address, :salary)";

if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":name", $param_name);
$stmt->bindParam(":address", $param_address);
$stmt->bindParam(":salary", $param_salary);

// Set parameters
$param_name = $name;
$param_address = $address;
$param_salary = $salary;

// Attempt to execute the prepared statement


if($stmt->execute()){
// Records created successfully. Redirect to landing
page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again
later.";
}
}

// Close statement
unset($stmt);
}

// Close connection
unset($pdo);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee
record to the database.</p>
<form action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-
control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo
$name_err;?></span>
</div>
<div class="form-group">
<label>Address</label>
<textarea name="address" class="form-control
<?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>"><?php echo
$address; ?></textarea>
<span class="invalid-feedback"><?php echo
$address_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary"
class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' :
''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo
$salary_err;?></span>
</div>
<input type="submit" class="btn btn-primary"
value="Submit">
<a href="index.php" class="btn btn-secondary ml-
2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
The same "create.php" file will display the HTML form and process the
submitted form data. It will also perform basic validation on user inputs (line
no-11 to 37) before saving the data.

Creating the Read Page


Now it's time to build the Read functionality of our CRUD application.

Let's create a file named "read.php" and put the following code inside it. It will
simply retrieve the records from the employees table based the id attribute of
the employee.

Example
Procedural Object Oriented PDO

Download
<?php
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Include config file
require_once "config.php";

// Prepare a select statement


$sql = "SELECT * FROM employees WHERE id = :id";

if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":id", $param_id);

// Set parameters
$param_id = trim($_GET["id"]);

// Attempt to execute the prepared statement


if($stmt->execute()){
if($stmt->rowCount() == 1){
/* Fetch result row as an associative array. Since the
result set
contains only one row, we don't need to use while loop
*/
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Retrieve individual field value


$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id parameter. Redirect to
error page
header("location: error.php");
exit();
}

} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
unset($stmt);

// Close connection
unset($pdo);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h1 class="mt-5 mb-3">View Record</h1>
<div class="form-group">
<label>Name</label>
<p><b><?php echo $row["name"]; ?></b></p>
</div>
<div class="form-group">
<label>Address</label>
<p><b><?php echo $row["address"]; ?></b></p>
</div>
<div class="form-group">
<label>Salary</label>
<p><b><?php echo $row["salary"]; ?></b></p>
</div>
<p><a href="index.php" class="btn btn-
primary">Back</a></p>
</div>
</div>
</div>
</div>
</body>
</html>

Creating the Update Page


Similarly, we can build the Update functionality of our CRUD application.

Let's create a file named "update.php" and put the following code inside it. It
will update the existing records in the employees table based the id attribute of
the employee.

Example
Procedural Object Oriented PDO

Download
<?php
// Include config file
require_once "config.php";

// Define variables and initialize with empty values


$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";

// Processing form data when form is submitted


if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];

// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}

// Validate address address


$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}

// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}

// Check input errors before inserting in database


if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an update statement
$sql = "UPDATE employees SET name=:name, address=:address,
salary=:salary WHERE id=:id";

if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":name", $param_name);
$stmt->bindParam(":address", $param_address);
$stmt->bindParam(":salary", $param_salary);
$stmt->bindParam(":id", $param_id);

// Set parameters
$param_name = $name;
$param_address = $address;
$param_salary = $salary;
$param_id = $id;

// Attempt to execute the prepared statement


if($stmt->execute()){
// Records updated successfully. Redirect to landing
page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again
later.";
}
}

// Close statement
unset($stmt);
}

// Close connection
unset($pdo);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);

// Prepare a select statement


$sql = "SELECT * FROM employees WHERE id = :id";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":id", $param_id);

// Set parameters
$param_id = $id;

// Attempt to execute the prepared statement


if($stmt->execute()){
if($stmt->rowCount() == 1){
/* Fetch result row as an associative array. Since
the result set
contains only one row, we don't need to use while
loop */
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Retrieve individual field value


$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id. Redirect to error
page
header("location: error.php");
exit();
}

} else{
echo "Oops! Something went wrong. Please try again
later.";
}
}

// Close statement
unset($stmt);

// Close connection
unset($pdo);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Update Record</h2>
<p>Please edit the input values and submit to update
the employee record.</p>
<form action="<?php echo
htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-
control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo
$name_err;?></span>
</div>
<div class="form-group">
<label>Address</label>
<textarea name="address" class="form-control
<?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>"><?php echo
$address; ?></textarea>
<span class="invalid-feedback"><?php echo
$address_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary"
class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' :
''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo
$salary_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo
$id; ?>"/>
<input type="submit" class="btn btn-primary"
value="Submit">
<a href="index.php" class="btn btn-secondary ml-
2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Creating the Delete Page


Finally, we will build the Delete functionality of our CRUD application.

Let's create a file named "delete.php" and put the following code inside it. It
will delete the existing records from the employees table based the id attribute
of the employee.

Example
Procedural Object Oriented PDO

Download
<?php
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Include config file
require_once "config.php";

// Prepare a delete statement


$sql = "DELETE FROM employees WHERE id = :id";

if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":id", $param_id);

// Set parameters
$param_id = trim($_POST["id"]);

// Attempt to execute the prepared statement


if($stmt->execute()){
// Records deleted successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
unset($stmt);

// Close connection
unset($pdo);
} else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Record</h2>
<form action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="id" value="<?php
echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this
employee record?</p>
<p>
<input type="submit" value="Yes"
class="btn btn-danger">
<a href="index.php" class="btn btn-
secondary ml-2">No</a>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Creating the Error Page


At the end, let's create one more file "error.php". This page will be displayed if
request is invalid i.e. if id parameter is missing from the URL query string or it is
not valid.

Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.m
in.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Invalid Request</h2>
<div class="alert alert-danger">Sorry, you've made
an invalid request. Please <a href="index.php" class="alert-link">go
back</a> and try again.</div>
</div>
</div>
</div>
</div>
</body>
</html>
After a long journey finally we've finished our CRUD application with PHP and
MySQL. We recommend you to check out PHP & MySQL database tutorial
section from the beginning, if you haven't already covered, for a better
understanding of each and every part of this tutorial.

Beginner-Friendly Guide to AJAX in PHP with


Practical Examples
Introduction
AJAX, which stands for Asynchronous JavaScript and XML, is a powerful technique that
lets web pages update content without reloading the entire page. When combined
with PHP, a popular server-side scripting language, AJAX enables dynamic, user-
friendly web applications. This article provides a clear, beginner-friendly guide to
using AJAX in PHP, including practical examples for fetching data from a database,
performing jQuery AJAX POST requests, and exploring advanced AJAX techniques.
With over 1500 words, we’ll walk through step-by-step examples, ensuring clarity and
ease of understanding for developers new to AJAX and PHP.

What is AJAX and Why Use It with PHP?


AJAX allows JavaScript to send requests to a server and receive responses in the
background, updating parts of a web page without a full refresh. PHP, on the other
hand, handles server-side tasks like processing data or querying databases. Together,
they create seamless, interactive experiences, such as live search, form submissions,
or dynamic content updates.

Benefits of Using AJAX with PHP

 Faster Updates: Only specific parts of a page reload, improving speed.


 Better User Experience: No page refreshes mean smoother interactions.
 Efficient Data Handling: Fetch or send data without disrupting the user.
 Versatile: Works with databases, APIs, or simple file processing.

This guide covers three key areas: fetching data from a database using AJAX,
performing a jQuery AJAX POST request, and exploring advanced AJAX techniques in
PHP.

Example 1: How to Fetch Data from a Database in PHP


Using AJAX
Let’s create a simple example where users can search for names in a database, and
the results appear instantly using AJAX. We’ll use PHP to query a MySQL database and
jQuery to handle the AJAX request.

Step 1: Set Up the Database

Create a MySQL database called ajax_demo and a table named users with some sample
data. Run this SQL in your database tool (e.g., phpMyAdmin):
CREATE DATABASE ajax_demo;
USE ajax_demo;
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL );

INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie'), ('Diana');


('Bob'), ('Charlie'), ('Diana');
Step 2: Create the PHP Backend

Create a file named fetch_data.php to handle the database query:

<?php

$host = 'localhost';

$user = 'root';

$pass = '';

$db = 'ajax_demo';

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

$sql = "SELECT name FROM users WHERE name LIKE '%$search%'";

$result = $conn->query($sql);

$users = [];

while ($row = $result->fetch_assoc()) {

$users[] = $row['name'];

echo json_encode($users);

$conn->close();
?>

This script connects to the database, searches for names matching the user’s input,
and returns the results as JSON.

Step 3: Create the Frontend

Create an HTML file named index.html with a search input and a results area:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>AJAX with PHP: Fetch Data</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

<h2>Search Users</h2>

<input type="text" id="search" placeholder="Enter a name">

<div id="results"></div>

<script>

$(document).ready(function() {

$('#search').on('input', function() {

let searchTerm = $(this).val();

$.ajax({

url: 'fetch_data.php',

type: 'GET',

data: { search: searchTerm },

success: function(data) {

let users = JSON.parse(data);

let output = users.length ? users.join('<br>') : 'No results found';

$('#results').html(output);

},
error: function() {

$('#results').html('Error fetching data');

});

});

});

</script>

</body>

</html>

</html>
Step 4: Test the Application

 Place index.html and fetch_data.php in your server’s root folder (e.g., htdocs for
XAMPP).
 Start your server (e.g., Apache and MySQL via XAMPP).
 Open index.html in a browser (e.g., http://localhost/index.html).
 Type a name like “Ali” or “Bob” in the search box. Matching names appear
instantly below the input.

How It Works

 The user types in the search input, triggering a jQuery AJAX GET request
to fetch_data.php.
 The PHP script queries the database for names matching the search term and
returns them as JSON.
 jQuery updates the #results div with the names, all without reloading the page.

This example is user-friendly because it provides instant feedback and handles errors
gracefully.

Example 2: jQuery AJAX POST Example in PHP


Now, let’s create an example where users submit a form using a jQuery AJAX POST
request, and PHP processes the data. This is useful for forms like contact or
registration pages.

Step 1: Create the PHP Backend

Create a file named submit_form.php:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '';

if ($name && $email) {


// In a real app, save to a database or send an email
$response = ['status' => 'success', 'message' => "Received: $name, $email"];
} else {
$response = ['status' => 'error', 'message' => 'Please fill all fields'];
}

echo json_encode($response);
}
?>
This script checks for POST data, sanitizes it, and returns a JSON response.

Step 2: Create the Frontend

Create form.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX POST with PHP</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.message { margin-top: 10px; }
.success { color: green; }
.error { color: red; }
</style>
</head>
<body>
<h2>Contact Form</h2>
<form id="contactForm">
<input type="text" id="name" placeholder="Your Name" required><br><br>
<input type="email" id="email" placeholder="Your Email" required><br><br>
<button type="submit">Submit</button>
</form>
<div id="message" class="message"></div>

<script>
$(document).ready(function() {
$('#contactForm').on('submit', function(e) {
e.preventDefault();
let name = $('#name').val();
let email = $('#email').val();

$.ajax({
url: 'submit_form.php',
type: 'POST',
data: { name: name, email: email },
success: function(data) {
let response = JSON.parse(data);
let messageClass = response.status === 'success' ? 'success' : 'error';
$('#message').removeClass().addClass('message ' +
messageClass).text(response.message);
},
error: function() {
$('#message').removeClass().addClass('message error').text('Error submitting form');
}
});
});
});
</script>
</body>
</html>
Step 3: Test the Form
 Place form.html and submit_form.php in your server’s root folder.
 Open form.html in a browser.
 Fill in the name and email fields and click Submit. A success or error message
appears without a page reload.

How It Works

 The form submits data via a jQuery AJAX POST request to submit_form.php.
 PHP processes the input, validates it, and returns a JSON response.
 jQuery displays the response in the #message div, styled as green for success or
red for errors.

This example is clear and user-friendly, with visual feedback and error handling.

Advanced AJAX in PHP


For developers ready to go beyond basics, here are advanced AJAX techniques in PHP
to enhance your applications:

1. Real-Time Data Updates

Use AJAX with PHP to create live features, like a chat or dashboard. For example, poll
a PHP script every few seconds to fetch new data:

setInterval(function() {
$.ajax({
url: 'get_updates.php',
type: 'GET',
success: function(data) {
$('#updates').html(data);
}
});
}, 5000); // Every 5 seconds
In get_updates.php, query a database for new records and return them as HTML or
JSON.

2. File Uploads with AJAX

Upload files without reloading using the FormData API:

$('#uploadForm').on('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
$.ajax({
url: 'upload_file.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
$('#result').html(response);
}
});
});
In upload_file.php, handle the file with $_FILES and save it to a folder.

3. Pagination with AJAX


Load database records in chunks without reloading:

let page = 1;
$('#loadMore').on('click', function() {
$.ajax({
url: 'load_more.php',
type: 'GET',
data: { page: page },
success: function(data) {
$('#content').append(data);
page++;
}
});
});
In load_more.php, use LIMIT and OFFSET in your SQL query to fetch records for the
current page.

4. Error Handling and Loading States

Add loading spinners and detailed error messages:

$.ajax({
url: 'fetch_data.php',
type: 'GET',
beforeSend: function() {
$('#loader').show();
},
success: function(data) {
$('#results').html(data);
},
error: function(xhr, status, error) {
$('#results').html('Error: ' + xhr.status + ' ' + error);
},
complete: function() {
$('#loader').hide();
}
});
Style #loader with CSS to show a spinning animation.

5. CSRF Protection

Secure POST requests with a CSRF token:

session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
Add the token to your form:

<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">


Verify it in submit_form.php:

if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {


die(json_encode(['status' => 'error', 'message' => 'Invalid CSRF token']));
}
Tips for Success
 Use jQuery CDN: Include jQuery via a CDN for simplicity, as shown in the
examples.
 Sanitize Inputs: Always escape or validate user inputs in PHP to prevent SQL
injection or XSS attacks.
 Test Locally: Use XAMPP or WAMP to run PHP and MySQL locally.
 Debugging: Use browser developer tools (F12) to inspect AJAX requests and
responses.
 Optimize: Minimize database queries and use caching for frequently accessed
data.

Conclusion
AJAX with PHP is a game-changer for building dynamic, user-friendly web applications.
The examples above—fetching database data, handling POST forms, and advanced
techniques like file uploads or real-time updates—show how easy it is to get started.
You can create fast, interactive features that enhance the user experience by using
jQuery for AJAX and PHP for server-side logic.

Try these examples on your local server, experiment with the advanced techniques,
and explore PHP’s official documentation or jQuery’s AJAX guide for more ideas. With
practice, you’ll master AJAX in PHP and build amazing web apps!

Code Igniter 4

CodeIgniter - Overview
Previous
Quiz
Next

CodeIgniter is an application development framework, which can be used to develop


websites, using PHP. It is an Open Source framework. It has a very rich set of
functionality, which will increase the speed of website development work.

If you know PHP well, then CodeIgniter will make your task easier. It has a very rich set of
libraries and helpers. By using CodeIgniter, you will save a lot of time, if you are
developing a website from scratch. Not only that, a website built in CodeIgniter is secure
too, as it has the ability to prevent various attacks that take place through websites.

CodeIgniter Features
Some of the important features of CodeIgniter are listed below −

 Model-View-Controller Based System


 Extremely Light Weight
 Full Featured database classes with support for several platforms.
 Query Builder Database Support
 Form and Data Validation
 Security and XSS Filtering
 Session Management
 Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols
(sendmail, SMTP, and Mail) and more.
 Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD,
ImageMagick, and NetPBM
 File Uploading Class
 FTP Class
 Localization
 Pagination
 Data Encryption
 Benchmarking
 Full Page Caching
 Error Logging
 Application Profiling
 Calendaring Class
 User Agent Class
 Zip Encoding Class
 Template Engine Class
 Trackback Class
 XML-RPC Library
 Unit Testing Class
 Search-engine Friendly URLs
 Flexible URI Routing
 Support for Hooks and Class Extensions
 Large library of helper functions

CodeIgniter - Installing
Previous
Quiz
Next

It is very easy to install CodeIgniter. Just follow the steps given below −

 Step-1 − Download the CodeIgniter from the link CodeIgniter


o There are two different options legacy and latest. The names itself are self
descriptive. legacy has version less than 2.x and latest has 3.0 version.
o We can also go with GitHub and get all of the latest scripts..
 Step-2 − Unzip the folder.
 Step-3 − Upload all files and folders to your server.
 Step-4 − After uploading all the files to your server, visit the URL of your server,
e.g., www.domain-name.com.

On visiting the URL, you will see the following screen −

CodeIgniter - Application Architecture


Previous
Quiz
Next

The architecture of CodeIgniter application is shown below.

 As shown in the figure, whenever a request comes to CodeIgniter, it will first go


to index.php page.
 In the second step, Routing will decide whether to pass this request to step-3 for
caching or to pass this request to step-4 for security check.
 If the requested page is already in Caching, then Routing will pass the request to
step-3 and the response will go back to the user.
 If the requested page does not exist in Caching, then Routing will pass the
requested page to step-4 for Security checks.
 Before passing the request to Application Controller, the Security of the
submitted data is checked. After the Security check, the Application
Controller loads necessary Models, Libraries, Helpers,
Plugins and Scripts and pass it on to View.
 The View will render the page with available data and pass it on for Caching. As
the requested page was not cached before so this time it will be cached
in Caching, to process this page quickly for future requests.

Directory Structure
The image given below shows the directory structure of the CodeIgniter.

CodeIgniter directory structure is divided into 3 folders −

 Application
 System
 User_guide

Application
As the name indicates the Application folder contains all the code of your application that
you are building. This is the folder where you will develop your project. The Application
folder contains several other folders, which are explained below −

 Cache − This folder contains all the cached pages of your application. These
cached pages will increase the overall speed of accessing the pages.
 Config − This folder contains various files to configure the application. With the
help of config.php file, user can configure the application.
Using database.php file, user can configure the database of the application.
 Controllers − This folder holds the controllers of your application. It is the basic
part of your application.
 Core − This folder will contain base class of your application.
 Helpers − In this folder, you can put helper class of your application.
 Hooks − The files in this folder provide a means to tap into and modify the inner
workings of the framework without hacking the core files.
 Language − This folder contains language related files.
 Libraries − This folder contains files of the libraries developed for your application.
 Logs − This folder contains files related to the log of the system.
 Models − The database login will be placed in this folder.
 Third_party − In this folder, you can place any plugins, which will be used for your
application.
 Views − Applications HTML files will be placed in this folder.

System
This folder contains CodeIgniter core codes, libraries, helpers and other files, which help
make the coding easy. These libraries and helpers are loaded and used in web app
development.

This folder contains all the CodeIgniter code of consequence, organized into various
folders −

 Core − This folder contains CodeIgniters core class. Do not modify anything here.
All of your work will take place in the application folder. Even if your intent is to
extend the CodeIgniter core, you have to do it with hooks, and hooks live in the
application folder.
 Database − The database folder contains core database drivers and other
database utilities.
 Fonts − The fonts folder contains font related information and utilities.
 Helpers − The helpers folder contains standard CodeIgniter helpers (such as date,
cookie, and URL helpers).
 Language − The language folder contains language files. You can ignore it for
now.
 Libraries − The libraries folder contains standard CodeIgniter libraries (to help you
with e-mail, calendars, file uploads, and more). You can create your own libraries or
extend (and even replace) standard ones, but those will be saved in
the application/libraries directory to keep them separate from the standard
CodeIgniter libraries saved in this particular folder.

User_guide
This is your user guide to CodeIgniter. It is basically, the offline version of user guide on
CodeIgniter website. Using this, one can learn the functions of various libraries, helpers
and classes. It is recommended to go through this user guide before building your first
web app in CodeIgniter.

Beside these three folders, there is one more important file named index.php. In this file,
we can set the application environment and error level and we can define system and
application folder name. It is recommended, not to edit these settings if you do not have
enough knowledge about what you are going to do.

CodeIgniter - MVC Framework


Previous
Quiz
Next
CodeIgniter is based on the Model-View-Controller (MVC) development pattern.
MVC is a software approach that separates application logic from presentation. In
practice, it permits your web pages to contain minimal scripting since the presentation is
separate from the PHP scripting.

 The Model represents your data structures. Typically, your model classes will
contain functions that help you retrieve, insert and update information in your
database.
 The View is information that is being presented to a user. A View will normally be a
web page, but in CodeIgniter, a view can also be a page fragment like a header or
footer. It can also be an RSS page, or any other type of page.
 The Controller serves as an intermediary between the Model, the View, and any
other resources needed to process the HTTP request and generate a web page.

CodeIgniter - Basic Concepts

Controllers
A controller is a simple class file. As the name suggests, it controls the whole application
by URI.

Creating a Controller
First, go to application/controllers folder. You will find two files
there, index.html and Welcome.php. These files come with the CodeIgniter.

Keep these files as they are. Create a new file under the same path named Test.php.
Write the following code in that file −

<?php
class Test extends CI_Controller {

public function index() {


echo "Hello World!";
}
}
?>

The Test class extends an in-built class called CI_Controller. This class must be
extended whenever you want to make your own Controller class.

Calling a Controller
The above controller can be called by URI as follows −

http://www.your-domain.com/index.php/test

Notice the word test in the above URI after index.php. This indicates the class name of
controller. As we have given the name of the controller Test, we are writing test after
the index.php. The class name must start with uppercase letter but we need to
write lowercase letter when we call that controller by URI. The general syntax for calling
the controller is as follows −

http://www.your-domain.com/index.php/controller/method-name

Creating & Calling Constructor Method


Let us modify the above class and create another method named hello.

<?php
class Test extends CI_Controller {

public function index() {


echo "This is default function.";
}

public function hello() {


echo "This is hello function.";
}
}
?>

We can execute the above controller in the following three ways −

 http://www.your-domain.com/index.php/test
 http://www.your-domain.com/index.php/test/index
 http://www.your-domain.com/index.php/test/hello
After visiting the first URI in the browser, we get the output as shown in the picture given
below. As you can see, we got the output of the method index, even though we did not
pass the name of the method the URI. We have used only controller name in the URI. In
such situations, the CodeIgniter calls the default method index.

Visiting the second URI in the browser, we get the same output as shown in the above
picture. Here, we have passed methods name after controllers name in the URI. As the
name of the method is index, we are getting the same output.

Visiting the third URI in the browser, we get the output as shown in picture given below.
As you can see, we are getting the output of the method hello because we have
passed hello as the method name, after the name of the controller test in the URI.

Points to Remember
 The name of the controller class must start with an uppercase letter.
 The controller must be called with lowercase letter.
 Do not use the same name of the method as your parent class, as it will override
parent classs functionality.

Views
This can be a simple or complex webpage, which can be called by the controller. The
webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us
create a simple view. Create a new file under application/views with
name test.php and copy the below given code in that file.

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>

<body>
CodeIgniter View Example
</body>

</html>

Change the code of application/controllers/test.php file as shown in the below.

Loading the View


The view can be loaded by the following syntax −

$this->load->view('name');

Where name is the view file, which is being rendered. If you have planned to store the
view file in some directory then you can use the following syntax −

$this->load->view('directory-name/name');

It is not necessary to specify the extension as php, unless something other than .php is
used.

The index() method is calling the view method and passing the test as argument to view()
method because we have stored the html coding in test.php file
under application/views/test.php.

<?php
class Test extends CI_Controller {

public function index() {


$this->load->view('test');
}
}
?>

Here is the output of the above code −


The following flowchart illustrates of how everything works −

Models
Models classes are designed to work with information in the database. As an example, if
you are using CodeIgniter to manage users in your application then you must have model
class, which contains functions to insert, delete, update and retrieve your users data.

Creating Model Class


Model classes are stored in application/models directory. Following code shows how to
create model class in CodeIgniter.

<?php
Class Model_name extends CI_Model {

Public function __construct() {


parent::__construct();
}
}
?>

Where Model_name is the name of the model class that you want to give. Each model
class must inherit the CodeIgniters CI_Model class. The first letter of the model class must
be in capital letter. Following is the code for users model class.

<?php
Class User_model extends CI_Model {
Public function __construct() {
parent::__construct();
}

}
?>

The above model class must be saved as User_model.php. The class name and file name
must be same.

Loading Model
Model can be called in controller. Following code can be used to load any model.

$this->load->model('model_name');

Where model_name is the name of the model to be loaded. After loading the model you
can simply call its method as shown below.

$this->model_name->method();

Auto-loading Models
There may be situations where you want some model class throughout your application.
In such situations, it is better if we autoload it.

/*
| ---------------------------------------------------------------
| Auto-Load Models
| ---------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();

As shown in the above figure, pass the name of the model in the array that you want to
autoload and it will be autoloaded, while system is in initialization state and is accessible
throughout the application.

Helpers
As the name suggests, it will help you build your system. It is divided into small functions
to serve different functionality. A number of helpers are available in CodeIgniter, which
are listed in the table below. We can build our own helpers too.

Helpers are typically stored in your system/helpers, or application/helpers directory.


Custom helpers are stored in application/helpers directory and systems helpers are
stored in system/helpers directory. CodeIgniter will look first in
your application/helpers directory. If the directory does not exist or the specified
helper is not located, CodeIgniter will instead, look in your global system/helpers/
directory. Each helper, whether it is custom or system helper, must be loaded before
using it.

Given below are the most commonly used Helpers.

Loading a Helper
A helper can be loaded as shown below −

$this->load->helper('name');

Where name is the name of the helper. For example, if you want to load the URL Helper,
then it can be loaded as −

$this->load->helper('url');

Routing
CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL.
Typically, there is a one-to-one relationship between a URL string and its corresponding
controller class/method. The segments in a URI normally follow this pattern −

your-domain.com/class/method/id/
 The first segment represents the controller class that should be invoked.
 The second segment represents the class function, or method, that should be
called.
 The third, and any additional segments, represent the ID and any variables that
will be passed to the controller.

In some situations, you may want to change this default routing mechanism. CodeIgniter
provides facility through which you can set your own routing rules.

Customize Routing Rules


There is a particular file where you can handle all these. The file is located at
application/config/routes.php. You will find an array called $route in which you can
customize your routing rules. The key in the $route array will decide what to route and
the value will decide where to route. There are three reserved routes in CodeIgniter.

S.
Reserved Routes & Description
N.

1 $route['default_controller']
This route indicates which controller class should be loaded, if the URI
contains no data, which will be the case when people load your root URL.
You are encouraged to have a default route otherwise a 404 page will
appear, by default. We can set home page of website here so it will be
loaded by default.

$route['404_override']
This route indicates which controller class should be loaded if the requested
controller is not found. It will override the default 404 error page. It wont
2
affect to the show_404() function, which will continue loading the
default error_404.php file
in application/views/errors/error_404.php.

$route['translate_uri_dashes']
As evident by the Boolean value, this is not exactly a route. This option
enables you to automatically replace dashes (-) with underscores in the
3 controller and method URI segments, thus saving you additional route
entries if you need to do that. This is required because the dash is not a valid
class or method-name character and will cause a fatal error, if you try to use
it.

Routes can be customized by wildcards or by using regular expressions but keep in


mind that these customized rules for routing must come after the reserved rules.

Wildcards
We can use two wildcard characters as explained below −

 (:num) − It will match a segment containing only numbers.


 (:any) − It will match a segment containing any character.

Example

$route['product/:num']='catalog/product_lookup';

In the above example, if the literal word product is found in the first segment of the URL,
and a number is found in the second segment, the catalog class and the product_lookup
method are used instead.

Regular Expressions
Like wildcards, we can also use regular expressions in $route array key part. If any URI
matches with regular expression, then it will be routed to the value part set into $route
array.

Example

$route['products/([a-z]+)/(\d+)']='$1/id_$2';

In the above example, a URI similar to products/shoes/123 would instead call


the shoes controller class and the id_123 method.
CodeIgniter - Configuration
Previous
Quiz
Next

After setting up the site, the next thing that we should do is to configure the site. The
application/config folder contains a group of files that set basic configuration of your site.

Configuring Base URL


The base URL of the site can be configured in application/config/config.php file. It is URL
to your CodeIgniter root. Typically, this will be your base URL, with a trailing slash e.g.

http://example.com/

If this is not set, then CodeIgniter will try to guess the protocol, domain and path to your
installation. However, you should always configure this explicitly and never rely on
autoguessing, especially in production environments. You can configure the base URL in
the $config array with key base_url as shown below −

$config['base_url'] = 'http://your-domain.com';
Advertisement

Database Configuration
The database of the site can be configured in application/config/database.php file. Often
we need to set up database for different environment like development and production.
With the multidimensional array provided in the CodeIgniter, we can setup database for
different environment. The configuration settings are stored in the array as shown below

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);

You can leave few options to their default values except hostname, username, password,
database and dbdriver.

 hostname − Specify location of your database here e.g. localhost or IP address


 username − Set username of your database here.
 password − Set password of your database here.
 database − Set name of the database here.
 dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre
SQL, ODBC, and MS SQL.

By changing the key of the array $db, you can set other configuration of database as
shown below. Here, we have set the key to test to set the database for testing
environment, by keeping the other database environment as it is.

$db['test'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);

You can simply switch to different environment by changing the value of a variable as
shown below −

$active_group = default; //This will set the default environment

$active_group = test; //This will set the test environment


Autoload Configuration
This file specifies, by default, which systems should be loaded. In order to keep the
framework as light-weight as possible, only the absolute minimal resources are loaded by
default. One should autoload the frequently used system, rather than loading it at local
level, repeatedly. Following are the things you can load automatically −

 Libraries − It is a list of libraries, which should be auto loaded. Provide a list of


libraries in an array as shown below to be autoloaded by CodeIgniter. In this
example, we are auto loading database, email and session libraries.
$autoload['libraries'] = array('database', 'email', 'session');
 Drivers − These classes are located in system/libraries/ or in your
application/libraries/ directory, but are also placed inside their own subdirectory
and they extend the CI_Driver_Library class. They offer multiple interchangeable
driver options. Following is an example to autoload cache drivers.
$autoload['drivers'] = array('cache');
 Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries
in the array, as shown below, to be autoloaded by CodeIgniter. In the given
example, we are autoloading URL and file helpers.
$autoload['helper'] = array('url', 'file');
 Custom config files − These files are intended for use, only if you have created
custom config files. Otherwise, leave it blank. Following is an example of how to
autoload more than one config files.
$autoload['config'] = array('config1', 'config2');
 Language files − It is a list of language files, which should be auto loaded. Look at
the example given below. Provide a list of languages in an array as shown below to
be auto loaded by CodeIgniter. Keep in mind that do not include the "_lang" part of
your file. For example, "codeigniter_lang.php" would be referenced as
array('codeigniter');
 Models − It is a list of models file, which should be autoloaded. Provide a list of
models in an array as shown below to be autoloaded by CodeIgniter. Following is
the example of how to auto load more than one models files.
$autoload['model'] = array('first_model', 'second_model');

CodeIgniter - Working with Database


Previous
Quiz
Next

Like any other framework, we need to interact with the database very often and
CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact
with database.

In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions
work with CodeIgniter. We will use stud table to select, update, delete, and insert the
data in stud table.

Table Name: stud


roll_no int(11)

name varchar(30)

Connecting to a Database
We can connect to database in the following two way −

 Automatic Connecting − Automatic connection can be done by using the file


application/config/autoload.php. Automatic connection will load the database for
each and every page. We just need to add the database library as shown below −
$autoload['libraries'] = array(database);
 Manual Connecting − If you want database connectivity for only some of the
pages, then we can go for manual connecting. We can connect to database
manually by adding the following line in any class.
$this->load->database();

Here, we are not passing any argument because everything is set in the database config
file application/config/database.php

Advertisement

Inserting a Record
To insert a record in the database, the insert() function is used as shown in the following
table −

Syntax insert([$table = ''[, $set = NULL[, $escape = NULL]]])

 $table (string) − Table name


Parameter  $set (array) − An associative array of field/value pairs
s  $escape (bool) − Whether to escape values and
identifiers

Returns TRUE on success, FALSE on failure

Return
bool
Type

The following example shows how to insert a record in stud table. The $data is an array
in which we have set the data and to insert this data to the table stud, we just need to
pass this array to the insert function in the 2 nd argument.

$data = array(
'roll_no' => 1,
'name' => Virat
);

$this->db->insert("stud", $data);
Updating a Record
To update a record in the database, the update() function is used along
with set() and where() functions as shown in the tables below. The set() function will
set the data to be updated.

Syntax set($key[, $value = ''[, $escape = NULL]])

 $key (mixed) − Field name, or an array of field/value


pairs
Parameter
 $value (string) − Field value, if $key is a single field
s
 $escape (bool) − Whether to escape values and
identifiers

Returns CI_DB_query_builder instance (method chaining)

Return
CI_DB_query_builder
Type

The where() function will decide which record to update.

Syntax where($key[, $value = NULL[, $escape = NULL]])

 $key (mixed) − Name of field to compare, or


associative array
Parameter  $value (mixed) − If a single key, compared to this
s value
 $escape (bool) − Whether to escape values and
identifiers

Returns DB_query_builder instance

Return
object
Type

Finally, the update() function will update data in the database.

update([$table = ''[, $set = NULL[, $where = NULL[, $limit =


Syntax
NULL]]]])

 $table (string) − Table name


Parameter  $set (array) − An associative array of field/value pairs
s  $where (string) − The WHERE clause
 $limit (int) − The LIMIT clause

Returns TRUE on success, FALSE on failure

Return
bool
Type

$data = array(
'roll_no' => 1,
'name' => Virat
);

$this->db->set($data);
$this->db->where("roll_no", 1);
$this->db->update("stud", $data);

Deleting a Record
To delete a record in the database, the delete() function is used as shown in the following
table −

delete([$table = ''[, $where = ''[, $limit = NULL[, $reset_data


Syntax
= TRUE]]]])

 $table (mixed) − The table(s) to delete from; string or


array
Parameter  $where (string) − The WHERE clause
s  $limit (int) − The LIMIT clause
 $reset_data (bool) − TRUE to reset the query write
clause

CI_DB_query_builder instance (method chaining) or FALSE on


Returns
failure

Return
mixed
Type

Use the following code to to delete a record in the stud table. The first argument
indicates the name of the table to delete record and the second argument decides which
record to delete.

$this->db->delete("stud", "roll_no = 1");

Selecting a Record
To select a record in the database, the get function is used, as shown in the following
table −

Syntax get([$table = ''[, $limit = NULL[, $offset = NULL]]])

 $table (string) − The table to query array


Parameters  $limit (int) − The LIMIT clause
 $offset (int) − The OFFSET clause

Returns CI_DB_result instance (method chaining)

Return Type CI_DB_result


Use the following code to get all the records from the database. The first statement
fetches all the records from stud table and returns the object, which will be stored in
$query object. The second statement calls the result() function with $query object to get
all the records as array.

$query = $this->db->get("stud");
$data['records'] = $query->result();

Closing a Connection
Database connection can be closed manually, by executing the following code −

$this->db->close();

Example
Create a controller class called Stud_controller.php and save it
at application/controller/Stud_controller.php

Here is a complete example, wherein all of the above-mentioned operations are


performed. Before executing the following example, create a database and table as
instructed at the starting of this chapter and make necessary changes in the database
config file stored at application/config/database.php

<?php
class Stud_controller extends CI_Controller {

function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}

public function index() {


$query = $this->db->get("stud");
$data['records'] = $query->result();

$this->load->helper('url');
$this->load->view('Stud_view',$data);
}

public function add_student_view() {


$this->load->helper('form');
$this->load->view('Stud_add');
}

public function add_student() {


$this->load->model('Stud_Model');

$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);

$this->Stud_Model->insert($data);

$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}

public function update_student_view() {


$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}

public function update_student(){


$this->load->model('Stud_Model');

$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);

$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);

$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}

public function delete_student() {


$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
?>

Create a model class called Stud_Model.php and save it


in application/models/Stud_Model.php

<?php
class Stud_Model extends CI_Model {

function __construct() {
parent::__construct();
}

public function insert($data) {


if ($this->db->insert("stud", $data)) {
return true;
}
}

public function delete($roll_no) {


if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}

public function update($data,$old_roll_no) {


$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
}
?>

Create a view file called Stud_add.php and save it


in application/views/Stud_add.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<?php
echo form_open('Stud_controller/add_student');
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no','name'=>'roll_no'));
echo "<br/>";

echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name'));
echo "<br/>";

echo form_submit(array('id'=>'submit','value'=>'Add'));
echo form_close();
?>
</body>
</html>

Create a view file called Stud_edit.php and save it


in application/views/Stud_edit.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>

<body>
<form method = "" action = "">

<?php
echo form_open('Stud_controller/update_student');
echo form_hidden('old_roll_no',$old_roll_no);
echo form_label('Roll No.');
echo form_input(array('id'⇒'roll_no',
'name'⇒'roll_no','value'⇒$records[0]→roll_no));
echo "
";

echo form_label('Name');
echo form_input(array('id'⇒'name','name'⇒'name',
'value'⇒$records[0]→name));
echo "
";

echo form_submit(array('id'⇒'sub mit','value'⇒'Edit'));


echo form_close();
?>

</form>
</body>

</html>

Create a view file called Stud_view.php and save it


in application/views/Stud_view.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>

<body>
<a href = "<?php echo base_url(); ?>
index.php/stud/add_view">Add</a>

<table border = "1">


<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>Name</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";

foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td><a href = '".base_url()."index.php/stud/edit/"
.$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."index.php/stud/delete/"
.$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>

</body>

</html>

Make the following change in the route file at application/config/routes.php and add
the following line at the end of file.

$route['stud'] = "Stud_controller";
$route['stud/add'] = 'Stud_controller/add_student';
$route['stud/add_view'] = 'Stud_controller/add_student_view';
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1';
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';

Now, let us execute this example by visiting the following URL in the browser. Replace the
yoursite.com with your URL.

http://yoursite.com/index.php/stud

CodeIgniter - Libraries
Previous
Quiz
Next

The essential part of a CodeIgniter framework is its libraries. It provides a rich set of
libraries, which indirectly increase the speed of developing an application. The system
library is located at system/libraries. All we need to do is to load the library that we want
to use. The library can be loaded as shown below −

$this->load->library('class name');

Where class name is the name of the library that we want to load. If we want to load
multiple libraries, then we can simply pass an array as argument to library() function as
shown below −

$this->load->library(array('email', 'table'));
Library Classes
The library classes are located in system/libraries. Each class has various functions to
simplify the developing work. Following table shows the names of the library class and its
description.

Given below are the most commonly used Library Classes.


Advertisement

Creating Libraries
CodeIgniter has rich set of libraries, which you can find in system/libraries folder but
CodeIgniter is not just limited to system libraries, you can create your own libraries too,
which can be stored in application/libraries folder. You can create libraries in three
ways.

 Create new library


 Extend the native library
 Replace the native library

Create New Library


While creating new library one should keep in mind, the following things −

 The name of the file must start with a capital letter e.g. Mylibrary.php
 The class name must start with a capital letter e.g. class Mylibrary
 The name of the class and name of the file must match.

Mylibrary.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mylibrary {

public function some_function() {


}
}

/* End of file Mylibrary.php */

Loading the Custom Library

The above library can be loaded by simply executing the following line in your controller.

$this->load->library(mylibrary);

mylibrary is the name of your library and you can write it in lowercase as well as
uppercase letters. Use the name of the library without .php extension. After loading the
library, you can also call the function of that class as shown below.

$this->mylibrary->some_function();
Extend the Native Library
Sometimes, you may need to add your own functionality to the library provided by
CodeIgniter. CodeIgniter provides facility by which you can extend the native library and
add your own functions. To achieve this, you must extend the class of native library class.
For example if you want to extend the Email library then it can be done as shown below −

Class MY_Email extends CI_Email {


}

Here, in the above example, MY_Email class is extending the native librarys email class
CI_Email. This library can be loaded by the standard way of loading email library. Save the
above code in file My_Email.php

Replace the Native Library


In some situations, you do not want to use the native library the way it works and want to
replace it with your own way. This can be done by replacing the native library. To achieve
this, you just need to give the same class name as it is named in native library. For
example, if you want to replace the Email class, then use the code as shown below. Save
your file name with Email.php and give a class name to CI_Email.

Email.php

Class CI_Email {
}

CodeIgniter - Error Handling


Previous
Quiz
Next

Many times, while using application, we come across errors. It is very annoying for the
users if the errors are not handled properly. CodeIgniter provides an easy error handling
mechanism.

You would like the messages to be displayed, when the application is in developing mode
rather than in production mode as the error messages can be solved easily at the
developing stage.

The environment of your application can be changed, by changing the line given below
from index.php file. This can be set to anything but normally there are three values
(development, test, production) used for this purpose.

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] :


'development');
Different environment will require different levels of error reporting. By default,
development mode will display errors and testing and live mode will hide them.
CodeIgniter provides three functions as shown below to handle errors.

 show_error() function displays errors in HTML format at the top of the screen.
show_error($message, $status_code, $heading = 'An Error
Syntax
Was Encountered')

 $message (mixed) − Error message


Parameter
 $status_code (int) − HTTP Response status code
s
 $heading (string) − Error page heading

Return
mixed
Type
 show_404() function displays error if you are trying to access a page which does
not exist.
Syntax show_404($page = '', $log_error = TRUE)

Parameter  $page (string) URI string


s  $log_error (bool) Whether to log the error

Return
void
Type
 log_message() function is used to write log messages. This is useful when you
want to write custom messages.
Syntax log_message($level, $message, $php_error = FALSE)

 $level (string) − Log level: error, debug or info


Parameter  $message (string) − Message to log
s  $php_error (bool) − Whether were logging a native
PHP error message

Return
void
Type

Logging can be enabled in application/config/config.php file. Given below is the


screenshot of config.php file, where you can set threshold value.

/*
|--------------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disable logging, Error logging TURNED OFF
| 1 = Error Message (including PHP errors)
| 2 = Debug Message
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;

You can find the log messages in application/log/. Make sure that this directory is
writable before you enable log files.

Various templates for error messages can be found


in application/views/errors/cli or application/views/errors/html.

CodeIgniter - File Uploading


Previous
Quiz
Next

Using File Uploading class, we can upload files and we can also, restrict the type and size
of the file to be uploaded. Follow the steps shown in the given example to understand the
file uploading process in CodeIgniter.

Example
Copy the following code and store it at application/view/Upload_form.php.

<html>

<head>
<title>Upload Form</title>
</head>

<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>

<form action = "" method = "">


<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>

</body>

</html>

Copy the code given below and store it at application/view/Upload_success.php

<html>

<head>
<title>Upload Form</title>
</head>

<body>
<h3>Your file was successfully uploaded!</h3>

<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>

<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>


</body>

</html>

Copy the code given below and store it at application/controllers/Upload.php.


Create uploads folder at the root of CodeIgniter i.e. at the parent directory of application
folder.

<?php

class Upload extends CI_Controller {

public function __construct() {


parent::__construct();
$this->load->helper(array('form', 'url'));
}

public function index() {


$this->load->view('upload_form', array('error' => ' ' ));
}

public function do_upload() {


$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);

if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}

else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>

Make the following change in the route file in application/config/routes.php and add
the following line at the end of file.

$route['upload'] = 'Upload';

Now let us execute this example by visiting the following URL in the browser. Replace the
yoursite.com with your URL.

http://yoursite.com/index.php/upload

It will produce the following screen −

After successfully uploading a file, you will see the following screen −
CodeIgniter - Sending Email
Previous
Quiz
Next

Sending email in CodeIgniter is much easier. You also configure the preferences regarding
email in CodeIgniter. CodeIgniter provides following features for sending emails −

 Multiple Protocols − Mail, Sendmail, and SMTP


 TLS and SSL Encryption for SMTP
 Multiple recipients
 CC and BCCs
 HTML or Plaintext email
 Attachments
 Word wrapping
 Priorities
 BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
 Email Debugging tools

Email class has the following functions to simplify the job of sending emails.

Retur
S.
Syntax Parameters Return n
N.
Type

1 from($from[, $name = $from (string) − From CI_Email CI_Ema


''[, $return_path = e-mail address instance il
NULL]]) $name (string) − From (method
display name chaining)
$return_path (string)
− Optional email
address to redirect
undelivered e-mail to

$replyto (string) − E-
CI_Email
mail address for replies
reply_to($replyto[, $n instance CI_Ema
2 $name (string) −
ame = '']) (method il
Display name for the
chaining)
reply-to e-mail address

$to (mixed) − Comma- CI_Email


delimited string or an instance CI_Ema
2 to($to)
array of e-mail (method il
addresses chaining)

$cc (mixed) − Comma- CI_Email


delimited string or an instance CI_Ema
3 cc($cc)
array of e-mail (method il
addresses chaining)

$bcc (mixed) −
Comma-delimited string
CI_Email
or an array of e-mail
instance CI_Ema
4 bcc($bcc[, $limit = '']) addresses
(method il
$limit (int) − Maximum
chaining)
number of e-mails to
send per batch

CI_Email
$subject (string) − E- instance CI_Ema
5 subject($subject)
mail subject line (method il
chaining)

CI_Email
$body (string) − E-mail instance CI_Ema
6 message($body)
message body (method il
chaining)

CI_Email
$str (string) −
instance CI_Ema
7 set_alt_message($str) Alternative e-mail
(method il
message body
chaining)

$header (string) − CI_Email


set_header($header, Header name instance CI_Ema
8
$value) $value (string) − (method il
Header value chaining)

CI_Email
$clear_attachments (
clear([$clear_attachm instance CI_Ema
9 bool) Whether or not to
ents = FALSE]) (method il
clear attachments
chaining)

$auto_clear (bool) − CI_Email


send([$auto_clear = Whether to clear instance CI_Ema
10
TRUE]) message data (method il
automatically chaining)
$filename (string) −
File name
$disposition (string) −
disposition of the
attachment. Most email
clients make their own
attach($filename[, CI_Email
decision regardless of
$disposition = ''[, instance CI_Ema
11 the MIME specification
$newname = NULL[, (method il
used here. iana
$mime = '']]]) chaining)
$newname (string) −
Custom file name to use
in the e-mail
$mime (string) − MIME
type to use (useful for
buffered data)

Attachme
nt
$filename (string) −
attachment_cid($filen Content-
12 Existing attachment string
ame) ID or
filename
FALSE if
not found

Sending an Email
To send an email using CodeIgniter, first you have to load email library using the following

$this->load->library('email');

After loading the library, simply execute the following functions to set necessary elements
to send an email. The from() function is used to set − from where the email is being sent
and to() function is used − to whom the email is being sent.
The subject() and message() function is used to set the subject and message of the
email.

$this->email->from('your@example.com', 'Your Name');


$this->email->to('someone@example.com');

$this->email->subject('Email Test');
$this->email->message('Testing the email class.');

After that, execute the send() function as shown below to send an email.

$this->email->send();

Example
Create a controller file Email_controller.php and save it
in application/controller/Email_controller.php.

<?php
class Email_controller extends CI_Controller {

function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
}

public function index() {

$this->load->helper('form');
$this->load->view('email_form');
}

public function send_mail() {


$from_email = "your@example.com";
$to_email = $this->input->post('email');

//Load email library


$this->load->library('email');

$this->email->from($from_email, 'Your Name');


$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');

//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Email sent successfully.");
else
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('email_form');
}
}
?>

Create a view file called email_form.php and save it


at application/views/email_form.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter Email Example</title>
</head>

<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Email_controller/send_mail');
?>

<input type = "email" name = "email" required />


<input type = "submit" value = "SEND MAIL">

<?php
echo form_close();
?>
</body>

</html>

Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.

$route['email'] = 'Email_Controller';

Execute the above example by visiting the following link. Replace the yoursite.com with
the URL of your site.

http://yoursite.com/index.php/email

CodeIgniter - Form Validation


Previous
Quiz
Next

Validation is an important process while building web application. It ensures that the data
that we are getting is proper and valid to store or process. CodeIgniter has made this task
very easy. Let us understand this process with a simple example.

Example
Create a view file myform.php and save the below code it
in application/views/myform.php. This page will display form where user can submit
his name and we will validate this page to ensure that it should not be empty while
submitting.
<html>

<head>
<title>My Form</title>
</head>

<body>
<form action = "" method = "">
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "" size = "50" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>

</html>

Create a view file formsuccess.php and save it


in application/views/formsuccess.php. This page will be displayed if the form is
validated successfully.

<html>

<head>
<title>My Form</title>
</head>

<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor('form', 'Try it again!'); ?></p>
</body>

</html>

Create a controller file Form.php and save it in application/controller/Form.php. This


form will either, show errors if it is not validated properly or redirected
to formsuccess.php page.

<?php

class Form extends CI_Controller {

public function index() {


/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');

/* Set validation rule for name field in the form */


$this->form_validation->set_rules('name', 'Name', 'required');

if ($this->form_validation->run() == FALSE) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
}
}
?>

Add the following line in application/config/routes.php.

$route['validation'] = 'Form';

Let us execute this example by visiting the following URL in the browser. This URL may be
different based on your site.

http://yoursite.com/index.php/validation

It will produce the following screen −

We have added a validation in the controller − Name is required field before submitting
the form. So, if you click the submit button without entering anything in the name field,
then you will be asked to enter the name before submitting as shown in the screen below.

After entering the name successfully, you will be redirected to the screen as shown below.
In the above example, we have used the required rule setting. There are many rules
available in the CodeIgniter, which are described below.

Advertisement

Validation Rule Reference


The following is a list of all the native rules that are available to use −

Given below are the most commonly used list of native rules available to use.

CodeIgniter - Session Management


Previous
Quiz
Next

When building websites, we often need to track users activity and state and for this
purpose, we have to use session. CodeIgniter has session class for this purpose.

Initializing a Session
Sessions data are available globally through the site but to use those data we first need to
initialize the session. We can do that by executing the following line in constructor.

$this->load->library('session');

After loading the session library, you can simply use the session object as shown below.

$this->session
Advertisement

Add Session Data


In PHP, we simply use $_SESSION array to set any data in session as shown below.

$_SESSION[key] = value;

Where key is the key of array and value is assigned on right side of equal to sign.

The same thing can be done in CodeIgniter as shown below.

$this->session->set_userdata('some_name', 'some_value');
set_userdata() function takes two arguments. The first argument, some_name, is the
name of the session variable, under which, some_value will be stored.

set_userdata() function also supports another syntax in which you can pass array to
store values as shown below.

$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);

$this->session->set_userdata($newdata);

Remove Session Data


In PHP, we can remove data stored in session using the unset() function as shown below.

unset($_SESSION[some_name]);

Removing session data in CodeIgniter is very simple as shown below. The below version
of unset_userdata() function will remove only one variable from session.

$this->session->unset_userdata('some_name');

If you want to remove more values from session or to remove an entire array you can use
the below version of unset_userdata() function.

$this->session->unset_userdata($array_items);

Fetch Session Data


After setting data in session, we can also retrieve that data as shown
below. Userdata() function will be used for this purpose. This function will return NULL if
the data you are trying to access is not available.

$name = $this->session->userdata('name');

Example
Create a controller class called Session_controller.php and save it
in application/controller/Session_controller.php.

<?php
class Session_controller extends CI_Controller {

public function index() {


//loading session library
$this->load->library('session');

//adding data to session


$this->session->set_userdata('name','virat');

$this->load->view('session_view');
}

public function unset_session_data() {


//loading session library
$this->load->library('session');

//removing session data


$this->session->unset_userdata('name');
$this->load->view('session_view');
}

}
?>

Create a view file called session_view.php and save it


in application/views/session_view.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>

<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/
sessionex/unset'>
Click Here</a> to unset session data.
</body>

</html>

Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.

$route['sessionex'] = 'Session_Controller';
Execute the above example by using the following address. Replace yoursite.com with
the URL of your site.

http://yoursite.com/index.php/sessionex

CodeIgniter - Flashdata
Previous
Quiz
Next

While building web application, we need to store some data for only one time and after
that we want to remove that data. For example, to display some error message or
information message. In PHP, we have to do it manually but CodeIgniter has made this job
simple for us. In CodeIgniter, flashdata will only be available until the next request, and it
will get deleted automatically.

Add Flashdata
We can simply store flashdata as shown below.

$this->session->mark_as_flash('item');
 mark_as_flash() function is used for this purpose, which takes only one argument
of the value to be stored. We can also pass an array to store multiple values.
 set_flashdata() function can also be used, which takes two arguments, name and
value, as shown below. We can also pass an array.
$this->session->set_flashdata('item','value');
Advertisement

Retrieve Flashdata
Flashdata can be retrieved using the flashdata() function which takes one argument of the
item to be fetched as shown below. flashdata() function makes sure that you are getting
only flash data and not any other data.

$this->session->flashdata('item');

If you do not pass any argument, then you can get an array with the same function.

Example
Create a class called FlashData_Controller.php and save it
at application/controller/FlashData_Controller.php.

<?php
class FlashData_Controller extends CI_Controller {

public function index() {


//Load session library
$this->load->library('session');

//redirect to home page


$this->load->view('flashdata_home');
}

public function add() {


//Load session library
$this->load->library('session');
$this->load->helper('url');

//add flash data


$this->session->set_flashdata('item','item-value');

//redirect to home page


redirect('flashdata');
}
}
?>

Create a view file called flashdata_home.php and save it in application/views/


flashdata_home.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter Flashdata Example</title>
</head>

<body>
Flash Data Example
<h2><?php echo $this->session->flashdata('item'); ?></h2>
<a href = 'flashdata/add'>Click Here</a> to add flash data.
</body>

</html>

Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.

$route['flashdata'] = 'FlashData_Controller';
$route['flashdata/add'] = 'FlashData_Controller/add';
Execute the above example by visiting the following link. Replace the yoursite.com with
the URL of your site.

http://yoursite.com/index.php/flashdata

After visiting the above URL, you will see a screen as shown below.

Click on Click Here link and you will see a screen as shown below. Here, in this screen
you will see a value of flash data variable. Refresh the page again and you will see a
screen like above and flash data variable will be removed automatically.

CodeIgniter - Tempdata
Previous
Quiz
Next

In some situations, where you want to remove data stored in session after some specific
time-period, this can be done using tempdata functionality in CodeIgniter.

Add Tempdata
To add data as tempdata, we have to use mark_as_tempdata() function. This function
takes two argument items or items to be stored as tempdata and the expiration time for
those items are as shown below.

// 'item' will be erased after 300 seconds(5 minutes)


$this->session->mark_as_temp('item',300);
You can also pass an array to store multiple data. All the items stored below will be
expired after 300 seconds.

$this->session->mark_as_temp(array('item','item2'),300);

You can also set different expiration time for each item as shown below.

// 'item' will be erased after 300 seconds, while 'item2'


// will do so after only 240 seconds

$this->session->mark_as_temp(array(
'item'=>300,
'item2'=>240
));
Advertisement

Retrieve Tempdata
We can retrieve the tempdata using tempdata() function. This function assures that you
are getting only tempdata and not any other data. Look at the example given below to
see how to retrieve tempdata. tempdata() function will take one argument of the item to
be fetched.

$this->session->tempdata('item');

If you omit the argument, then you can retrieve all the existing tempdata.

Remove Tempdata
Tempdata is removed automatically after its expiration time but if you want to remove
tempdata before that, then you can do as shown below using
the unset_tempdata() function, which takes one argument of the item to be removed.

$this->session->unset_tempdata('item');

Example
Create a class called Tempdata_controller.php and save it
in application/controller/Tempdata_controller.php.

<?php
class Tempdata_controller extends CI_Controller {

public function index() {


$this->load->library('session');
$this->load->view('tempdata_view');
}
public function add() {
$this->load->library('session');
$this->load->helper('url');

//tempdata will be removed after 5 seconds


$this->session->set_tempdata('item','item-value',5);

redirect('tempdata');
}
}
?>

Create a file called tempdata_view.php and save it


in application/views/tempdata_view.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter Tempdata Example</title>
</head>

<body>
Temp Data Example
<h2><?php echo $this->session->tempdata('item'); ?></h2>
<a href = 'tempdata/add'>Click Here</a> to add temp data.
</body>

</html>

Make the changes in the routes.php file in application/config/routes.php and add the
following line at the end of the file.

$route['tempdata'] = "Tempdata_controller";
$route['tempdata/add'] = "Tempdata_controller/add";

Execute the above example by visiting the following link. Replace the yoursite.com with
the URL of your site.

http://yoursite.com/index.php/tempdata

After visiting the above URL, you will see a screen as shown below.
Click on Click Here link and you will see a screen as shown below.

Here, in this screen you will see a value of temp data variable. Refresh the same page
after five seconds again as we have set the temp data for five seconds and you will see a
screen like above and temp data variable will be removed automatically after five
seconds. If you refresh the same page before 5 seconds, then the temp data will not be
removed, as the time period is not over.

Destroying a Session
In PHP, we are using the session_destroy() function to destroy the session and in
CodeIgniter we can destroy the function as shown below.

$this->session->sess_destroy();

After calling this function, all the session data including the flashdata and tempdata will
be deleted permanently and cannot be retrieved back.

CodeIgniter - Cookie Management


Previous
Quiz
Next

Cookie is a small piece of data sent from web server to store on clients computer.
CodeIgniter has one helper called Cookie Helper for cookie management.
set_cookie($name[, $value = ''[, $expire = ''[, $domain =
Syntax ''[, $path = '/'[, $prefix = ''[, $secure = FALSE[, $httponly =
FALSE]]]]]]]])

 $name (mixed) − Cookie name or associative array of


all of the parameters available to this function
 $value (string) − Cookie value
 $expire (int) − Number of seconds until expiration
 $domain (string) − Cookie domain
Parameter (usually: .yourdomain.com)
s  $path (string) − Cookie path
 $prefix (string) − Cookie name prefix
 $secure (bool) − Whether to only send the cookie
through HTTPS
 $httponly (bool) − Whether to hide the cookie from
JavaScript

Return
void
Type

In the set_cookie() function, we can pass all the values using two ways. In the first way,
only array can be passed and in the second way, individual parameters can also be
passed.

Syntax get_cookie($index[, $xss_clean = NULL]])

 $index (string) − Cookie name


Parameter
 $xss_clean (bool) − Whether to apply XSS filtering
s
to the returned value

Return The cookie value or NULL if not found

Return
mixed
Type

The get_cookie() function is used to get the cookie that has been set using the
set_cookie() function.

delete_cookie($name[, $domain = ''[, $path = '/'[, $prefix =


Syntax
'']]]])

 $name (string) − Cookie name


 $domain (string) − Cookie domain
Parameter
(usually: .yourdomain.com)
s
 $path (string) − Cookie path
 $prefix (string) − Cookie name prefix

Return
void
Type

The delete_cookie() function is used to delete the cookie().


Example
Create a controller called Cookie_controller.php and save it
at application/controller/Cookie_controller.php

<?php
class Cookie_controller extends CI_Controller {

function __construct() {
parent::__construct();
$this->load->helper(array('cookie', 'url'));
}

public function index() {


set_cookie('cookie_name','cookie_value','3600');
$this->load->view('Cookie_view');
}

public function display_cookie() {


echo get_cookie('cookie_name');
$this->load->view('Cookie_view');
}

public function deletecookie() {


delete_cookie('cookie_name');
redirect('cookie/display');
}

}
?>

Create a view file called Cookie_view.php and save it


at application/views/Cookie_view.php

<!DOCTYPE html>
<html lang = "en">

<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>

<body>
<a href = 'display'>Click Here</a> to view the cookie.<br>
<a href = 'delete'>Click Here</a> to delete the cookie.
</body>

</html>

Change the routes.php file in application/config/routes.php to add route for the above
controller and add the following line at the end of the file.

$route['cookie'] = "Cookie_controller";
$route['cookie/display'] = "Cookie_controller/display_cookie";
$route['cookie/delete'] = "Cookie_controller/deletecookie";

After that, you can execute the following URL in the browser to execute the example.

http://yoursite.com/index.php/cookie

It will produce an output as shown in the following screenshot.

CodeIgniter - Common Functions


Previous
Quiz
Next

CodeIgniter library functions and helper functions need to be initialized before they are
used but there are some common functions, which do not need to be initialized.

These common functions and their descriptions are given below.

Syntax is_php($version)

Parameters $version (string) − Version number

TRUE if the running PHP version is at least the one specified or


Return
FALSE if not

Return
void
Type

Determines if the PHP version being used is greater than the


Description
supplied version number.

Syntax is_really_writable($file)

Parameters $file (string) − File path

Return TRUE if the path is writable, FALSE if not


Return
bool
Type

Description checks to see if file is writable or not.

Syntax config_item($key)

Parameters $key (string) − Config item key

Return Configuration key value or NULL if not found

Return
mixed
Type

Description This function is used to get the configuration item

Syntax set_status_header($code[, $text = ''])

$code (int) − HTTP Response status code


Parameters
$text (string) − A custom message to set with the status code

Return

Return
void
Type

Description This function permits you to manually set a server status header.

Syntax remove_invisible_characters($str[, $url_encoded = TRUE])

$str (string) − Input string


Parameters $url_encoded (bool) − Whether to remove URLencoded
characters as well

Return Sanitized string

Return
string
Type

This function prevents inserting NULL characters between


Description
ASCII characters

Syntax html_escape($var)

Parameters $var (mixed) − Variable to escape (string or array)

Return HTML escaped string(s)

Return
mixed
Type

Description This function acts as a native PHP htmlspecialchars() function.

Syntax get_mimes()
Return An associative array of file types

Return
array
Type

This function returns a reference to the MIMEs array


Description
from application/config/mimes.php.

Syntax is_https()

Return TRUE if currently using HTTP-over-SSL, FALSE if not

Return
bool
Type

Returns TRUE if a secure (HTTPS) connection is used and


Description
FALSE in any other case (including non-HTTP requests).

Syntax is_cli()

Return TRUE if currently running under CLI, FALSE otherwise

Return
bool
Type

Returns TRUE if the application is run through the command


Description
line and FALSE if not.

Syntax function_usable($function_name)

Parameters $function_name (string) − Function name

Return
bool
Type

Returns TRUE if a function exists and is usable, FALSE


Description
otherwise.

Given below is an example, which demonstrates all of the above functions.

Example
Here we have created only one controller in which we will use the above functions. Copy
the below given code and save it
at application/controller/CommonFun_Controller.php.

<?php
class CommonFun_Controller extends CI_Controller {

public function index() {


set_status_header(200);
echo is_php('5.3')."<br>";
var_dump(is_really_writable('./Form.php'));
echo config_item('language')."<br>";
echo remove_invisible_characters('This is a ‌test','UTF8')."<br>";

$str = '< This > is \' a " test & string';


echo html_escape($str)."<br>";
echo "is_https():".var_dump(is_https())."<br>";
echo "is_cli():".var_dump(is_cli())."<br>";

var_dump(function_usable('test'))."<br>";
echo "get_mimes():".print_r(get_mimes())."<br>";
}

public function test() {


echo "Test function";
}

}
?>

Change the routes.php file at application/config/routes.php to add route for the above
controller and add the following line at the end of the file.

$route['commonfunctions'] = 'CommonFun_Controller';

Type the following URL in the address bar of your browser to execute the example.

http://yoursite.com/index.php/commonfunctions

You might also like