PHP & MYSQL Unit-1
PHP & MYSQL Unit-1
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially,
PHP was supposed to be an abbreviation for "Personal Home Page", but it now stands for the
recursive initialism "PHP: Hypertext Preprocessor".
Today, PHP is the world’s most popular server-side programming language for building web
applications. Over the years, it has gone through successive revisions and versions.
PHP - History
PHP started out as a small open-source project that evolved gradually as more and more people
found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994.
At that time, PHP stood for Personal Home Page, as he used it to maintain his personal
homepage. Later on, he added database support and called it as "Personal Home Page/Forms
Interpreter" or PHP/FI, which could be used to build simple, dynamic web applications.
Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP
3. The name of the language was also changed to the recursive acronym PHP: Hypertext
Preprocessor. They are also the authors of Zend Engine, a compiler and runtime
environment for the PHP. Zend Engine powered PHP 4 was released in May 2000.
PHP 5 was released in 2004, which included many new features such as OOP support,
the PHP Data Objects (PDO), and numerous performance enhancements.
PHP 7, is a new major PHP version which was developed in 2015. It included new
language features, most notable being, the introduction of return type declarations for
functions which complement the existing parameter type declarations, and support for the
scalar types (integer, float, string, and boolean) in parameter and return type declarations.
Features of PHP
Simplicity
Flexibility
● PHP scripts run seamlessly on various devices, including mobile, tablet, and PC.
● Can be embedded into HTML, XML, and JavaScript.
● Compatible with multiple databases, enhancing data manipulation options.
● Works efficiently with major web servers like Apache and IIS.
Object-Oriented Programming (OOP)
Interpreted Language
Efficiency
Fast Performance
Case-Sensitivity
Server-Side Scripting
PHP Versions
PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He
called this suite of scripts "Personal Home Page Tools". It can be regarded as PHP version 1.0.
In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL,
and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the
version 2.0 status.
PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi
Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a
mature interface for multiple databases, protocols and APIs, object-oriented
programming support, and consistent language syntax.
PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many
web servers, HTTP sessions, output buffering, secure ways of handling user input and
several new language constructs.
PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0
with a new object model and dozens of other new features. PHP's development team
includes dozens of developers and others working on PHP-related and supporting
projects such as PEAR, PECL, and documentation.
PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation
(phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the
important features of PHP 7 include its improved performance, reduced memory usage,
Return and Scalar Type Declarations and Anonymous Classes.
PHP 8.0 was released on 26 November 2020. This is a major version having many
significant improvements from its previous versions. One standout feature is Just-in-time
compilation (JIT) that can provide substantial performance improvements. The latest
version of PHP is 8.2.8, released on July 4th, 2023.
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that are
given below:
○ XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
We will learn how to install the XAMPP server on windows platform step by step. Follow the
below steps and install the XAMPP server on your system.
Step 1: Click on the above link provided to download the XAMPP server according to your
window requirement.
Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to
make changes in your system. A window will pop-up, where you have to click on the Next
button.
Step 3: Here, select the components, which you want to install and click Next.
Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.
Step 5: Click Next and move ahead.
Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.
Step 7: A finish window will display after successful installation. Click on the Finish button.
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on
the localhost.
PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal
Home Page.
We can use PHP in HTML code by simply adding a PHP tag without doing any extra work.
Example 1: First open the file in any editor and then write HTML code according to requirement.
If we have to add PHP code then we can add by simply adding <?php ….. ?> tags in between
and add your PHP code accordingly.
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<h1>
<?php
echo "Hii Hello PHP "
?>
</h1>
</body>
</html>
Understanding PHP
● Php runs on different OS like windows, unix and linux and support different Database
like mysql, ms access and oracle.
● Php can not only collect form data but it can also create, read, write, delete and close
files on the server.
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
There are two ways in which you can add comments to your PHP code. The first turns a single
line into a comment by preceding it with a pair of forward slashes:
// This is a comment
This version of the comment feature is a great way to temporarily remove a line of code from
a program that is giving you errors.
For example, you could use such a comment to hide a debugging line of code until you need it,
like this:
// echo "X equals $x";
You can also use this type of comment directly after a line of code to describe its action, like
this:
$x += 10; // Increment $x by 10
When you need multiple-line comments, there’s a second type of comment, which looks like
Example 3-2.
Example 3-2. A multiline comment
You can use the /* and */ pairs of characters to open and close comments almost anywhere
you like inside your code. Most, if not all, programmers use this construct to temporarily
comment out entire sections of code that do not work or that, for one reason or another, they
do not wish to be interpreted.
A common error is to use /* and */ to comment out a large section of code that already
contains a commented-out section that uses those characters. You can’t nest comments this
way; the PHP inter‐ preter won’t know where a comment ends and will display an error
message. However, if you use a program editor or IDE with syntax highlighting, this type of
error is easier to spot.
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
OUTPUT:
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:
3. Special Types
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
1. resource
2. NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or
FALSE (0). It is often used with conditional statements. If the condition is correct, it returns
TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
○ Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
○ The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31
to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $college = "Mahajana";
3. //both single and double quote statements will treat different
4. echo "Hello $college";
5. echo "</br>";
6. echo 'Hello $college';
7. ?>
Output:
Hello Mahajana
Hello $college
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM"
}
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function
calls or references to external PHP resources. For example - a database call. It is an external
resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
Output:
PHP keywords are predefined, reserved words in PHP that are used to perform specific
functions. These keywords are reserved by PHP and cannot be used as variable names,
function names, or class names. PHP keywords are case-insensitive, meaning that they can be
written in either upper or lower case letters.
Using Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
○ As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
1. $variablename=value;
○ A variable must start with a dollar ($) sign, followed by the variable name.
○ It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
○ One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
○ PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
Constants in PHP,
PHP constants are name or identifier that can't be changed during the execution of the script
except for magic constants, which are not really constants. PHP constants can be defined by 2
ways:
Constants are similar to the variable except once they defined, they can never be undefined or
changed. They remain constant across the entire program. PHP constants follow the same PHP
variable rules. For example, it can be started with a letter or underscore only.
Use the define() function to create a constant. It defines constant at run time. Let's see the syntax
of define() function in PHP.
1. <?php
2. define("MESSAGE","Hello PHP");
3. echo MESSAGE;
4. ?>
Hello PHP
PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const
keyword are case-sensitive.
1. <?php
2. const MESSAGE="Hello const by PHP";
3. echo MESSAGE;
4. ?>
Note: Unlike variables, constants are automatically global throughout the script.
Expressions in PHP,
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".
The most basic forms of expressions are constants and variables. When you type $a = 5, you're
assigning 5 into $a. 5, obviously, has the value 5, or in other words 5 is an expression with the
value of 5 (in this case, 5 is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd
expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value
of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the
following function:
<?php
function foo ()
{ return 5;}
?>
Operators in PHP.
As in any programming language, PHP also has operators which are symbols (sometimes
keywords) that are predefined to perform certain commonly required operations on one or more
operands.
For example, using the expression "4 + 5" is equal to 9. Here "4" and "5" are called operands and
"+" is called an operator.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. String Operators
6. Array Operators
7. Conditional (or Ternary Operators)
This chapter will provide an overview of how you can use these operators in PHP. In the
subsequent chapters, we will take a closer look at each of the operators and how they work.
The following table highligts the arithmetic operators that are supported by PHP. Assume
variable "$a" holds 42 and variable "$b" holds 20 −
You would use Comparison operators to compare two operands and find the relationship between
them. They return a Boolean value (either true or false) based on the outcome of the comparison.
The following table highligts the comparison operators that are supported by PHP. Assume
variable $a holds 10 and variable $b holds 20, then −
== Checks if the value of two operands are equal or not, if yes then ($a == $b) is
condition becomes true. not true
!= Checks if the value of two operands are equal or not, if values are ($a != $b) is
not equal then condition becomes true. true
> Checks if the value of left operand is greater than the value of right ($a > $b) is
operand, if yes then condition becomes true. false
< Checks if the value of left operand is less than the value of right ($a < $b) is
operand, if yes then condition becomes true. true
>= Checks if the value of left operand is greater than or equal to the ($a >= $b) is
value of right operand, if yes then condition becomes true. false
<= Checks if the value of left operand is less than or equal to the value ($a <= $b) is
of right operand, if yes then condition becomes true. true
You can use Logical operators in PHP to perform logical operations on multiple expressions
together. Logical operators always return Boolean values, either true or false.
Logical operators are commonly used with conditional statements and loops to return decisions
according to the Boolean conditions. You can also combine them to manipulate Boolean values
while dealing with complex expressions.
The following table high ligts the logical operators that are supported by PHP.
and Called Logical AND operator. If both the operands are true (A and B) is true
then condition becomes true.
&& Called Logical AND operator. If both the operands are non (A && B) is true
zero then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is false
state of its operand. If a condition is true then Logical NOT
operator will make false.
You can use Assignment operators in PHP to assign or update the values of a given variable with
a new value. The right-hand side of the assignment operator holds the value and the left-hand
side of the assignment operator is the variable to which the value will be assigned.
The data type of both the sides should be the same, else you will get an error. The associativity of
assignment operators is from right to left. PHP supports two types of assignment operators −
Simple Assignment Operator − It is the most commonly used operator. It is used to assign
value to a variable or constant.
Compound Assignment Operators − A combination of the assignment operator (=) with
other operators like +, *, /, etc.
The following table highligts the assignment operators that are supported by PHP −
There are two operators in PHP for working with string data types −
The "." (dot) operator is PHP's concatenation operator. It joins two string operands
(characters of right hand string appended to left hand string) and returns a new string.
PHP also has the ".=" operator which can be termed as the concatenation assignment
operator. It updates the string on its left by appending the characters of right hand
operand.
$third=$first.$second;
$leftstring=$rightstring
PHP defines the following set of symbols to be used as operators on array data types −
=== $a === $b Identity TRUE if $a and $b have the same key/value pairs in the
same order and of the same types.
There is one more operator in PHP which is called conditional operator. It is also known as
ternary operator. It first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.
All the operators we have discussed above can be categorised into following categories −
To force a certain operator to be called before other, parentheses should be used. In this example,
(2+6)/3 performs addition first, followed by division.
Some operators may have the same level of precedence. In that case, the order of associativity
(either left or right) decides the order of operations. Operators of same precedence level but are
non-associative cannot be used next to each other.
The following table lists the PHP operators in their decreasing order of precedence −
Operators Purpose
++ -- increment/decrement
instanceof types
! logical
*/ multiplication/division
% modulo
^ bitwise XOR
| bitwise OR
|| logical or
?? null coalescing
?: ternary
yield yield
print print
and logical
xor logical
or logical
Conditional statements:
The ability to implement conditional logic is the fundamental requirement of any programming
language (PHP included). PHP has three keywords (also called as language constructs) – if,
elseif and else – are used to take decision based on the different conditions.
The if keyword is the basic construct for the conditional execution of code fragments. More often
than not, the if keyword is used in conjunction with else keyword, although it is not always
mandatory.
If you want to execute some code if a condition is true and another code if the sme condition is
false, then use the "if....else" statement.
Syntax
The usage and syntax of the if statement in PHP is similar to that of the C language. Here is the
syntax of if statement in PHP −
if (expression)
code to be executed if expression is true;
else
code to be executed if expression is false;
PHP will execute the statement following the Boolean expression if it evaluates to true.
If the Boolean expression evaluates to false, the statement is ignored.
If the algorithm needs to execute another statement when the expression is false, it is
written after the else keyword.
<?php
$a=10;
$b=20;
if ($a > $b)
echo "a is bigger than b";
else
echo "a is not bigger than b";
?>
If you want to execute some code if one of the several conditions are true, then use the elseif
statement. The elseif language construct in PHP is a combination of if and else.
if (expr1)
code to be executed if expr1 is true;
elseif (expr2)
code to be executed if expr2 is true;
else
code to be executed if expr2 is false;
EXAMPLE
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "<h3>Have a nice weekend!</h3>";
else
echo "<h3>Have a nice day!</h3>";
?>
</body>
</html>
Switch
The switch statement is followed by an expression, which is successively compared with value
in each case clause. If it is found that the expression matches with any of the cases, the
corresponding block of statements is executed.
The switch statement executes the statements inside the curly brackets line by line.
If and when a case statement is found whose expression evaluates to a value that matches
the value of the switch expression, PHP starts to execute the statements until the end of
the switch block, or the first time it encounters a break statement.
If you don't write a break statement at the end of a case's statement list, PHP will go on
executing the statements of the following case.
<?php
$x=0;
switch ($x) {
case 0:
echo "x equals 0 \n";
case 1:
echo "x equals 1 \n";
case 2:
echo "x equals 2 \n";
}
?>
x equals 0
x equals 1
x equals 2
The ‘?’Operator,
One way of avoiding the verbosity of if and else statements is to use the more com‐ pact
ternary operator, ?, which is unusual in that it takes three operands rather than the typical two.
The ? operator is passed an expression that it must evaluate, along with two state‐ments to
execute: one for when the expression evaluates to TRUE, the other for when it is FALSE.
The easiest way to create a loop in a PHP script is with the while construct. The syntax of while
loop in PHP is similar to that in C language. The loop body block will be repeatedly executed as
long as the Boolean expression in the while statement is true.
The following flowchart helps in understanding how the while loop in PHP works −
The value of the expression is checked each time at the beginning of the loop. If the while
expression evaluates to false from the very beginning, the loop won't even be run once. Even if
the expression becomes false during the execution of the block, the execution will not stop until
the end of the iteration.
while (expr){
statements
}
EXAMPLE
<?php
$x = 1;
while ($x<=10) {
echo "Iteration No. $x \n";
$x++;
}
?>
It will produce the following output −
Iteration No. 1
Iteration No. 2
Iteration No. 3
Iteration No. 4
Iteration No. 5
Iteration No. 6
Iteration No. 7
Iteration No. 8
Iteration No. 9
Iteration No. 10
do-while Loop,
The "do…while" loop is another looping construct available in PHP. This type of loop is similar
to the while loop, except that the test condition is checked at the end of each iteration rather than
at the beginning of a new iteration.
The while loop verifies the truth condition before entering the loop, whereas in "do…while"
loop, the truth condition is verified before re entering the loop. As a result, the "do…while" loop
is guaranteed to have at least one iteration irrespective of the truth condition.
The following figure shows the difference in "while" loop and "do…while" loop by using a
comparative flowchart representation of the two.
The syntax for constituting a "do…while" loop is similar to its counterpart in C language.
do {
statements;
}
while (expression);
EXAMPLE
<?php
$i=1;
do{
echo "Iteration No: $i \n";
$i++;
}
while ($i<=5);
?>
Iteration No: 1
Iteration No: 2
Iteration No: 3
Iteration No: 4
Iteration No: 5
for Loop.
The for statement is used when you know how many times you want to execute a statement or
a block of statements.
The syntax of for statement in PHP is similar to the for statement in C language.
Iteration No: 1
Iteration No: 2
Iteration No: 3
Iteration No: 4
Iteration No: 5
Iteration No: 6
Iteration No: 7
Iteration No: 8
Iteration No: 9
Iteration No: 10
Foreach Loop
The foreach construct in PHP is specially meant for iterating over arrays. If you try to use it on a
variable with a different data type, PHP raises an error.
The foreach loop in PHP can be used with indexed array as well as associative array. There are
two types of usage syntaxes available −
statements
The above method is useful when you want to iterate an indexed array. The syntax below is more
suitable for associative arrays.
statements
EXAMPLE
<?php
?>
It will produce the following output −
Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40
Element at index 4 is 50