0% found this document useful (0 votes)
2K views113 pages

Notes For PHP

This document provides an introduction to PHP, including: - PHP is an open-source scripting language used to build dynamic web applications. It allows developers to add database connectivity, user authentication, and other functionality to websites. - Some key features of PHP include being free, running efficiently on servers, supporting multiple platforms and databases, and having an easy to learn syntax. - The document outlines the history of PHP from its creation in 1994 to present versions. It also lists many characteristics of PHP like performance, open source nature, error handling, and compatibility with web servers. - Instructions are provided for installing XAMPP, a package that allows running PHP locally for development, along with a simple

Uploaded by

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

Notes For PHP

This document provides an introduction to PHP, including: - PHP is an open-source scripting language used to build dynamic web applications. It allows developers to add database connectivity, user authentication, and other functionality to websites. - Some key features of PHP include being free, running efficiently on servers, supporting multiple platforms and databases, and having an easy to learn syntax. - The document outlines the history of PHP from its creation in 1994 to present versions. It also lists many characteristics of PHP like performance, open source nature, error handling, and compatibility with web servers. - Instructions are provided for installing XAMPP, a package that allows running PHP locally for development, along with a simple

Uploaded by

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

Royal Education Society’s

College of Computer Science and Information Technology, Latur

Department of Computer Science


Academic Year (2021-22)
Choice Based Credit System (CBCS Pattern)

Class/Semester: BCA TY Vth Sem Name of Paper: Web Development and PHP Programming

UNIT I
Introduction to PHP

Introduction to PHP, History and Features of PHP

What is PHP?

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

1. What is a PHP File?

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”

2. What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

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.

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


1
3. Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

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.

22 May Added more advanced two-stage parse/execute tag-parsing system called


4.0
2000 the Zend engine.

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

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


2
3 Zend Engine 3 (performance improvements and 64-bit integer support on
7.0 December Windows, uniform variable syntax, AST-based compilation
2015 process, added Closure::call() ,

26
8.0 November Just-In-Time (JIT) compilation,
2020

Feature Of PHP Or Characteristics Of PHP

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.

Familiarity with syntax:


PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:
PHP code can be easily embedded within HTML tags and script.

Platform Independent:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


3
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed
in one OS can be easily executed in other OS also.

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.

Loosely Typed Language:


PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.

Web servers Support:


PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
XAMPP etc.

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.

A Helpful PHP Community:


It has a large community of developers who regularly updates documentation.

Installation & Configuration of PHP

To install PHP, we will suggest you to given below:

o WAMP for Windows


o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other components
too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


4
To begin Programming in PHP for web development, first we require software
bundle named XAMPP. There are other similar software bundles that can run PHP,
but XAMPP works well in all the major platforms: Windows, Mac and Linux.

Where XAMPP stands for:

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)

P: Perl programming language.

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 is an open source relational database management system (RDBMS) based on


Structured Query Language (SQL).

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.

After you install XAMPP,

1. Open any Text Editor.

2. Write the following PHP Program / CODE in the Text Editor:


Prepared By Prof: M. G. Rajegave COCSIT, Latur.
5
<?PHP

echo 'Hello From PHP! <br />';

?>
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"

5. Then, go to XAMPP installation folder (typically, C:\xampp) and run xampp-


control.exe by double clicking it.
6. In the xampp-control window, click the start button beside Apache. Later, if you
need other options like MySQL, you'll also have to start MySQL by clicking the start
button beside MySQL in the XAMPP control Panel. Note: if
your OS hides common file extensions, then you'll see xampp-control, instead of
xampp- control.exe
7. Now, in your web browser's address bar, type the address:

1.3 Embedding PHP code in Your Web Pages

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 must have a .php extension.

A PHP file normally contains HTML tags, and some PHP scripting code.

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


6
Below, we have an example of a simple PHP script that sends the text "Hello World" back to the
browser:

<html>
<body>
<?php

print "Hello World";


?>
</body>
</html>

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.

 PHP is a acronym for "PHP: Hypertext Preprocessor".


 PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
Prepared By Prof: M. G. Rajegave COCSIT, Latur.
7
PHP Case Sensitivity

 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?

 HTML stands for Hyper Text Markup Language


 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a
link", etc.
Example

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
Prepared By Prof: M. G. Rajegave COCSIT, Latur.
8
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</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

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


9
echo "Here is how to calculate in PHP";?></br>

<?php

$lions =

21;

$zebras

= 20;

$animals = $lions + $zebras;

echo "The number of animals is ",

$animals,", there are 21 lions and 20 zebras";?>

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.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back to their
own work a year or two later and having to re-figure out what they did. Comments can remind
you of what you were thinking when you wrote the code

PHP supports several ways of commenting:

Example

Syntax for single-line comments:

