PHP Notes Detailed
PHP Notes Detailed
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
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;
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
Open Compiler
<?php
 $x = 10;
 $y = "20";
x + y is: 30
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
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable
which is being assigned (the source variable).
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 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.
Output
It will produce the below outcome −
Open Compiler
<?php
 echo 'Hello ' . $name . ' How are you?';
?>
Open Compiler
<?php
 $name = "Rahul";
 echo "Hello $name How are you?";
?>
Output
It will produce the following result −
Open Compiler
<?php
 $name = "Rahul";
 echo 'Hello $name How are you?';
?>
Output
It will produce the following output −
Open Compiler
<?php
 echo 'Hello ', 'how ', 'are ', 'you?', "\n";
 echo 'Hello ' . 'how ' . 'are ' . 'you?' . "\n";
?>
Output
Here is the output of the above 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 −
Open Compiler
<?php
 $name = "Rajesh";
Output
Following is the output of the above code −
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.
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.
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
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".
$int_var = 12345;
$another_int = -12345 + 12345;
$var1 = 1.55;
$var2 =-123.0;
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;
$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).
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 = "";
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 −
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";
When you run this code, it will produce the following output −
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.
PHP also has Heredoc and Nowdoc representations of string data type.
<?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;
 print $channel;
?>
When you run this code, it will produce the following output −
<channel>
 <title>What's For Dinner</title>
 <link>http://menu.example.com/ </link>
 <description>Choose what to eat tonight.</description>
</channel>
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.
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;
?>
Programmers normally use the Null data type in PHP to initialize variables or to indicate
that a value is missing.
$my_var = NULL;
$my_var = null;
A variable that has been assigned NULL has the following properties −
Note − The data types of variables in PHP are determined at runtime based on the values
that are assigned to them.
$arr = array(
 "foo" => "bar",
 "bar" => "foo",
);
$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.
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.
class foo {
 function bar() {
 echo "Hello World.";
 }
}
$obj = new foo;
$obj->bar();
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.
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
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;
?>
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.
$var = (type)expr;
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.
Open Compiler
<?php
 $a = "99";
 $b = (int)$a;
 var_dump($b);
?>
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".
Open Compiler
<?php
 $a = "10 Rs.";
 $b = (int)$a;
 var_dump($b);
 $a = "$100";
 $b = (int)$a;
 var_dump($b);
?>
int(10)
int(0)
Open Compiler
<?php
 $a = 100;
 $b = (double)$a;
 var_dump($b);
?>
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);
?>
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);
?>
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);
?>
float(295.95)
float(0)
Open Compiler
<?php
 $a = 100;
 $b = (string)$a;
 var_dump($b);
 $x = 55.50;
 $y = (string)$x;
 var_dump($y);
?>
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.
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);
?>
bool(true)
bool(false)
bool(true)
  intval()
  floatval()
  strval()
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.
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;
42
4
42
34
34
34
26
26
26
0
1
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;
42
4.2
42
99.9
0
0
1
The doubleval() function is an alias of floatval() function, and hence returns similar
results.
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;
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);
?>
myclass
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.
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 −
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)
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"
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.
This makes sure that PHP does not change data types and makes your code more secure.
PHP Operators
Last Updated : 14 Jun, 2025
 
 
 
// 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
 Logical
 && $x && $y True if both the operands are true else false
 AND
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 || $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
!= 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
 Greater Than or
 >= $x >= $y Returns True if $x is greater than or equal to $y
 Equal To
Output
bool(true)
 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.
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
 $x +=
 += Add then Assign Simple Addition same as $x = $x + $y
 $y
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
 $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
 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
 Post-
 -- $x-- First, return $x, then decrement it by one
 Decrement
 $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
