Notes For PHP
Notes For PHP
Class/Semester: BCA TY Vth Sem Name of Paper: Web Development and PHP Programming
UNIT I
Introduction to PHP
What is PHP?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code is executed on the server, and the result is returned to the browser as plain HTML
PHP files have extension ".php”
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash
movies. You can also output any text, such as XHTML and XML.
History of php
Rasmus Lerdorf started developing PHP in 1994. A lot of CGI programs were written by him which
were used for maintenance of his personal website. He modified these programs to make them work
with web forms and to interact with databases. The implementation of this modification was termed
as “Personal Home Page/Forms Interpreter” (PHP/FI). The first version of PHP/FI was made available
to the world by Lerdorf in June 1995 for Bug Reporting and Code Improvement. Features like Form
Handling, Variables similar to Perl and HTML embedding were present in this first version.
Release
Version Notes
date
8 June Officially called "Personal Home Page Tools (PHP Tools)". This is the first
1.0
1995 use of the name "PHP".
1 Officially called "PHP/FI 2.0". This is the first release that could actually be
2.0 November characterised as PHP, being a standalone language with many features that
1997 have endured to the present day.
6 June Development moves from one person to multiple developers. Zeev Suraski
3.0
1998 and Andi Gutmans rewrite the base for this version.
13 July
5.0 Zend Engine II with a new object model.
2004
Not
6.x Abandoned version of PHP that planned to include native Unicode support.
released
26
8.0 November Just-In-Time (JIT) compilation,
2020
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.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of
PHP according to your requirement without paying any cost. All its components are free to download
and use.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g.,
E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent
threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work in
a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.
X: Stands for Cross platform (Means you can install xampp on any Operating System)
A: Apache server (To run PHP script on local machine we need a server)
M: MySQL (To store data in database and to perform database operation we need MySQL)
P: PHP (Well known Object oriented Scripting language to create dynamic website- PHP
Interpreter is required to Compile and Run the PHP Script)
You don't have to install Apache, PHP and MySQL separately, in fact, it is often difficult for
beginners to install these bundles separately and combine them to run PHP CODE. XAMPP
does that for you with just a few clicks.
Apache is the most widely used Web Server software. Developed and maintained by
Apache Software Foundation, Apache is open source software available for free. It runs on
67% of all webservers in the world. It is fast, reliable, and secure
Web Server is the software that receives your request to access a web page. It runs a few
security checks on your HTTP request and takes you to the web page. Depending on the
page
you have requested, the page may ask the server to run a few extra modules while
generating the document to serve you. It then serves you the document you requested
MySQL:
MySQL runs on virtually all platforms, including Linux, UNIX, and Windows. Although it can
be used in a wide range of applications, MySQL is most often associated with web-based
applications and online publishing.
?>
3. Save the file in XAMPP Installation Directory \ Web Root Directory Note-
1: Default XAMPP Installation Directory in Windows is C:\xampp Note-2:
Default Web Root Directory in XAMPP is htdocs. All your php files will have to be in
this htdocs folder. That means, for a typical installation of XAMPP in Windows, you
will have to save the PHP CODE in C:\xampp\htdocs folder.
4. When you save the file, name it test.php (just as an example, any valid file name with
.php in the end will work).
Note: when you save this file, make sure it has no .txt extension at the end. Some
text editors place .txt at the end of file name, so it becomes test.php.txt instead of
test.php. To avoid this, when you save the file using any text editor, place double
quote around the file name: e.g. "test.php"
The PHP script is executed on the server, and the plain HTML result is sent back to
the browser.
A PHP script always starts with <?php and ends with ?>. A PHP script can be placed
anywhere in the document.
On servers with shorthand-support, you can start a PHP script with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php)
rather than the shorthand form.
<?php
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
<html>
<body>
<?php
Alternatively we can use the form below with server having shorthand-support
<html>
<body>
<?
print "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: print and echo.
In the example above we have used the print statement to output the text "Hello
World". We can use any Editor (ex: Notepad) to write the above statement or program
1.4 Understanding PHP, HTML, and White Space. Writing Comments in PHP
PHP:
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based software
applications.
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
output
Hello World!
Hello World!
Hello World!
HTML
What is HTML?
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
Prepared By Prof: M. G. Rajegave COCSIT, Latur.
8
</head>
<body>
</body>
</html>
output:
My First Heading
My first paragraph.
Example Explained
The <!DOCTYPE html> declaration defines that this document is an HTML5 document
The <html> element is the root element of an HTML page
The <head> element contains meta information about the HTML page
The <title> element specifies a title for the HTML page (which is shown in the browser's
title bar or in the page's tab)
The <body> element defines the document's body, and is a container for all the visible
contents, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
The <h1> element defines a large heading
The <p> element defines a paragraph
White Space
PHP is generally white space insensitive, meaning that you can add any number of
spaces in your code to make your scripts more readable. But those spaces will not be
displayed in the output page.
HTML is also generally white space insensitive. Specifically, the only white space in HTML
that affects the rendered page is a single space (multiple spaces still get rendered as
one).
Multiple spaces added in the HTML document will be ignored and only single space will
be added.
Example:
<?php
<?php
$lions =
21;
$zebras
= 20;
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to
be read by someone who is looking at the code.
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
To create dynamic Web sites with PHP, you must know how to send data to the
Web browser. PHP has a number of built-in functions for this purpose, the most
common being echo () and print ().
echo and print are more or less the same. They are both used to output data to the
screen.
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command (notice that the text
can contain HTML markup):
<?php
echo "<h2>PHP is Fun!</h2>"; Output:
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
PHP is
?> Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display Variables
The following example shows how to output text and variables with the echo statement:
<?php
$txt2 = "COCSIT";
$x = 5;
$y = 4;
echo $x + $y;
?>
Output:
<?php
?>
Output:
PHP is Fun!
Hello world!
I'm about to learn PHP!
Display Variables
The following example shows how to output text and variables with the print statement:
<?php
$txt2 = "COCSIT";
$x = 5;
$y = 4;
print $x + $y;
?>
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:
It holds only single value. There are 4 scalar data types in PHP.
boolean
integer
float
string
2. PHP Data Types: Compound Types
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,
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.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
Decimal number: 34
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. $company = "Microsoft";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
Prepared By Prof: M. G. Rajegave COCSIT, Latur.
16
6. echo 'Hello $company';
7. ?>
Output:
HelloMicrosoft
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:
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:
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() {
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. ?>
Keywords in PHP
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:
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
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:
Example
<?php
$txt = "W3Schools.com";
?>
The following example will produce the same output as the example above:
Example
<?php
?>
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changedduring the script.
A valid constant name starts with a letter or underscore (no $ sign before theconstant name).
Note: Unlike variables, constants are automatically global across the entirescript.
Syntax
Parameters:
Example
define("msg","All the bcaty student here inform that<br> our php 1st unit
will be complete coming soon...");
echo msg;
?>
output:
All the bcaty student here inform that our 1st unit
will complete coming soon...
Example
<?php
?>
Output:
Welcome to COCSIT!
Constants are automatically global and can be used across the entire script.Example:
This example uses a constant inside a function, even if it is defined outside thefunction:
myTest() {
echo GREETING;
myTest();
?>
Welcome to PHP!
An expression is a bit of PHP that can be evaluated to produce a value. The simplest
expressions are literal values and variables. A literal value evaluates to itself, while a
variable evaluates to the value stored in the variable. More complex expressions can be
formed using simple expressions and operators
Most operators in PHP are binary operators; they combine two operands (or
expressions) into a single, more complex expression. PHP also supports a number of unary
operators, which convert a single expression into a more complex expression. Finally,
PHP supports a single ternary operator that combines three expressions into a single
expression
Syntax
$x=100; //100 is an expression
These operators are called increment and decrement operators respectively. They are unary
operators, needing just one operand and can be used in prefix or postfix manner, although
with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator
decrements by 1). However, when used in assignment expression, prefix
makesincremnt/decrement first and then followed by assignment. In case of postfix,
assignment is done before increment/decrement
$x=10;
?>
Output
This produces following result
x = 11 y = 10
Expression with Ternary conditional operator
Ternary operator has three operands. First one is a logical expression. If it is TRU, second
operand expression is evaluated otherwise third one is evaluated
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Output
Following result will be displayed
Pass
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
x=y x=y The left operand gets set to the value of the expression on
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x% Modulus
y
=== Identical $x === Returns true if $x is equal to $y, and they are of the
$y same type
!== Not identical $x !== Returns true if $x is not equal to $y, or they are not of
$y the same type
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than
$y zero, depending on if $x is less than, equal to, or
greater than $y. Introduced in PHP 7.
The PHP comparison operators are used to compare two values (number or string):
PHP has two operators that are specially designed for strings.
The PHP conditional assignment operators are used to set a value depending on conditions:
Unit - II
Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
if...else statement - executes some code if a condition is true and another code
if that condition is false
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
<?php
$t = date("H");
Switch statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a
variable), that is evaluated once. The value of the expression is then compared
with the values for each case in the structure. If there is a match, the block of
code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no
match is found.
Example
<?php
$favcolor = "red";
The ? Operator:
There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation. The conditional
operator has this syntax −
<html>
<head>
<title> The ? Operator:
</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
</body>
</html>
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
Syntax
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Explaination
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
2) The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do
{
code to be executed;
Increment / Decrement
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Out put:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values
by referring to an index number.
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements
to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
PHP supports multidimensional arrays that are two, three, four, five, or more levels
deep. However, arrays more than three levels deep are hard to manage for most
people.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices:
row and column.
To get access to the elements of the $cars array we must point to the two indices
(row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
We can also put a for loop inside another for loop to get the elements of the $cars
array (we still have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Output:
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
Saab
5
2
Row number 3
Land Rover
17
15
The include() and require() statement allow you to include the code contained in a
PHP file within another PHP file. Including a file produces the same result as copying
the script from the file specified and pasted into the location where it is called.
You can save a lot of time and work through including files — Just store a block of
code in a separate file and include it wherever you want using the include() and
require() statements instead of typing the entire block of code multiple times. A
typical example is including the header, footer and menu file within all the pages of a
website.
The basic syntax of the include() and require() statement can be given with:
The only difference is — the include() statement will only generate a PHP warning but
allow script execution to continue if the file to be included can't be found, whereas
the require() statement will generate a fatal error and stops the script execution.
Example
<?php require "my_variables.php"; ?>
<?php require "my_functions.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php displayTitle($home_page); ?></title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful resources.</p>
<?php include "footer.php"; ?>
</body>
</html>
The meaning of "Casting" is taking a variable of one particular data type and
converting it to another data type. (ex: Integer to Float)
The meaning of type casting is to use the value of a variable with different
data type. In other word typecasting is a way to utilize one data type variable
into the different data type. Typecasting is the explicit conversion of data type
because user explicitly defines the data type in which he wants to cast.
Implicit Casting
Implicit casting is something done by PHP according to your code, but you are not
capable of customizing. When dividing an integer by another integer the result can
either be integer or float. The decision is taken by PHP. See the below example.
<?php
39 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
$x = 2;
$y = 4;
Explicit Casting
We can explicitly cast a variable to different data types. For instance, we can convert
a float to an integer like following. (The decimal portion will be dropped)
<?php
$x = 5.35;
var_dump($y);
The data type you need to change the variable into should be written inside
parentheses, before the variable.
Cast Description
1. Casting to an integer
When casting a float to integer, the decimal portion will be dropped. So, make sure
that this drop does not affect any other things.
<?php
$x = 5.35;
var_dump($y);
?>
We can also cast strings to integers. This can be useful when collecting numeric data
from forms. (More details in the PHP forms chapter)
<?php
$x = '25';
var_dump($y);
?>
41 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
The following example shows a useful way that you can use casting for. Casting any
string that starts with a number followed by a phrase to an integer will return the
starting number as an integer
<?php
echo $numberOfAnimals;
?>
Output:
10
2. Casting to a float
(float), (double) and (real) are valid casts. All of them casts the variable to float data
type.
When casting an integer to float there won't be any data loss, as integers do not have
any decimal portion.
<?php
$x = 7;
var_dump($y);
?>
float(7)
3. Casting to a boolean
<?php
$a = (bool) 0;
$b = (bool) 5;
$c = (bool) '';
$d = (bool) 'Hyvor';
$e = (bool) [];
$f = (bool) [2,5];
$g = (bool) null;
var_dump($a); // false
var_dump($b); // true
var_dump($c); // false
var_dump($d); // true
var_dump($e); // false
var_dump($f); // true
var_dump($g); // false
var_dump($h); // true
var_dump($h); // true
?>
Output:
4. Casting to an array
We can add any single variable into an array which has only one element.
<?php
$a = (array) 5;
$b = (array) 'Hyvor';
$c = (array) true;
var_dump($a); // [5]
var_dump($b); // ['Hyvor']
var_dump($c); // [true]
?>
Output:
array(1) { [0]=> int(5) } array(1) { [0]=> string(5) "Hyvor" } array(1) { [0]=> bool(true) }
Syntax
function functionName() {
code to be executed;
Note: A function name must start with a letter or an underscore. Function names are
NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code, and the closing curly brace (
} ) indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name followed by brackets ():
Example
<?php
//function definition
function writeMsg() {
?>
Example
$z = $x + $y;
return $z;
?>
PHP 7 also supports Type Declarations for the return statement. Like with the type
declaration for function arguments, by enabling the strict requirement, it will throw a
"Fatal Error" on a type mismatch.
To declare a type for the function return, add a colon ( : ) and the type right before
the opening curly ( { )bracket when declaring the function.
In the following example we specify the return type for the function:
return $a + $b;
?>
You can specify a different return type, than the argument types, but make sure the
return is the correct type:
Example
?>
In PHP, arguments are usually passed by value, which means that a copy of the value
is used in the function and the variable that was passed into the function cannot be
changed.
Example
function add_five(&$value) {
$value += 5;
$num = 2;
add_five($num);
echo $num;
?>
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
Get a Date
The required format parameter of the date() function specifies how to format the date
(or time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to
add additional formatting.
Example
<?php
?>
Output:
Today is 2020/11/03
Today is 2020.11.03
Today is Tuesday
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
Example
<?php
?>
Output:
PHP Strings
Example
<?php
?>
Example
<?php
?>
Output:
Example
?>
Output:
!dlrow olleH
The PHP strpos() function searches for a specific text within a string. If a match is
found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
Example
<?php
?>
Output:
The PHP str_replace() function replaces some characters with some other characters
in a string.
Example
<?php
?>
Output:
Hello Dolly!
3.4 Objects in PHP: What is Class & Object, Creating and accessing a Class &
Object,
PHP being an object oriented programming language, allows creation of classes and
objects to follow the object oriented programming paradigm while developing any
software or application.
A class is a user-defined data type which includes local variables and local
methods.
While an object is an instance of the class which holds the local variables with
values assigned and on which we can call the local methods defined in the class.
we will learn how to define a class in PHP and how to create its objects.
When we define a class in PHP, just like any variable we have to give our class a
name, and there are some rules that we must follow while naming our class in PHP,
they are:
The syntax for defining a class in PHP is very simple, we use the keyword class
followed by the name of the class and then we enclose the code for the class within
curly braces { } just like for a function/method.
<?php
class Person {
?>
Although it is not mandatory, but it is good practice to use the class name as the
filename for the PHP file. Also, PHP allows for multiple classes to be defined in a
single file, but again it is not recommended.
Complete example
<?php
class Books {
/* Member variables */
var $price;
var $title;
function setPrice($par){
$this->price = $par;
function getPrice(){
function setTitle($par){
$this->title = $par;
function getTitle(){
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Once you defined your class, then you can create as many objects as you like of that
class type. Following is an example of how to create object using new operator.
Here we have created three objects and these objects are independent of each other
and they will have their existence separately. Next we will see how to access member
function and process member variables.
After creating your objects, you will be able to call member functions related to that
object. One member function will be able to process member variable of related
object only.
Following example shows how to set title and prices for the three books by calling
member functions.
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Advanced Chemistry
Algebra
10
15
In order to create a class, we group the code that handles a certain topic into one
place. For example, we can group all of the code that handles the users of a blog into
one class, all of the code that is involved with the publication of the posts in the blog
into a second class, and all the code that is devoted to comments into a third class.
To name the class, it is customary to use a singular noun that starts with a capital
letter. For example, we can group a code that handles users into a User class, the
code that handles posts into a Post class, and the code that is devoted to comments
into a Comment class.
For the example given below, we are going to create a Car class into which we will
group all of the code which has something to do with cars.
class Car {
// The code
We call properties to the variables inside a class. Properties can accept values like
strings, integers, and booleans (true/false values), like any other variable. Let's add
some properties to the Car class.
class Car {
public $comp;
If the name contains more than one word, all of the words, except for the first word,
start with an upper case letter. For example, $color or $hasSunRoof.
A property can have a default value. For example, $color = 'beige'.
We can also create a property without a default value. See the property $comp in
the above example.
In order to work with a class, we need to create an object from it. In order to create
an object, we use the new keyword. For example:
In fact, we can create as many objects as we like from the same class, and then give
each object its own set of properties.
echo $bmw -> color; than (->), and then the property name.
echo $mercedes -> color;
For example, in order to set the color to 'blue' in the bmw object:
and in order to set the value of the $comp property for both objects:
In order to get the color of the $bmw object, we use the following line of code:
Result:
Blue
We can also get the company name and the color of the second car object.
Result:
beige
Mercedes Benz
The classes most often contain functions. A function inside a class is called a method.
Here we add the method hello() to the class with the prefix public.
class Car {
public $comp;
public $color = 'beige';
public $hasSunRoof = true;
public function hello()
{
return "beep";
}
}
Result:beep
beep
Complete Example:
<?php
class Car {
// properties
public $comp;
// Create an instance
?>
Function Overloading:
Function overloading contains same function name and that function preforms
different task according to number of arguments.
For example, find the area of certain shapes where radius are given then it should
return area of circle if height and width are given then it should give area of rectangle
and others. Like other OOP languages function overloading can not be done by native
approach. In PHP function overloading is done with the help of magic function
__call(). This function takes function name and arguments.
<?php
// overloading in PHP
class shape
if($name_of_function == 'area')
switch (count($arguments))
// area of circle
case 1:
case 2:
return $arguments[0]*$arguments[1];
$s = new Shape;
// Functio call
echo($s->area(2));
echo "";
?>
Output:
6.28
Function Overriding:
// function overriding
class P {
function geeks()
echo "Parent";
class C extends P
function geeks()
echo "Child";
$p = new P;
$c= new C;
// print Parent
$p->geeks();
// Print child
$c->geeks();
?>
Output:
Parent
Child
The child class will inherit all the public and protected properties and methods from
the parent class. In addition, it can have its own properties and methods.
<?php
69 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
class Fruit {
public $name;
public $color;
$this->name = $name;
$this->color = $color;
$strawberry->message();
$strawberry->intro();
?>
Output:
PHP Constructor
If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.
Notice that the construct function starts with two underscores (__)!
We see in the example below, that using a constructor saves us from calling the
set_name() method which reduces the amount of code:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
function get_name() {
return $this->name;
echo $apple->get_name();
?>
Output:
Apple
PHP Destructor
If you create a __destruct() function, PHP will automatically call this function at the
end of the script.
Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called when
you create an object from a class, and a __destruct() function that is automatically
called at the end of the script:
Example
<?php
class Fruit {
public $name;
public $color;
$this->name = $name;
function __destruct() {
?>
Output:
An HTML form is used to collect user input. The user input is most often sent to a server for
processing.
Example:
<form>
form elements
</form>
The <form> element is a container for different types of input elements, such as:
text fields, checkboxes, radio buttons, submit buttons, etc.
An <input> element can be displayed in many ways, depending on the type attribute.
Type Description
<input type="radio"> Displays a radio button (for selecting one of many choices)
The action attribute defines the action to be performed when the form is submitted.
74 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
Usually, the form data is sent to a file on the server when the user clicks on the
submit button.
In the example below, the form data is sent to a file called "action_page.php". This
file contains a server-side script that handles the form data
<form action="/action_page.php">
</form>
Tip: If the action attribute is omitted, the action is set to the current page.
Value Description
The default value is _self which means that the response will open in the current
window.
The method attribute specifies the HTTP method to be used when submitting the
form data.
The form-data can be sent as URL variables (with method="get") or as HTTP post
transaction (with method="post").
Example
This example uses the GET method when submitting the form data:
Notes on GET:
Notes on POST:
1. Appends the form data inside the body of the HTTP request (the submitted form
data is not shown in the URL)
2. POST has no size limitations, and can be used to send large amounts of data.
3. Form submissions with POST cannot be bookmarked
Open up your favorite code editor and create a new PHP file. Now type the following
code and save this file as "contact-form.php" in the root directory of your project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<label for="inputName">Name:<sup>*</sup></label>
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
</p>
<p>
<label for="inputSubject">Subject:</label>
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
</p>
</form>
</body>
</html>
Explanation of code
The action attribute references a PHP file "process-form.php" that receives the data
entered into the form when user submit it by pressing the submit button.
The method attribute tells the browser to send the form data through POST method.
To access the value of a particular form field, you can use the following superglobal
variables. These variables are available in all scopes throughout a script.
When a user submit the above contact form through clicking the submit button, the
form data is sent to the "process-form.php" file on the server for processing. It
simply captures the information submitted by the user and displays it to browser.
The PHP code of "process-form.php" file will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Thank You</h1>
<ol>
</ol>
</body>
</html>
The PHP code above is quite simple. Since the form data is sent through the post
method, you can retrieve the value of a particular form field by passing its name to
the $_POST superglobal array, and displays each field value using echo() statement.
Unit - IV
Other kinds of data stores can also be used, such as files on the file system or large
hash tables in memory but data fetching and writing would not be so fast and easy
with those type of systems.
What is MySQL:
SET(val1, val2, val3, ...) A string object that can have 0 or more values,
chosen from a list of possible values. You can list
up to 64 values in a SET list
Before you start building PHP connection to MySQL database you need to know what
PHPMyAdmin is. It’s a control panel from where you can manage the database that
you’ve created. Open your browser and go to localhost/PHPMyAdmin or click
“Admin” in XAMPP UI.
Create Database
Now return to the homepage of PHPMyAdmin. Click the New button to create a new
database.
The newly created database will be empty now, as there are no tables in it.
MySQL Commands:
86 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
To run the mysql from command prompt set path from Advanced Settings
C:\Users\Madha>cd\
C:\>cd C:\xampp\mysql\bin
Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.
2. Create a database
Create Table
7.Rename a table
Syntax :
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname=”my_DB”;
// Create connection
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output:
Connected successfully
You will need special CREATE privileges to create or to delete a MySQL database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
// Check connection
if (!$conn) {
// Create database
if (mysqli_query($conn, $sql)) {
} else {
mysqli_close($conn);
?>
Output:
Example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
if (mysqli_query($conn, $sql))
{
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After a database and a table have been created, we can start adding data in them.
The INSERT INTO statement is used to add new records to a MySQL table:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
// Check connection
if (!$conn) {
} else {
mysqli_close($conn);
?>
<html>
<body>
<?php
$username = "root";
$password = "";
$database = "mydb";
<tr>
</tr>';
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result)>0)
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["class"];
$field4name = $row["address"];
echo '<tr>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
</tr>';
mysqli_close($conn);
?>
</body>
</html>
Syntax
mysqli_num_rows(result);
Example
Return the number of rows in a result set:
<html>
<body>
<?php
$username = "root";
$password = "";
$database = "mydb";
$conn = mysqli_connect("localhost", $username, $password, $database);
$query = "SELECT * FROM tblinfo";
if ($result=mysqli_query($conn,$query))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
Output:
Result set has 7 rows.
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
<html>
<body>
<?php
$username = "root";
$password = "";
$database = "mydb";
$conn = mysqli_connect("localhost", $username, $password, $database);
$sql = "UPDATE tblinfo SET name='Vaibhav Patil' WHERE id=4";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
Output:
Record updated successfully