<!DOCTYPE html>

<html>
<body>
<?php
// This is a single-line comment

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


10
# This is also a single-line comment
?>
</body>
</html>

Syntax for multiple-line comments:

<html>
<body>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

Using comments to leave out parts of the code:

<html>
<body>

<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>

SENDING DATA TO THE WEB BROWSER

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.

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


11
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is marginally
faster than print.
The PHP echo Statement

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

$txt1 = "Learn PHP";

$txt2 = "COCSIT";

$x = 5;

$y = 4;

echo "<h2>" . $txt1 . "</h2>";

echo "Study PHP at " . $txt2 . "<br>";

echo $x + $y;

?>

Output:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


12
Learn PHP
Study PHP at COCSIT
9

The PHP print Statement


The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice that the text
can contain HTML markup):

<?php

print "<h2>PHP is Fun!</h2>";

print "Hello world!<br>";

print "I'm about to learn 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

$txt1 = "Learn PHP";

$txt2 = "COCSIT";

$x = 5;

$y = 4;

print "<h2>" . $txt1 . "</h2>";

print "Study PHP at " . $txt2 . "<br>";

print $x + $y;

?>

Output:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


13
Learn PHP
Study PHP at COCSIT
9

PHP Data Types

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:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

1. PHP Data Types: Scalar 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

3. PHP Data Types: Special Types

There are 2 special data types in PHP

1. resource
2.NULL

1.PHP Data Types: Scalar Types

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,

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


14
it returns TRUE otherwise FALSE.

Example:

1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:

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.

Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31
to 2^31.

Example:

1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


15
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:

Decimal number: 34

Octal number: 163

HexaDecimal number: 69
PHP Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.

Example:

1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:

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:

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:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=>


string(3) "KTM" }

Array Element1: Royal Enfield


Array Element2: Yamaha
You will learn more about array in later chapters of this tutorial.
Array Element3: KTM
PHP object

Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.

Example:

1. <?php
2. class bike {
3. function model() {

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


17
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:

Bike Model: Royal Enfield


This is an advanced topic of PHP, which we will discuss later in detail.

PHP Resource

Resources are not the exact data type in PHP. Basically, these are used to store some
function calls or references to external PHP resources. For example - a database call. It
is an external resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

PHP Null

Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>

Output: //it will not give any output

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:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


18
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

case Used in the switch conditional

catch Used in the try..catch statement

class Declare a class

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

endif End an if or elseif block

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

include_once Embed code from another file

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


19
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

1.7 Using Variables, Constants in PHP

Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

<?php

$txt = "Hello world!";

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

Think of variables as containers for storing data.

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


20
PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for PHP variables:

A variable starts with the $ sign, followed by the name of the variable

A variable name must start with a letter or the underscore character

A variable name cannot start with a number

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)

Remember that PHP variable names are case-sensitive!

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";

echo "I love $txt!";

?>

The following example will produce the same output as the example above:

Example

<?php

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


21
$txt = "W3Schools.com";

echo "I love " . $txt . "!";

?>

The following example will output the sum of two variables:

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.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


22
 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false

Example

Create a constant with a case-sensitive name:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


23
<?php

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

Create a constant with a case-insensitive name:

<?php

define("GREETING", "Welcome to COCSIT!", true);


echo greeting;

?>

Output:

Welcome to COCSIT!

Constants are Global

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:

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


24
<?php

define("GREETING", "Welcome to PHP!");function

myTest() {

echo GREETING;

myTest();

?>

Prepared By Prof: M. G. Rajegave COCSIT, Latur.


25
Output:

Welcome to PHP!

1.8 Expressions in 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

$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

Expression with ++ and -- operators

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

Uses postfix ++ operator

15 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<?php

$x=10;

$y=$x++; //equivalent to $y=$x followed by $x=$x+1

echo "x = $x y = $y";

?>

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

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Increment/Decrement operators

 Logical operators

 String operators

 Array operators

16 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


 Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th


power

PHP Assignment Operators

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.

Assignment Same Description


as...

x=y x=y The left operand gets set to the value of the expression on

17 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


the right

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

18 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === Returns true if $x is equal to $y, and they are of the
$y same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== Returns true if $x is not equal to $y, or they are not of
$y the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than $x >= $y Returns true if $x is greater than or equal to $y


or equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

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

19 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but


not both

20 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and


$txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === Returns true if $x and $y have the same


$y key/value pairs in the same order and of

21 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non- $x !== Returns true if $x is not identical to $y


identity $y

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x
is expr2 if expr1 = TRUE.
The value of $x
is expr3 if expr1 = FALSE

?? Null $x = expr1 ?? expr2 Returns the value of $x.


coalescing The value of $x
is expr1 if expr1 exists, and is
not NULL.
If expr1 does not exist, or is
NULL, the value of $x is expr2.
Introduced in PHP 7

Unit - II

22 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


2. Programming with PHP

2.1 Conditional statements: if, if-else, switch, The ? Operator

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.

In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true

 if...else statement - executes some code if a condition is true and another code
if that condition is false

 if...elseif...else statement - executes different codes for more than two


conditions

 switch statement - selects one of many blocks of code to be executed

1)PHP - The if Statement


The if statement executes some code if one condition is true.

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

if ($t < "20") {


echo "Have a good day!";
}
?>
Have a good day

23 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


PHP - The if...else Statement
The 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;
} else {
code to be executed if condition is false;
}
Example
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