Output
GeeksforGeeks!!!
GeeksforGeeks!!!
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) {
?>
Output
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) {
else{
?>
Output
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") {
else{
?>
Output
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":
break;
case "Friday":
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Mid-week!";
?>
Output
Note:
 The switch statement compares the variable’s value strictly (both type and value).
  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
Example:
<?php
$age = 20;
echo ($age >= 18) ? "You are an adult." : "You are a minor.";
?>
Output
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
?>
Output
1
2
3
4
5
Output
1
2
3
4
5
Output
1
2
3
4
5
Output
10 20 30 40 50 60
Anjali => 25
Kriti => 30
Ayushi => 22
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
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:
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_STRING - When we pass 2 or SORT_STRING in the sorting_type parameter, the items in the
 array are compared string-wise
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:
Output :
Array
[0] => 1
[1] => 2
[2] => 3
[3] => 4
Output :
Array
(
<?php
// sort function
sort($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
print_r($array);
?>
Output:
Array
Program 3 : Program to demonstrate the use of sort() function to sort the string case-insensitively.
<?php
// case-insensitively
// string case-insensitively
print_r($array);
?>
Output:
Array
?>
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
 );
// 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
// Implementation of ksort()
ksort($arr);
?>
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
// Implementation of ksort
ksort($arr);
?>
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
 
 
 
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;
}
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
 
 
 
$num = 60;
function local_var() {
local_var();
?>
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;
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
 // Static variable
 static $num = 5;
 $sum = 2;
 $sum++;
 $num++;
?>
Output:
6
3
7
3
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
<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>
</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
 GET requests are only used to request POST requests can be used to create
 data (not modify) and modify data.
 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.
 In GET method only ASCII characters In POST method all types of data is
 are allowed. allowed.
Examples:
 Age is a number
Goal: Ensure the data is correct, complete, and safe before using it.
Examples:
✅ Validation Functions
o FILTER_VALIDATE_EMAIL
o FILTER_VALIDATE_INT
o FILTER_VALIDATE_URL
✅ Sanitization Functions
 htmlspecialchars()
 strip_tags()
o FILTER_SANITIZE_EMAIL
 o FILTER_SANITIZE_URL
✅ 5️⃣ Practical Example – Validating and Sanitizing a Form
html
CopyEdit
Message:<br>
<textarea name="message"></textarea><br>
</form>
php
CopyEdit
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);
// 2. Sanitize input
$name = htmlspecialchars($name);
$message = htmlspecialchars($message);
// 3. Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
 }
 // 4. Validate that name and message are not empty
if (empty($name) || empty($message)) {
// - Send an email
?>
➜ 1️⃣ Trimming
php
CopyEdit
trim($input)
➜ 2️⃣ Sanitization
php
CopyEdit
htmlspecialchars($name)
php
CopyEdit
filter_var($email, FILTER_SANITIZE_EMAIL)
  Removes illegal characters from email.
➜ 3️⃣ Validation
php
CopyEdit
filter_var($email, FILTER_VALIDATE_EMAIL)
php
CopyEdit
empty($name)
✅ Result
html
CopyEdit
</form>
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)) {
?>
PHP has a single function that can both sanitize and validate:
php
CopyEdit
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
Earlier versions of PHP used the MySQL extension. However, this extension was
deprecated in 2012.
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 support Prepared Statements. Prepared Statements protect from SQL injection, and
are very important for web application security.
  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.
PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
ADVERTISEMENT
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
$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());
}
// 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.
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
You will need special CREATE privileges to create or to delete a MySQL database.
// 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)
// 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);
?>
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.
A database table has its own unique name and consists of columns and rows.
We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":
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.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
}
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);
$conn = null;
?>
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());
}
// 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());
}
// 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.
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>
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());
}
// 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.
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.
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());
}
// 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.
The type definition string specify the data types of the corresponding bind
variables and contains one or more of the following four characters:
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.
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());
}
 // Set parameters
 $first_name = $_REQUEST['first_name'];
 $last_name = $_REQUEST['last_name'];
 $email = $_REQUEST['email'];
