Professional Documents
Culture Documents
PHP MySQL
PHP MySQL
By:
Satish Naik
Published by
Course Outcomes (COs): At the end of the course students will be able to:CO1: Design dynamic and
interactive web pages and websites. CO2: Run PHP scripts on the server and retrieve results.
CO3: Handle databases like MySQL using PHP in websites.
Unit Contents Page Nos
Introduction to PHP: Introduction to PHP, History and Features of PHP, Installation &
Configuration of PHP, Embedding PHP code in Your Web Pages, Understanding PHP,
Unit I HTML and White Space, Writing Comments in PHP, Sending Data to the Web Browser,
Data types in PHP, Keywords in PHP, Using Variables, Constants in PHP, Expressions
in PHP, Operators in PHP.
Programming with PHP: Conditional statements: if, if-else, switch, The? Operator,
Unit II Looping statements: while Loop, do-while Loop, for Loop
Arrays in PHP: Introduction- What is Array? Creating Arrays, Accessing Array
elements, Types of Arrays: Indexed v/s Associative arrays, Multidimensional arrays,
Creating Array, Accessing Array, Manipulating Arrays, displaying array, Using Array
Functions, Including and Requiring Files- use of Include () and Require (), Implicit and
Explicit Casting in PHP.
Using Functions, Class- Objects, Forms in PHP: Functions in PHP, Function
definition, Creating and invoking user-defined functions, Formal parameters versus
Unit III actual parameters, Function and variable scope, Recursion, Library functions, Date
and Time Functions Strings in PHP: What is String? , Creating and Declaring String,
String Functions
Class &Objects in PHP: What is Class & Object, Creating and accessing a Class
&Object, Object properties, object methods, Overloading, inheritance, Constructor and
Destructor
Form Handling: Creating HTML Form, Handling HTML Form data in PHP
Database Handling Using PHP with MySQL: Introduction to MySQL: Database
terms, Data Types.
Accessing MySQL –Using MySQL Client and Using PHP MyAdmin, MySQL
Unit IV Commands, Using PHP with MySQL: PHP MySQL Functions, connecting to MySQL
and Selecting the Database, Executing Simple Queries, Retrieving Query Results,
Counting Returned Records, Updating Records with PHP
References:
1. PHP & MySQL for Dynamic Web Sites-Fourth Edition By Larry Ullman.
2. Learning PHP, MySQL and JavaScript By Robin Nixon–O‟REILLY Publications
3. Programming PHP By RasmusLerdorf, Kevin Tatroe, Peter Macintyre
4. SAMS Teach Yourself PHP in 24 hours, Author: Matt Zandstra, Sams Publishing
PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is
the latest version of PHP, which was released on 28 November. Some important points need to
be noticed about PHP are as followed:
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below:
Performance:
PHP script is executed much faster than those scripts which are written in other languages such as
JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically
reduced, which results in faster processing speed and better performance.
Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic websites easily. But
you must have the basic the knowledge of following technologies for web development as well.
o HTML
o CSS
o JavaScript
Kamadhenu BCA College -5-
o Ajax
o XML and JSON
o jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript.
So, learn these technologies for better implementation of PHP.
CSS - CSS helps to make the webpage content more effective and attractive.
History of PHP
As it is realized today, PHP is truly the standby to an item named PHP/FI. It was introduced in 1994
by Rasmus Lerdorf, the absolute first exhibition of PHP was a direct arrangement of Common
Gateway Interface (CGI) parallels inscribed in the C programming language. Initially utilized for
ensuring visits to his internet-based resume, he named the set-up contents " the Individual
Home Page Tools," all the more normally referred to as " the PHP Tools." With time,
furthermore, functionalities were wanted, and Lerdorf revised his PHP Tools, capable of delivering
a lot bigger and more extravagant execution. This model now was capable of information base
cooperation; this gives a structured framework through which clients could faster basic powerful
web applications. In June of 1995, Lerdorf delivered his source code for the PHP Tools developers'
population, allowing engineers and developers worldwide to use it to their best advantage. This
additionally allowed and urged clients to give bug fixes in the code and, for the best part, to refine
it.
In September 1995, Lerdorf redeveloped PHP, and he dropped the name PHP. Presently alluding
to the devices as FI (another way to say " Form Interpreter " ), the new execution incorporated
a portion of the fundamental usefulness of PHP as far as we might be concerned today. It had
variables that were somewhat similar to Perl, form variables can be automatically distinguished,
and HTML imbibed syntax. PHP resembles pearl in syntax but is considerably more limited, easy
to use, and unpredictable. Indeed, to imbibe the code into an HTML document, developers have
to utilize comments in HTML. However, this strategy was not completely welcomed. FI kept getting
popular as a CGI instrument but not exactly as a language.
The language was purposely intended to look alike C in structure, making it a simple reception for
developers acquainted with C, Perl, and commonly available languages. Notwithstanding, this
started to change the next month; in October 1995, Lerdorf delivered a total revise of the code.
Bringing back the original name PHP, it was momentarily named "Personal Home Page
Construction Kit," It was only released to boast that it was the most advanced scripting interface
present.
Throughout its history, PHP has evolved from a simple set of tools for managing personal
homepages to a powerful, versatile language used by millions of developers worldwide for
building dynamic web applications, content management systems, e-commerce platforms, and
more. It continues to evolve with regular updates and contributions from a large and active
community.
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.
Step 1: Click on the above link provided to download the XAMPP server according to your
window requirement.
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 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.
Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in
the text editor in which we want to use the PHP.
1. <!Doctype Html>
2. <Html>
3. <Head>
4. <Title>
5. Use a Php in Html
6. </Title>
7. </Head>
8. <Body>
9. </Body>
10. </Html>
Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the
code of PHP. And, then we have to type the start and end tag of PHP.
1. <h1>
2. <?php ?>
3. </h1>
Step 3: After then, we have to type the code of PHP between the tags of PHP.
1. <h1>
2. <?php
3. echo "Hii User!! You are at JavaTpoint Site"
4. ?>
5. </h1>
Step 4: When we successfully add the PHP code, then we have to save the Html file and then run
the file in the browser.
1. <!Doctype Html>
2. <Html>
3. <Head>
4. <Title>
5. Use a Php in Html
6. </Title>
7. </Head>
Example #1
Code:
<html>
<title>First Application of PHP</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
echo "Welcome User";
?>
</body>
</html>
White Space
White Space is a property defined in CSS (Cascading Style Sheets) that enable the user to
control the text wrapping and white spaces inside an element of the website. It can take
several types of values depending upon the user's need.
Normal: It is the default value for the property. It will perform text wrapping whenever necessary.
When the normal value is assigned to the white-space property, every sequence with more than
two spaces will be replaced by a single white space.
Syntax
1. white-space: normal;
Below is an example to illustrate the implementation of white-space property using normal as the
value.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> CSS | white-space Property using normal value</title>
5. <style>
6. div {
7. width: 500px;
8. height: 500px;
9. white-space: normal;
10. background-color: rgb(23, 102, 23);
11. color: white;
12. font-size: 30px;
13. }
14. </style>
15. </head>
16.
17. <body>
18. <center>
Kamadhenu BCA College -15-
19. <div> Using white-space property
20. <br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptas, illum.
21. </div>
22. </center>
23. </body>
24. </html>
Nowrap: When the white space property is assigned a nowrap value. Every sequence of
characters with more than two spaces will be represented as a single space. It won't
perform wrapping unless the user specifies it.
Syntax
1. white-space: nowrap;
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> CSS | white-space Property using nowrap value</title>
5. <style>
6. div {
7. width: 500px;
8. height: 500px;
9. white-space: nowrap;
10. background-color: rgb(23, 102, 23);
11. color: rgb(133, 28, 28);
12. font-size: 30px;
13. }
14. </style>
Kamadhenu BCA College -16-
15. </head>
16.
17. <body>
18. <center>
19. <div> Using white-space property
20. <br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptas, illum.
21. </div>
22. </center>
23. </body>
24. </html>
Output:
PHP Comments
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code. PHP supports single line
and multi-line comments. These comments are similar to C/C++ and Perl style (Unix shell
style) comments.
Output:
Welcome to PHP multi line comment
The form request may be get or post. To retrieve data from get request, we need to use $_GET,
for post request $_POST.
1. GET method
2. POST method
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
Kamadhenu BCA College -18-
PHP Post Form
Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc. The data passed through post
request is not visible on the URL browser so it is secured. You can send large amount of
data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variab
le
echo "Welcome: $name, your password is: $password";
?>
Output:
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:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
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:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
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:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
PHP Keywords
PHP has a set of keywords that are reserved words which cannot be used as function names, class
names or method names. Prior to PHP 7, these keywords could not be used as class property
names either:
Keyword Description
abstract Declare a class as abstract
and A logical operator
as Used in the foreach loop
break Break out of loops and switch statements
Kamadhenu BCA College -23-
callable A data type which can be executed as a function
case Used in the switch conditional
catch Used in the try..catch statement
class Declare a class
clone Create a copy of an object
const Define a class constant
continue Jump to the next iteration of a loop
declare Set directives for a block of code
default Used in the switch statement
do Create a do...while loop
echo Output text
else Used in conditional statements
elseif Used in conditional statements
empty Check if an expression is empty
enddeclare End a declare block
endfor End a for block
endforeach End a foreach block
endif End an if or elseif block
endswitch End a switch block
endwhile End a while block
extends Extends a class or interface
final Declare a class, property or method as final
finally Used in the try...catch statement
fn Declare an arrow function
for Create a for loop
foreach Create a foreach loop
function Create a function
global Import variables from the global scope
goto Jump to a line of code
if Create a conditional statement
implements Implement an interface
include Embed code from another file
include_once Embed code from another file
instanceof Test an object's class
insteadof Resolve conflicts with traits
interface Declare an interface
isset Check if a variable exists and is not null
list Assigns array elements into variables
namespace Declares a namespace
new Creates an object
or A logical operator
print Output text
private Declare a property, method or constant as private
protected Declare a property, method or constant as
protected
public Declare a property, method or constant as public
require Embed code from another file
require_once Embed code from another file
return Exit a function and return a value
static Declare a property or method as static
Kamadhenu BCA College -24-
switch Create a switch block
throw Throw an exception
trait Declare a trait
try Create a try...catch structure
unset Delete a variable or array element
use Use a namespace
var Declare a variable
while Create a while loop or end a do...while loop
xor A logical operator
yield Used in generator functions
yield from Used in generator functions
PHP Variables
Variables are "containers" for storing information.
In the example above, the variable $x will hold the value 5, and the
variable $y will hold the value "John".
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
$txt = "W3Schools.com";
echo "I love $txt!";
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
The following example will output the sum of two variables:
$x = 5;
$y = 4;
echo $x + $y;
PHP automatically associates a data type to the variable, depending on its value.
Since the data types are not set in a strict sense, you can do things like adding a
string to an integer without causing an error.
In PHP 7, type declarations were added. This gives an option to specify the data type
expected when declaring a function, and by enabling the strict requirement, it will
throw a "Fatal Error" on a type mismatch.
Variable Types
PHP has no command for declaring a variable, and the data type depends on the
value of the variable.
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
You can assign the same value to multiple variables in one line:
$x = $y = $z = "Fruit";
The scope of a variable is the part of the script where the variable can be
referenced/used.
$x = 5; // global scope
function myTest() {
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
Kamadhenu BCA College -27-
myTest();
$x = 5;
$y = 10;
function myTest() {
$y = $x + $y;
myTest();
$y = 10;
function myTest() {
myTest();
To do this, use the static keyword when you first declare the variable:
function myTest() {
static $x = 0;
echo $x;
$x++;
myTest();
myTest();
myTest();
PHP Constants
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:
1. Using define() function
2. Using const keyword
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.
Conventionally, PHP constants should be defined in uppercase letters.
Output:
File: constant2.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
echo MESSAGE, "</br>";
echo message;
?>
Output:
Hello JavaTpoint PHP
Hello JavaTpoint PHP
File: constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
File: constant4.php
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Constant() function
There is another way to print the value of constants using constant() function instead of using the
echo statement.
Syntax
Constant vs Variables
Constant Variables
Once the constant is defined, it can never be A variable can be undefined as well as
A constant can only be defined using define() A variable can be defined by simple
function. It cannot be defined by any simple assignment (=) operator.
assignment.
There is no need to use the dollar ($) sign To declare a variable, always use the dollar ($)
before constant during the assignment. sign before the variable.
Constants do not follow any variable scoping Variables can be declared anywhere in the
rules, and they can be defined and accessed program, but they follow variable scoping
anywhere. rules.
Constants are the variables whose values can't The value of the variable can be changed.
be changed throughout the program.
Introduction
Anything that has a value is an expression. In a typical assignment statement
($x=100), a literal value, a function or operands processed by operators is an
expression, anything that appears to the right of assignment operator (=)
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and
optional modifiers.
$exp = "/w3schools/i";
In the example above, / is the delimiter, w3schools is the pattern that is being
searched for, and i is a modifier that makes the search case-insensitive.
The delimiter can be any character that is not a letter, number, backslash or
space. The most common delimiter is the forward slash (/), but when your pattern
contains forward slashes it is convenient to choose other delimiters such as # or
~.
$pattern = "/w3schools/i";
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a
pattern in a string.
Example
Use a regular expression to do a case-insensitive count of the number of
occurrences of "ain" in a string:
$pattern = "/ain/i";
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values. For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
PHP Operators can be categorized in following forms:
Category Operator Description
Arithmetic + Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
** Exponentiation
Assignment = Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
Kamadhenu BCA College -33-
Comparison == Equal
=== Identical
!= or <> Not equal
!== Not identical
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical && or and Logical AND
`
xor Exclusive OR
! Logical NOT
Bitwise & Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
<< Shift left
>> Shift right
String . Concatenation
Increment/Decrement ++ Increment
-- Decrement
Ternary ? : Conditional (Ternary)
Null Coalescing ?? Null Coalescing (PHP 7)
Spaceship <=> Spaceship (PHP 7)
We can also categorize operators on behalf of operands. They can be categorized in 3
forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement
in PHP.
o if
o if-else
o if-else-if
o nested if
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true. If
statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
if(condition){
//code to be executed
}
Flowchart
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
12 is less than 100
PHP if-else statement is executed whether condition is true or false. If-else statement is
slightly different from if statement. It executes one block of code if the specified
condition is true and another block of code if the condition is false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:
12 is even number
Output:
B Grade
Output:
<?php
$a = 34; $b = 56; $c = 45;
if ($a < $b) {
if ($a < $c) {
echo "$a is smaller than $b and $c";
}
}
?>
Output:
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works
like PHP if-else-if statement.
break; 30");
case 20: }
echo("number is equal to 20"); ?>
break;
Output:
number is equal to 20
1. <?php
2. $car = "Hyundai";
3. $model = "Tucson";
4. switch( $car )
5. {
6. case "Honda":
7. switch( $model )
Output:
Practice programs:
if ($number % 2 == 0) {
echo "$number is even";
} else {
echo "$number is odd";
}
?>
<?php
$a = 10;
$b = 20;
$c = 15;
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
Kamadhenu BCA College -43-
case "Tuesday":
echo "Today is Tuesday";
break;
case "Wednesday":
echo "Today is Wednesday";
break;
case "Thursday":
echo "Today is Thursday";
break;
case "Friday":
echo "Today is Friday";
break;
case "Saturday":
echo "Today is Saturday";
break;
case "Sunday":
echo "Today is Sunday";
break;
default:
echo "Invalid day";
}
?>
<?php
$month = 3;
switch ($month) {
case 1:
echo "January";
break;
case 2:
echo "February";
break;
case 3:
echo "March";
break;
case 4:
echo "April";
break;
case 5:
echo "May";
break;
case 6:
echo "June";
break;
case 7:
echo "July";
break;
case 8:
echo "August";
break;
case 9:
echo "September";
Kamadhenu BCA College -44-
break;
case 10:
echo "October";
break;
case 11:
echo "November";
break;
case 12:
echo "December";
break;
default:
echo "Invalid month";
}
?>
Below is a PHP program with HTML form elements that accept an ID and password. Upon
submission, the program checks whether the provided ID and password match predefined
values. If they match, it displays a success message; otherwise, it displays an error message.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
<?php
// Define predefined ID and password
$valid_id = "user123";
$valid_password = "password123";
This program consists of an HTML form that accepts an ID and password. Upon form submission
(by clicking the "Login" button), the PHP code checks whether the provided ID and password
match the predefined values (user123 for ID and password123 for password). If the provided
credentials match, it displays a success message; otherwise, it displays an error message.
?: Operator : The ? operator in PHP is known as the ternary operator. It's a shorthand way of
writing an if...else statement in a single line. It evaluates a condition and returns one value if
the condition is true, and another value if the condition is false.
Here are two examples demonstrating the usage of the ternary operator:
<?php
$age = 20;
Looping, in programming, refers to the repetition of a block of code multiple times until
a certain condition is met. It allows you to automate repetitive tasks and process large
amounts of data efficiently.
PHP supports several types of loops, including for, while, do-while, and foreach. Here's an
overview of each type:
It should be used if the number of iterations is known otherwise use while loop. This means
for loop is used when you already know how many times you want to execute a block of
code.
It allows users to put all the loop related statements in one place. See in the syntax given
below:
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
1
2
3
4
5
6
7
8
9
10
1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
Output:
1
2
3
4
.
.
.
Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
1. <?php
2. /* example 1 */
3.
4. for ($i = 1; $i <= 9; $i++) {
5. echo $i;
6. }
7. echo "</br>";
8.
9. /* example 2 */
10.
11. for ($i = 1; ; $i++) {
12. if ($i > 9) {
13. break;
14. }
Kamadhenu BCA College -49-
15. echo $i;
16. }
17. echo "</br>";
18.
19. /* example 3 */
20.
21. $i = 1;
22. for (; ; ) {
23. if ($i > 9) {
24. break;
25. }
26. echo $i;
27. $i++;
28. }
29. echo "</br>";
30.
31. /* example 4 */
32.
33. for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
34. ?>
Output:
123456789
123456789
123456789
123456789
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop.
If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop
will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times
for 3rd outer loop).
Example
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Syntax
Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }
Syntax
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn
Practice programs :
Program to iterate over an array and display each element:
<?php
$colors = array("Red", "Green", "Blue");
1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "[email protected]",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>
Output:
Name : Alex
Email : [email protected]
Age : 21
Gender : Male
Example 3:
Multi-dimensional array
1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
5. $a[0][1] = "Bob";
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {
Output:
<?php
$student_scores = array("Alice" => 85, "Bob" => 92, "Charlie" => 78);
<?php
$books = array(
array("Title" => "The Great Gatsby", "Author" => "F. Scott Fitzgerald"),
array("Title" => "To Kill a Mockingbird", "Author" => "Harper Lee"),
array("Title" => "1984", "Author" => "George Orwell")
);
In these examples:
• Example 1 iterates over a simple indexed array of colors and prints each color.
• Example 2 iterates over an associative array of student scores and prints each
student's name along with their score.
• Example 3 iterates over a multidimensional array of books, and for each book, it
iterates over the key-value pairs and prints each key-value pair.
The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is true, the
block of code will be executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart
Output:
1
2
3
4
5
6
7
8
9
10
Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
Below is the example of printing alphabets using while loop.
1. <?php
2. $i = 'A';
3. while ($i < 'H') {
4. echo $i;
Output:
A
B
C
D
E
F
G
Syntax
1. while(true) {
2. //code to be executed
3. }
Example
1. <?php
2. while (true) {
3. echo "Hello K-BCA!";
4. echo "</br>";
5. }
6. ?>
Output:
The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is recommended
to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
Kamadhenu BCA College -58-
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the
do-while loop, it is must that the program should not contain any other statements after
the do-while loop. In this case, it will not generate any error.
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Example
The following example will increment the value of $x at least once. Because the given
condition is false.
Output:
PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and
for-each loop. If you use break inside inner loop, it breaks the execution of inner loop
only.
The break keyword immediately ends the execution of the loop or switch structure. It
breaks the current flow of the program at the specified condition and program control
resumes at the next statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach
loop, and also with switch case.
Syntax
1. jump statement;
Kamadhenu BCA College -60-
2. break;
1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>
Output:
1
2
3
4
5
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>
11. Output:
12. 1 1
13. 1 2
14. 1 3
15. 2 1
16. 2 2
17. 3 1
18. 3 2
19. 3 3
Output:
One
Two
Three
You can see in the above output, after getting the specified condition true, break
statement immediately ends the loop and control is came out from the loop.
1. <?php
2. $car = 'Mercedes Benz';
3. switch ($car) {
4. default:
5. echo '$car is not Mercedes Benz<br>';
6. case 'Orange':
7. echo '$car is Mercedes Benz';
8. }
9. ?>
Output:
The continue statement is used within looping and switch control structure when you
immediately jump to the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and
foreach loop. The continue statement allows the user to skip the execution of the code for the
specified condition.
Syntax
The syntax for the continue statement is given below:
1. jump-statement;
2. continue;
In the following example, we will print only those values of i and j that are same and skip
others.
1. <?php
2. //outer loop
3. for ($i =1; $i<=3; $i++) {
4. //inner loop
5. for ($j=1; $j<=3; $j++) {
6. if (!($i == $j) ) {
7. continue; //skip when i and j does not have same values
8. }
9. echo $i.$j;
10. echo "</br>";
11. }
12. }
13. ?>
Output:
11
22
33
The following example prints the value of array elements except those for which the
specified condition is true and continue statement is used.
1. <?php
2. $number = array ("One", "Two", "Three", "Stop", "Four");
3. foreach ($number as $element) {
4. if ($element == "Stop") {
5. continue;
6. }
7. echo "$element </br>";
8. }
9. ?>
Output:
One
Two
Three
Four
Arrays in PHP are versatile and powerful data structures used to store multiple values under a
single variable name. PHP supports various types of arrays, including indexed arrays, associative
arrays, and multidimensional arrays. Here's an overview of each type:
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Output:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data. In
this example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
Kamadhenu BCA College -67-
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Program example :
Program to display elements of an indexed array:
<?php
$colors = array("Red", "Green", "Blue");
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = 0;
This table provides a clear comparison between indexed arrays and associative arrays in
PHP, outlining their differences in declaration, access, usage, and use cases.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Syntax
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.
The include and require statements are identical, except upon failure:
So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file
is accidentally missing.
Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header
needs to be updated, you can only update the header include file.
Syntax
include 'filename';
or
require 'filename';
<?php
echo "<p>Copyright © 1999-" . date("Y") . kamadhenuacademy.com</p>";
?>
<html>
<body>
</body>
</html>
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done
(we are using a <div> element so that the menu easily can be styled with CSS
later):
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP 7 Tutorial
Welcome to my home page!
Some text.
Example 3
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling
file:
Example
<html>
<body>
</body>
</html>
However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will
continue to execute:
Example
<html>
<body>
</body>
</html>
If we do the same example using the require statement, the echo statement will
not be executed because the script execution dies after the require statement
returned a fatal error:
Example
<html>
<body>
</body>
</html>
PHP Casting
Sometimes you need to change a variable from one data type into another,
and sometimes you want a variable to have a specific data type. This can be
done with casting.
In PHP, casting refers to converting a value from one data type to another. There are two
types of casting: implicit casting and explicit casting.
1. Implicit Casting:
• Implicit casting occurs automatically by PHP when a value is used in a
context that expects a different data type.
• PHP tries to convert the value to the expected data type without any
explicit instruction from the programmer.
• For example, when performing arithmetic operations or comparisons
involving different data types, PHP performs implicit casting to ensure
compatibility.
$x = 10; // integer
Kamadhenu BCA College -78-
$y = 5.5; // float
In the example above, (int) is used to explicitly cast the string value $x to an integer. Similarly,
(float), (string), (array), and (object) can be used for explicit casting to float, string, array,
and object types respectively.
Cast to String
To cast to string, use the (string) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$b = (string) $b;
$c = (string) $c;
$d = (string) $d;
$e = (string) $e;
//To verify the type of any object in PHP, use the var_dump() function:
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
output :
string(1) "5"
string(4) "5.34"
string(5) "hello"
string(1) "1"
string(0) ""
Note that when casting a Boolean into string it gets the value "1", and when casting NULL into string
it is converted into an empty string "".
Cast to Integer
To cast to integer, use the (int) statement:
$a = 5; // Integer
$b = 5.34; // Float
$e = "hello"; // String
$f = true; // Boolean
$a = (int) $a;
$b = (int) $b;
$c = (int) $c;
$d = (int) $d;
$e = (int) $e;
$f = (int) $f;
$g = (int) $g;
Output :
int(5)
int(5)
int(25)
int(0)
int(0)
int(1)
int(0)
Note that when casting a string that starts with a number, the (int) function uses that number. If it
does not start with a number, the (int) function convert strings into the number 0.
Cast to Float
To cast to float, use the (float) statement:
$a = 5; // Integer
$b = 5.34; // Float
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL
$a = (float) $a;
Kamadhenu BCA College -81-
$b = (float) $b;
$c = (float) $c;
$d = (float) $d;
$e = (float) $e;
$f = (float) $f;
$g = (float) $g;
Ouput :
float(5)
float(5.34)
float(25)
float(0)
float(0)
float(1)
float(0)
Note that when casting a string that starts with a number, the (float) function uses that number. If it
does not start with a number, the (float) function convert strings into the number 0.
Cast to Boolean
To cast to boolean, use the (bool) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = 0; // Integer
$d = -1; // Integer
$e = 0.1; // Float
$f = "hello"; // String
$g = ""; // String
$h = true; // Boolean
$i = NULL; // NULL
$a = (bool) $a;
$b = (bool) $b;
$d = (bool) $d;
$e = (bool) $e;
$f = (bool) $f;
$g = (bool) $g;
$h = (bool) $h;
$i = (bool) $i;
Output :
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
If a value is 0, NULL, false, or empty, the (bool) converts it into false, otherwise true. Even -1
converts to true.
Cast to Array
To cast to array, use the (array) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (array) $a;
$b = (array) $b;
$c = (array) $c;
$d = (array) $d;
$e = (array) $e;
array(1) {
[0]=>
int(5)
}
array(1) {
[0]=>
float(5.34)
}
array(1) {
[0]=>
int(0)
}
array(1) {
[0]=>
int(-1)
}
array(1) {
[0]=>
float(0.1)
}
array(1) {
[0]=>
string(5) "hello"
}
array(1) {
[0]=>
string(0) ""
}
array(1) {
[0]=>
bool(true)
}
array(0) {
}
When converting into arrays, most data types converts into an indexed array with one element.
Cast to NULL
To cast to NULL, use the (unset) statement:
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (unset) $a;
$b = (unset) $b;
$c = (unset) $c;
$d = (unset) $d;
$e = (unset) $e;
Ouput :
NULL
NULL
NULL
NULL
NULL