Have a good day!


PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two
conditions.

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

if ($t < "10") {


24 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The hour (of the server) is 10, and will give the following message:
Have a good day!

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";

25 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

Your favorite color is 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;

/* If condition is true then assign a to result otheriwse b */


$result = ($a > $b ) ? $a :$b;

26 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


echo "TEST1 : Value of result is $result<br/>";

/* If condition is true then assign a to result otheriwse b */


$result = ($a < $b ) ? $a :$b;

echo "TEST2 : Value of result is $result<br/>";


?>

</body>
</html>

This will produce the following result −

TEST1 : Value of result is 20


TEST2 : Value of result is 10

2.2 Looping statements: while Loop, do...while Loop, for Loop

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.

In PHP, we have the following loop types:

1. while - loops through a block of code as long as the specified condition is


true
2. do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
3. for - loops through a block of code a specified number of times
4. foreach - loops through a block of code for each element in an array
1) The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.

Syntax

27 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


while (condition is true)
{
code to be executed;
Increment / Decrement
}
Examples
The example below displays the numbers from 1 to 5:

<?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

28 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will
write some output, and then increment the variable $x with 1. Then the condition is
checked (is $x less than, or equal to 5?), and the loop will continue to run as long as
$x is less than, or equal to 5:

Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5
3) The PHP for Loop
The for loop is used when you know in advance how many times the script should
run.

Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:

init counter: Initialize the loop counter value


test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value

29 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Examples
The example below displays the numbers from 0 to 10:

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

4) The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value
pair in an array.

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):

30 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
Output:
red
green
blue
yellow

2.3 Arrays in PHP: Introduction- What is Array?

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?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values
by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:

31 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


array();
In PHP, there are three types of arrays:
The count() function is used to return the length (the number of elements) of an array:

2.4 Types of Arrays: Indexed Vs. Associative arrays, Multidimensional arrays

I. Indexed arrays - Arrays with a numeric index


II. Associative arrays - Arrays with named keys
III. Multidimensional arrays - Arrays containing one or more arrays

I.PHP Indexed Arrays


There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");


or the index can be assigned manually:

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

I like Volvo, BMW and Toyota.

Loop Through an Indexed Array

32 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


To loop through and print all the values of an indexed array, you could use a for loop,
like this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
BMW
Toyota.

II) PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

33 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


?>
Output:
Peter is 35 years old.

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use a
foreach loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

III) PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

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.

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an array
of arrays of arrays).

First, take a look at the following table:

34 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Name Stock Sold

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>";

35 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

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

36 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Row number 2

 Saab
 5
 2

Row number 3

 Land Rover
 17
 15

2.6 Using Array Functions

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

2.7 Including and Requiring Files- use of Include() and Require()

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:

include("path/to/filename"); -Or- include "path/to/filename";


require("path/to/filename"); -Or- require "path/to/filename";

37 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Difference Between include and require Statements
You might be thinking if we can include files using the include() statement then why
we need require(). Typically the require() statement operates like include().

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>

38 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


2.8 Implicit and Explicit Casting in PHP

The meaning of "Casting" is taking a variable of one particular data type and
converting it to another data type. (ex: Integer to Float)

There are two types of casting

 Implicit Casting (Automatic)


 Explicit Casting (Manual)

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 Implicit Casting Example

<?php
39 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
$x = 2;

$y = 4;

var_dump($x / $y); // 2/4 = 0.5 (Float)

var_dump($y / $x); // 4/2 = 2 (Int)

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 Explicit Casting - Float to Integer

<?php

$x = 5.35;

$y = (int) $x; // cast $x to integer

var_dump($y);

The data type you need to change the variable into should be written inside
parentheses, before the variable.

The following casts are allowed:

Cast Description

(int) or (integer) Cast to an integer.

(float) or (double) or (real) Cast to a float.

(bool) or (boolean) Cast to a boolean.


40 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
(string) Cast to a string.

(array) Cast to an array.

(object) Cast to an object.

Explicit Casting Examples

1. Casting to an integer

Both (int) and (integer) casts are valid.

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 Explicit Casting - Float to Integer

<?php

$x = 5.35;