// 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.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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());
}
// Close connection
mysqli_close($link);
?>
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.
Consider we've a persons table inside the demo database that has following
records:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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());
}
// Close connection
mysqli_close($link);
?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+
+----+------------+-----------+---------------------+
+----+------------+-----------+---------------------+
  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:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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());
}
// Close connection
mysqli_close($link);
?>
After limiting the result set the output will look something like this:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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());
}
// Close connection
mysqli_close($link);
?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+
+----+------------+-----------+--------------------------+
+----+------------+-----------+--------------------------+
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.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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());
}
// Close connection
mysqli_close($link);
?>
After the deletion the persons table will look something like this:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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.
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.
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');
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.
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.
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";
 // 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;
 }
 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;
 // 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.
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";
 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"]);
 } 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>
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";
 // 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 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;
 }
 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;
 // 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"]);
 // Set parameters
 $param_id = $id;
 } 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>
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";
 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"]);
 // 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>
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.
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.
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 );
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'ajax_demo';
if ($conn->connect_error) {
$result = $conn->query($sql);
$users = [];
$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.
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">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Search Users</h2>
<div id="results"></div>
<script>
$(document).ready(function() {
$('#search').on('input', function() {
$.ajax({
url: 'fetch_data.php',
type: 'GET',
success: function(data) {
$('#results').html(output);
 },
 error: function() {
});
});
});
</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.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
 $name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
 $email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '';
 echo json_encode($response);
}
?>
This script checks for POST data, sanitizes it, and returns a JSON response.
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.
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.
$('#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.
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.
$.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
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
Add the token to your form:
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
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 −
 CodeIgniter - Installing
Previous
Quiz
Next
It is very easy to install CodeIgniter. Just follow the steps given below −
Directory Structure
The image given below shows the directory structure of the CodeIgniter.
  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.
  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.
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 {
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
<?php
 class Test extends CI_Controller {
  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>
$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 {
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.
<?php
 Class Model_name extends CI_Model {
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.
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.
 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.
Wildcards
We can use two wildcard characters as explained below −
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';
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.
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.
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 −
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.
name varchar(30)
Connecting to a Database
We can connect to database in the following two way −
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 −
 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.
 Return
 CI_DB_query_builder
 Type
 Return
 object
 Type
 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 −
 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.
Selecting a Record
To select a record in the database, the get function is used, as shown in the following
table −
$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
<?php
 class Stud_controller extends CI_Controller {
 function __construct() {
 parent::__construct();
 $this->load->helper('url');
 $this->load->database();
 }
 $this->load->helper('url');
 $this->load->view('Stud_view',$data);
 }
 $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);
}
 $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);
}
<?php
 class Stud_Model extends CI_Model {
 function __construct() {
 parent::__construct();
 }
<!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>
<!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 "
 ";
 </form>
 </body>
</html>
<!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>
 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.
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.
  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
class Mylibrary {
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 −
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
Email.php
Class CI_Email {
}
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.
  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')
 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)
 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)
 Return
 void
 Type
/*
|--------------------------------------------------------------------------------
| 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.
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');?>
</body>
</html>
<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>
</html>
<?php
 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
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 −
Email class has the following functions to simplify the job of sending emails.
 Retur
 S.
 Syntax Parameters Return n
 N.
 Type
 $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
 $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)
 CI_Email
 $clear_attachments (
 clear([$clear_attachm instance CI_Ema
9 bool) Whether or not to
 ents = FALSE]) (method il
 clear attachments
 chaining)
 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->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');
 }
 $this->load->helper('form');
 $this->load->view('email_form');
 }
 //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');
 }
 }
?>
<!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');
 ?>
 <?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
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>
<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>
<?php
 if ($this->form_validation->run() == FALSE) {
 $this->load->view('myform');
 }
 else {
 $this->load->view('formsuccess');
 }
 }
 }
?>
$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
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
Given below are the most commonly used list of native rules available to use.
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
$_SESSION[key] = value;
Where key is the key of array and value is assigned on right side of equal to sign.
$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);
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);
$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 {
 $this->load->view('session_view');
 }
 }
?>
<!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 {
<!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.
$this->session->mark_as_temp(array('item','item2'),300);
You can also set different expiration time for each item as shown below.
$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 {
 redirect('tempdata');
 }
 }
?>
<!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.
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]]]]]]]])
 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.
 Return
 mixed
 Type
The get_cookie() function is used to get the cookie that has been set using the
set_cookie() function.
 Return
 void
 Type
<?php
 class Cookie_controller extends CI_Controller {
 function __construct() {
 parent::__construct();
 $this->load->helper(array('cookie', 'url'));
 }
 }
?>
<!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
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.
Syntax is_php($version)
 Return
 void
 Type
Syntax is_really_writable($file)
Syntax config_item($key)
Return
 mixed
Type
Return
Return
 void
Type
Description This function permits you to manually set a server status header.
Return
 string
Type
Syntax html_escape($var)
Return
 mixed
Type
Syntax get_mimes()
 Return An associative array of file types
 Return
 array
 Type
Syntax is_https()
 Return
 bool
 Type
Syntax is_cli()
 Return
 bool
 Type
Syntax function_usable($function_name)
 Return
 bool
 Type
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 {
 var_dump(function_usable('test'))."<br>";
 echo "get_mimes():".print_r(get_mimes())."<br>";
 }
 }
?>
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