$y = (int) $x; // cast $x to integer

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 Explicit Casting - String to Integer

<?php

$x = '25';

$y = (integer) $x; // cast $x to int

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 Explicit Casting - Phrase to Integer

<?php

$string = '10 Animals';

$numberOfAnimals = (int) $string;

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 Explicit Casting - Integer to Float

<?php

$x = 7;

$y = (float) $x; // $y is 7, but float

var_dump($y);

?>

42 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Output:

float(7)

3. Casting to a boolean

Both bool and boolean are valid.

PHP Explicit Casting to 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

$h = (boolean) 'Hyvor'; // boolean also valid

var_dump($h); // true

43 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$h = (boolean) 'Hyvor'; // boolean also valid

var_dump($h); // true

?>

Output:

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

4. Casting to an array

We can add any single variable into an array which has only one element.

PHP Explicit Casting to Array

<?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) }

44 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Unit - III

3. Using Functions , Class- Objects, Forms in PHP

3.1 Functions in PHP: Defining and calling a function, Returning Value


from
 A function is a block of statements that can be used repeatedly in a program.

45 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:

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

echo "Hello world!";

writeMsg(); // call the function

?>

46 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Hello world!

PHP Functions - Returning values

To let a function return a value, use the return statement:

Example

<?php declare(strict_types=1); // strict requirement

function sum(int $x, int $y) {

$z = $x + $y;

return $z;

echo "5 + 10 = " . sum(5, 10) . "<br>";

echo "7 + 13 = " . sum(7, 13) . "<br>";

echo "2 + 4 = " . sum(2, 4);

?>

PHP Return Type Declarations

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:

47 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : float {

return $a + $b;

echo addNumbers(1.2, 5.2);

?>

You can specify a different return type, than the argument types, but make sure the
return is the correct type:

Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : int {

return (int)($a + $b);

echo addNumbers(1.2, 5.2);

?>

Passing Arguments by Reference

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.

When a function argument is passed by reference, changes to the argument also


change the variable that was passed in. To turn a function argument into a reference,
the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

48 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<?php

function add_five(&$value) {

$value += 5;

$num = 2;

add_five($num);

echo $num;

?>

3.2 Date and Time in PHP: Date and Time Functions

The PHP date() function is used to format a date and/or a time.

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

Syntax

date(format,timestamp)

Parameter Description

format Required. Specifies the format of the


timestamp

timestamp Optional. Specifies a timestamp. Default is


the current date and time

49 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


A timestamp is a sequence of characters, denoting the date and/or time at which a
certain event occurred.

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:

d - Represents the day of the month (01 to 31)

m - Represents a month (01 to 12)

Y - Represents a year (in four digits)

l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to
add additional formatting.

The example below formats today's date in three different ways:

Example

<?php

echo "Today is " . date("Y/m/d") . "<br>";

echo "Today is " . date("Y.m.d") . "<br>";

echo "Today is " . date("Y-m-d") . "<br>";

echo "Today is " . date("l");

?>

Output:

Today is 2020/11/03

Today is 2020.11.03

50 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Today is 2020-11-03

Today is Tuesday

Get a Time

Here are some characters that are commonly used for times:

H - 24-hour format of an hour (00 to 23)

h - 12-hour format of an hour with leading zeros (01 to 12)

i - Minutes with leading zeros (00 to 59)

s - Seconds with leading zeros (00 to 59)

a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

Example

<?php

echo "The time is " . date("h:i:sa");

?>

Output:

The time is 09:38:27am

PHP Strings

A string is a sequence of characters, like "Hello world!".

51 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


PHP String Functions

some commonly used functions to manipulate strings.

1.strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.

Example

Return the length of the string "Hello world!":

<?php

echo strlen("Hello world!"); // outputs 12

?>

2. str_word_count() - Count Words in a String

The PHP str_word_count() function counts the number of words in a string.

Example

Count the number of word in the string "Hello world!":

<?php

echo str_word_count("Hello world!"); // outputs 2

?>

Output:

3. strrev() - Reverse a String

The PHP strrev() function reverses a string.

Example

Reverse the string "Hello world!":

52 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<?php

echo strrev("Hello world!"); // outputs !dlrow olleH

?>

Output:

!dlrow olleH

4.strpos() - Search For a Text Within a String

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

Search for the text "world" in the string "Hello world!":

<?php

echo strpos("Hello world!", "world"); // outputs 6

?>

Output:

Tip: The first character position in a string is 0 (not 1).

5.str_replace() - Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters
in a string.

Example

53 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Replace the text "world" with "Dolly":

<?php

echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!

?>

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.

Defining a Class in PHP

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 class name should start with an alphabet.

The class name should not be a reserved PHP keyword.

The class name should not contain any spaces.

54 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Now that we know the rules related to naming convention for classes in PHP, let's
create a simple class with name Person.

Syntax for defining a Class in PHP

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.

Below is the code for class Person:

<?php

class Person {

// class variables and methods comes here...

?>

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;

55 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


/* Member functions */

function setPrice($par){

$this->price = $par;

function getPrice(){

echo $this->price ."<br/>";

function setTitle($par){

$this->title = $par;

function getTitle(){

echo $this->title ." <br/>";

?>

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

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.

56 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$physics = new Books;

$maths = new Books;

$chemistry = new Books;

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.

Calling Member Functions

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.

$physics->setTitle( "Physics for High School" );

$chemistry->setTitle( "Advanced Chemistry" );

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

57 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$chemistry->getTitle();

$maths->getTitle();

$physics->getPrice();

$chemistry->getPrice();

$maths->getPrice();

This will produce the following result −

Physics for High School

Advanced Chemistry

Algebra

10

15

3.5 Object properties, object methods, Overloading, inheritance, Constructor


and Destructor

Classes, objects, methods and properties

Object-oriented programming is a programming style in which it is customary to


group all of the variables and functions of a particular topic into a single class.

Object-oriented programming is considered to be more advanced and efficient than


the procedural style of programming. This efficiency stems from the fact that it
supports better code organization, provides modularity, and reduces the need
to repeat ourselves. That being said, we may still prefer the procedural style in
small and simple projects. However, as our projects grow in complexity, we are
better off using the object oriented style.

58 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


How to create classes?

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

How to add properties to a class?

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.

59 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


3

class Car {

public $comp;

public $color = 'beige';

public $hasSunRoof = true;

 We put the public keyword in front of a class property.


 The naming convention is to start the property name with a lower case letter.

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

How to create objects from a class?


We can create several objects from the same class, with each object having its own
set of properties.

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:

$bmw = new Car ();


 We created the object $bmw from the class Car with the new keyword.
 The process of creating an object is also known as instantiation.
We can create more than one object from the same class.

$bmw = new Car ();

60 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$mercedes = new Car ();

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.

How to get an object's properties?

Once we create an object, we


can get its properties. For
In order to get a property, we write the object
example:
name, and then dash greater

echo $bmw -> color; than (->), and then the property name.
echo $mercedes -> color;

Note that the property name does not start


Result:beige with the $ sign; only the object name starts
beige with a $.

How to set the object's properties?

In order to set an object property, we use a similar approach.

For example, in order to set the color to 'blue' in the bmw object:

$bmw -> color = 'blue';

and in order to set the value of the $comp property for both objects:

$bmw -> comp = "BMW";

61 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$mercedes -> comp = "Mercedes Benz";

Once we set the value of a property, we can get its value.

In order to get the color of the $bmw object, we use the following line of code:

echo $bmw -> color;

Result:

Blue

We can also get the company name and the color of the second car object.

echo $mercedes -> color;

echo $mercedes -> comp;

Result:

beige

Mercedes Benz

How to add methods to a class?

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";
}
}

62 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


We can approach the methods similar to the way that we approach the properties,
but we first need to create at least one object from the class.

$bmw = new Car ();


$mercedes = new Car ();
echo $bmw -> hello();
echo $mercedes -> hello();

Result:beep
beep

Complete Example:

<?php

// Declare the class

class Car {

// properties

public $comp;

public $color = 'beige';

public $hasSunRoof = true;

// method that says hello

public function hello()

63 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


return "beep";

// Create an instance

$bmw = new Car ();

$mercedes = new Car ();

// Get the values

echo $bmw -> color; // beige

echo "<br />";

echo $mercedes -> color; // beige

echo "<hr />";

// Set the values

$bmw -> color = 'blue';

$bmw -> comp = "BMW";

$mercedes -> comp = "Mercedes Benz";

// Get the values again

echo $bmw -> color; // blue

echo "<br />";

echo $mercedes -> color; // beige

64 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


echo "<br />";

echo $bmw -> comp; // BMW

echo "<br />";

echo $mercedes -> comp; // Mercedes Benz

echo "<hr />";

// Use the methods to get a beep

echo $bmw -> hello(); // beep

echo "<br />";

echo $mercedes -> hello(); // beep

?>

Function overloading and Overriding in PHP

Function overloading and overriding is the OOPs feature in PHP. In function


overloading, more than one function can have same method signature but different
number of arguments. But in case of function overriding, more than one functions will
have same method signature and number of arguments.

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

65 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


// PHP program to explain function

// overloading in PHP

// Creating a class of type shape

class shape

// __call is magic function which accepts

// function name and arguments

function __call($name_of_function, $arguments)

// It will match the function name

if($name_of_function == 'area')

switch (count($arguments))

// If there is only one argument

// area of circle

case 1:

return 3.14 * $arguments[0];

// IF two arguments then area is rectangel;

case 2:

return $arguments[0]*$arguments[1];

66 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


}

// Declaring a shape type object

$s = new Shape;

// Functio call

echo($s->area(2));

echo "";

// calling area method for rectangel

echo ($s->area(4, 2));

?>

Output:

6.28

Function Overriding:

Function overriding is same as other OOPs programming languages. In function


overriding, both parent and child classes should have same function name with and
number of arguments. It is used to replace parent method in child class. The purpose
of overriding is to change the behavior of parent class method. The two methods with
the same name and same parameter is called overriding.

67 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<?php

// PHP program to implement

// function overriding

// This is parent class

class P {

// Function geeks of parent class

function geeks()

echo "Parent";

// This is child class

class C extends P

// Overriding geeks method

function geeks()

echo "Child";

68 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


}

// Reference type of parent

$p = new P;

// Reference type of child

$c= new C;

// print Parent

$p->geeks();

// Print child

$c->geeks();

?>

Output:
Parent
Child

PHP - What is Inheritance?

Inheritance in OOP = When a class derives from another class.

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.

An inherited class is defined by using the extends keyword.

Let's look at an example:

<?php
69 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
class Fruit {

public $name;

public $color;

public function __construct($name, $color) {

$this->name = $name;

$this->color = $color;

public function intro() {

echo "The fruit is {$this->name} and the color is {$this->color}.";

// Strawberry is inherited from Fruit

class Strawberry extends Fruit {

public function message() {

echo "Am I a fruit or a berry? ";

$strawberry = new Strawberry("Strawberry", "red");

$strawberry->message();

$strawberry->intro();

?>

Output:

70 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Am I a fruit or a berry? The fruit is Strawberry and the color is red.

PHP Constructor

PHP - The __construct Function

A constructor allows you to initialize an object's properties upon creation of the


object.

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;

71 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


}

$apple = new Fruit("Apple");

echo $apple->get_name();

?>

Output:

Apple

PHP Destructor

PHP - The __destruct Function

A destructor is called when the object is destructed or the script is stopped or


exited.

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;

72 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


function __construct($name) {

$this->name = $name;

function __destruct() {

echo "The fruit is {$this->name}.";

$apple = new Fruit("Apple");

?>

Output:

The fruit is Apple.

3.6 Creating HTML Form

An HTML form is used to collect user input. The user input is most often sent to a server for
processing.

Example:

The <form> Element

73 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


The HTML <form> element is used to create an HTML form for user input:

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

The <input> Element

The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on the type attribute.

Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of many


choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

HTML Form Attributes

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

On submit, send form data to "action_page.php":

<form action="/action_page.php">

<label for="fname">First name:</label><br>

<input type="text" id="fname" name="fname" value="John"><br>

<label for="lname">Last name:</label><br>

<input type="text" id="lname" name="lname" value="Doe"><br><br>

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

</form>

Tip: If the action attribute is omitted, the action is set to the current page.

The Target Attribute


The target attribute specifies where to display the response that is received after
submitting the form.

The target attribute can have one of the following values:

Value Description

75 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


_blank The response is displayed in a new window or tab

_self The response is displayed in the current window

_parent The response is displayed in the parent frame

_top The response is displayed in the full body of the window

framename The response is displayed in a named iframe

The default value is _self which means that the response will open in the current
window.

The Method Attribute

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").

The default HTTP method when submitting form data is GET.

Example

This example uses the GET method when submitting the form data:

<form action="/action_page.php" method="get">

Notes on GET:

76 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


1. Appends the form data to the URL, in name/value pairs
2. NEVER use GET to send sensitive data! (the submitted form data is visible in
the URL!)
3. The length of a URL is limited (2048 characters)
4. Useful for form submissions where a user wants to bookmark the result
5. GET is good for non-secure data, like query strings in Google

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

3.7 Handling HTML Form data in PHP

Creating a Simple Contact Form

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>

<p>Please fill in this form and send us.</p>

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

77 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<p>

<label for="inputName">Name:<sup>*</sup></label>

<input type="text" name="name" id="inputName">

</p>

<p>

<label for="inputEmail">Email:<sup>*</sup></label>

<input type="text" name="email" id="inputEmail">

</p>

<p>

<label for="inputSubject">Subject:</label>

<input type="text" name="subject" id="inputSubject">

</p>

<p>

<label for="inputComment">Message:<sup>*</sup></label>

<textarea name="message" id="inputComment" rows="5"


cols="30"></textarea>

</p>

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

<input type="reset" value="Reset">

</form>

</body>

</html>

Explanation of code

78 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Notice that there are two attributes within the opening <form> tag:

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.

Capturing Form Data with PHP

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">

79 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<title>Contact Form</title>

</head>

<body>

<h1>Thank You</h1>

<p>Here is the information you have submitted:</p>

<ol>

<li><em>Name:</em> <?php echo $_POST["name"]?></li>

<li><em>Email:</em> <?php echo $_POST["email"]?></li>

<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>

<li><em>Message:</em> <?php echo $_POST["message"]?></li>

</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

4. Database Handling Using PHP with MySQL


80 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
5.
6. 4.1 Introduction to MySQL: Database terms, Data Types,
MySQL is an open-source, fast reliable, and flexible relational database
management system, typically used with PHP.
What is a Database?

A database is a separate application that stores a collection of data. Each database


has one or more distinct APIs for creating, accessing, managing, searching and
replicating the data it holds.

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.

Nowadays, we use relational database management systems (RDBMS) to store and


manage huge volume of data. This is called relational database because all the data is
stored into different tables and relations are established using primary keys or other
keys known as Foreign Keys.

What is MySQL:

 MySQL is a database system used for developing web-based software


applications.
 MySQL used for both small and large applications.
 MySQL is a relational database management system (RDBMS).
 MySQL is fast, reliable, and flexible and easy to use.
 MySQL supports standard SQL (Structured Query Language).
 MySQL is free to download and use.
 MySQL was developed by Michael Widenius and David Axmark in 1994.
 MySQL is presently developed, distributed, and supported by Oracle
Corporation.
 MySQL Written in C, C++.

Who uses MySQL:

81 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


 Some of the most famous websites like Facebook, Wikipedia, Google (not for
search), YouTube, Flickr.
 Content Management Systems (CMS) like WordPress, Drupal, Joomla, phpBB
etc.
 A large number of web developers worldwide are using MySQL to develop web
applications.
In MySQL there are three main data types: string, numeric, and date and
time.

Data type Description

CHAR(size) A FIXED length string (can contain letters,


numbers, and special characters).
The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1

VARCHAR(size) A VARIABLE length string (can contain letters,


numbers, and special characters).
The size parameter specifies the maximum column
length in characters - can be from 0 to 65535

BINARY(size) Equal to CHAR(), but stores binary byte strings.


The size parameter specifies the column length in
bytes. Default is 1

VARBINARY(size) Equal to VARCHAR(), but stores binary byte


strings. The size parameter specifies the maximum
column length in bytes.

82 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255
bytes

TINYTEXT Holds a string with a maximum length of 255


characters

TEXT(size) Holds a string with a maximum length of 65,535


bytes

BLOB(size) For BLOBs (Binary Large OBjects). Holds up to


65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of


16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to


16,777,215 bytes of data

LONGTEXT Holds a string with a maximum length of


4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to


4,294,967,295 bytes of data

83 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


ENUM(val1, val2, val3, ...) A string object that can have only one value,
chosen from a list of possible values. You can list
up to 65535 values in an ENUM list. If a value is
inserted that is not in the list, a blank value will be
inserted. The values are sorted in the order you
enter them

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

Accessing MySQL –Using MySQL Client and Using phpMyAdmin

Create MySQL Database at the Localhost

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.

Open xampp control panel and start mysql.

84 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Open browser and type http://localhost/

Click on phpMyAdmin link

Create Database

Now return to the homepage of PHPMyAdmin. Click the New button to create a new
database.

85 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


In the new window, name your database as per your need, I am naming it “practice”.
Now select Collation as utf8_general_ci, as we are using it for learning purposes

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

Open command prompt

Microsoft Windows [Version 10.0.15063]

(c) 2017 Microsoft Corporation. All rights reserved.

1.Switch to c: drive type command

C:\Users\Madha>cd\

2.Go to mysql folder type command

C:\>cd C:\xampp\mysql\bin

Login to mysql type following command with details

C:\xampp\mysql\bin>mysql -h localhost -u root

Welcome to the MariaDB monitor. Commands end with ; or \g.


Your MariaDB connection id is 8
Server version: 10.4.17-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and


others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

87 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


1. Show Database:

MariaDB [(none)]> show databases;


+--------------------+
| Database |
+--------------------+
| information_schema |
| mydb |
| mysql |
| performance_schema |
| phpmyadmin |
| test |
+--------------------+
6 rows in set (5.459 sec)

2. Create a database

MariaDB [(none)]> create database demo1;


Query OK, 1 row affected (0.366 sec)

To check database created type command see the list

MariaDB [(none)]> show databases;


+--------------------+
| Database |
+--------------------+
| demo1 |
88 Prepared By Prof: M. G. Rajegave COCSIT, Latur.
| information_schema |
| mydb |
| mysql |
| performance_schema |
| phpmyadmin |
| test |
+--------------------+
7 rows in set (0.002 sec)

3. Use Database/switch to database

MariaDB [(none)]> use demo1


Database changed
MariaDB [demo1]> show tables;
Empty set (0.041 sec)

Create Table

MariaDB [demo1]> create table register


-> (id int,
-> sname varchar(50),
-> address varchar(50));
Query OK, 0 rows affected (0.968 sec)
5.Add data in to a table

89 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


MariaDB [demo1]> insert into register(id,sname,address)
values(1,"Madhav Rajegave","Latur");
Query OK, 1 row affected (1.616 sec)

6.Select data from table

MariaDB [demo1]> select * from register;


+------+-----------------+---------+
| id | sname | address |
+------+-----------------+---------+
| 1 | Madhav Rajegave | Latur |
+------+-----------------+---------+
1 row in set (0.082 sec)

7.Rename a table

MariaDB [demo1]> rename table register to register1;

Query OK, 0 rows affected (0.433 sec)

8.Delete record from table


MariaDB [demo1]> delete from register1 where id=2;
Query OK, 1 row affected (0.222 sec)
Using PHP with MySQL: PHP MySQL Functions

90 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Sr.No Function Name Description

1 mysqli_connect() It opens a connection to a MySQLi Server

2 mysqli_close() It is used to close MySQLi connection

3 mysqli_query() It performs a query against the database.

4 mysqli_fetch_assoc() It is used to fetches a result row as an associative


array.

5 mysqli_num_rows() It returns the number of rows in a result set.

6 mysqli_select_db() This function changes the default database.

7 mysqli_insert_id() It returns an id of last query.


Def
init
ion and Usage

The connect() / mysqli_connect() function opens a new connection to the MySQL


server.

Syntax :

mysqli_connect(host, username, password, dbname);

91 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Parameter Description

host Specifies a host name or an IP address

username Specifies the MySQL username

password Specifies the MySQL password

dbname Specifies the default database to be used

Executing Simple Queries

Example:

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

$dbname=”my_DB”;

// Create connection

92 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


$conn = mysqli_connect($servername, $username, $password,$dbname);

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

Output:
Connected successfully

PHP Create a MySQL Database

A database consists of one or more tables.

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

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

// Create connection

$conn = mysqli_connect($servername, $username, $password);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

93 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


}

// Create database

$sql = "CREATE DATABASE myDB";

if (mysqli_query($conn, $sql)) {

echo "Database created successfully";

} else {

echo "Error creating database: " . mysqli_error($conn);

mysqli_close($conn);

?>

Output:

Database created successfully

Create a MySQL Table Using MySQLi

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

94 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


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

// sql to create table


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

if (mysqli_query($conn, $sql))

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

mysqli_close($conn);
?>

Output: Table MyGuests created successfully

Connecting to MySQL and Selecting the Database

Insert Data Into MySQL Using MySQLi:

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP

95 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


 String values inside the SQL query must be quoted
 Numeric values must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

$sql = "INSERT INTO MyGuests (firstname, lastname, email)

VALUES ('Mahesh', 'Patil', '[email protected]')";

96 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


if (mysqli_query($conn, $sql)) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

mysqli_close($conn);

?>

Output:New record created successfully

Retrieving Query Results


We can display the result in table tag of html

<html>

<body>

<?php

$username = "root";

$password = "";

$database = "mydb";

$conn = mysqli_connect("localhost", $username, $password, $database);

$query = "SELECT * FROM tblinfo";

97 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


echo '<table border="2" cellspacing="2" cellpadding="2">

<tr>

<td> <font face="Arial">ID</font> </td>

<td> <font face="Arial">Emp Name</font> </td>

<td> <font face="Arial">Class Name</font> </td>

<td> <font face="Arial">Address</font> </td>

</tr>';

$result = mysqli_query($conn,$query);

if(mysqli_num_rows($result)>0)

while ($row = mysqli_fetch_assoc($result))

$field1name = $row["id"];

$field2name = $row["name"];

$field3name = $row["class"];

$field4name = $row["address"];

echo '<tr>

98 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


<td>'.$field1name.'</td>

<td>'.$field2name.'</td>

<td>'.$field3name.'</td>

<td>'.$field4name.'</td>

</tr>';

mysqli_close($conn);

?>

</body>

</html>

99 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


Output:

Counting Returned Records


The mysqli_num_rows() function returns the number of rows in a result set.

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

100 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


mysqli_close($conn);
?>
</body>
</html>

Output:
Result set has 7 rows.

Updating Records with PHP


The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Notice the WHERE clause in the UPDATE syntax: The WHERE


clause specifies which record or records that should be updated.
If you omit the WHERE clause, all records will be updated!

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

101 Prepared By Prof: M. G. Rajegave COCSIT, Latur.


?>
</body>
</html>

Output:
Record updated successfully

102 Prepared By Prof: M. G. Rajegave COCSIT, Latur.

You might also like