Module 3A PHP

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 79

CSE2067 - Web Technologies

Department of Computer Science Engineering

School of Engineering
Module III - Syllabus
MODULE III: PHP [L-10hrs.,P- 10hrs.]
• PHP: Introduction to server-side Development with PHP,
Arrays, and Superglobals Arrays, $GET and $ POST, Super
global Arrays, $_SERVER Array, $_Files Array, Reading/Writing
Files, PHP Classes and Objects, Object, Classes and Objects in
PHP, Object Oriented Design, Working with Databases, SQL,
Database APIs, Managing a MySQL Database. Accessing
MySQL in PHP

PHP Introduction
• PHP is a acronym for “PHP: Hypertext Preprocessor”
• PHP is a server-side scripting language and executed on the
server
• PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
• PHP is open source software and free to download.
• PHP was created by Rasmus Lerdorf in 1994 but appeared
in the market in 1995.
PHP Introduction
• PHP runs on different platforms (Windows, Linux, Unix,
etc.)
• PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
• PHP is FREE to download from the official PHP resource:
www.php.net
• PHP is easy to learn and runs efficiently on the server
side
PHP Introduction
Some info on MySQL which we will cover in the next...
•> MySQL is a database server
•> MySQL is ideal for both small and large applications
•> MySQL supports standard SQL
•> MySQL compiles on a number of platforms
•> MySQL is free to download and use
Why use PHP
• PHP is a server-side scripting language, which is used to design
the dynamic web applications with MySQL database.
• PHP supports several protocols such as HTTP, POP3, SNMP,
LDAP, IMAP, and many more.
• Using PHP language, you can control the user to access some
pages of your website.
• PHP can handle the forms, such as - collect the data from users
using forms, save it into the database, and return useful
information to the user. For example - Registration form
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 data through forms
• 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
PHP Syntax
Basic PHP Syntax
• PHP pages contain HTML with embedded code that does
"something”.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>

<?php // Start
// PHP code goes here
?> //End
PHP Introduction
PHP Introduction
PHP code is executed on the server, and the result is returned to the
browser as plain HTML
PHP Getting Started
• To install PHP, we will suggest you to install AMP
(Apache, MySQL, PHP) software stack. There are
many AMP options available in the market that are
given below:
• WAMP for Windows
• LAMP for Linux
• MAMP for Mac
• SAMP for Solaris
• XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross
Platform: It includes some other components too such
as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
PHP Hello World
Executing first PHP script
• First Install the Xampp software.
• Start Apache and MysQL modules.
• Go to Xampp  htdocs
• Create the PHP script and save it using .php extension.
• Open the browser and type: localhost/first.php
PHP Hello World
// PHP files have extension ".php“ (first.php)
// Write the following code inside a notepad file and save it in
htdocs folder
PHP echo and print Statements

• echo and print are more or less the same.


• 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.
PHP echo and print Statements

• Echo • Print
<?php <?php
$name="John"; $name="John";
echo $name; print $name;
//or //or
echo ($name); print ($name);
?> ?>
PHP Comments

In PHP, we use // or # to make a single-line comment or


/* and */ to make a large comment block.
PHP Variables

• Variables are used for storing values, like text strings,


numbers or arrays.
• All variables in PHP start with a $ sign symbol.
• The correct way of declaring a variable in PHP:
PHP Variables

• In PHP, a variable does not need to be declared before adding a


value to it.
• you do not have to tell PHP which data type the variable is.
• PHP automatically converts the variable to the correct data
type, depending on its value.
PHP Variables

RULES
• A variable name must start with a letter or an underscore "_“
not a number
• A variable name can only contain alpha-numeric characters,
underscores (a-z, A-Z, 0-9, and _ )
• A variable name should not contain spaces. If a variable name
is more than one word, it should be separated with an
underscore ($my_string) or with capitalization ($myString)
PHP Variables
// Defining new variables and printing their values
<html>
<body>
<?php
$txt = "Hello world!"; // defining variable
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x; Hello world!
5
echo "<br>";
10.5
echo $y;
?>
</body>
</html>
PHP Variables
PHP variables: local and global
<html>
<body> Notice: Undefined variable: x in C:\xampp\htdocs\
<? php first.php on line 9
$x = 5; // global scope Variable x inside function is:
Variable x outside function is: 5
function Test() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}

Test();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
PHP Variables
PHP variables: local and global
<html>
<body> print('Variable x inside
<? php function is:'.$x);
$x=10;
function Test() {
$x=5;
echo "<p>Variable x inside function is: $x</p>";
}
Test();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html> Variable x inside function is: 5
Variable x outside function is: 10
PHP Variables
PHP variables: local and global
<html>
<body>
<? php
$x=5;
$y=6;

function Test() {
global $x,$y; //Access global variable
$x=$y+$x;
}
Test();
echo "<p>Sum of Number: $x</p>";
?>
</body>
</html> Sum of 2 numbers: 11
PHP Variables
PHP variables: static
Normally, when a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable NOT to be
deleted. We need it for a further job.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
012
myTest();
myTest();
myTest();
?>
PHP Concatenation

• The concatenation operator (.) is used to put two string values


together.
• To concatenate two string variables together, use the
concatenation operator:
<?php
$x = "good";
$y= "morning";
echo $x." ".$y;
?> good morning
PHP – Html code
<body>
<h1>Hello HTML</h1>
<p>
<?php
echo "Hi there.";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?";
?>
</p>
<p>Yes another paragraph.</p>
</body>
PHP Data Types

Variables can store data of different types, and


different data types can do different things.

PHP supports the following data types:


• String
• Integer
• Float (floating point numbers - also called
double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
A string is a sequence of characters, like "Hello
world!".
A string can be any text inside quotes.
To use single or double quotes
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
• An integer data type is a non-decimal number between
-2,147,483,648 and 2,147,483,647.
• In the following example $x is an integer.
• The PHP var_dump() function returns the data type and value

<?php
int(5985)
$x = 5985;
var_dump($x);
?>
PHP float
A float (floating point number) is a number with a decimal point or
a number in exponential form.

Example
<?php
$x = 10.365;
var_dump($x);
?>
Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars); array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW"
?> [2]=> string(6) "Toyota" }

NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value
assigned to it. Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x); ?>
PHP Operators

•Arithmetic Operators
•Logical or Relational Operators
•Comparison Operators
•Conditional or Ternary Operators
•Assignment Operators
•Array Operators
•Increment/Decrement Operators
•String Operators
PHP Operators

1.Arithmetic Operator 3.Array Operator


+ = Addition + = Union
- = Subtraction == = Equality
* = Multiplication === = Identity
/ = Division != = Inequality
% = Modulo <> = Inequality
** = Exponentiation !== = Non-identity

2.Assignment Operator 4.Bitwise Operator


= equal to & = and
^ = xor
| = not
<< = shift left
>> = shift right
PHP Operators
5.Comparison Operator 6.Incrementing/Decrementing
== = equal Operator
=== = identical ++$a = PreIncrement
!= = not equal $a++ = PostIncrement
!== = not identical --$a = PreDecrement
<> = not equal $a-- = Postdecrement
< = less than
<= =less than or equal
> = greater than
>= = greater than or equal 7.Logical Operator
<=> = spaceship operator && = And
(-1,0,1) || = Or
! = Not
and = And
xor = Xor
or = Or
PHP Operators

8. string Operator
. = concatenation operator
.= =concatenating assignment operator
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;

9. Ternary or Conditional operator


?: = Ternary operator
<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
Value of b is 5 print ("Value of b is " .
$b);
?>
PHP Conditional statements

PHP if else statement is used to test condition.

•if
•if-else
•if-else-if
•nested if
PHP Conditional statements
PHP If Statement

<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
12 is less than 100
PHP Conditional statements
PHP If else Statement

<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}
else{
echo "$num is odd number";
}
?>
12 is even number
PHP Conditional statements
PHP If-else-if Statement
<?php
$marks=69; else if ($marks>=80 && $mar
if ($marks<33){ ks<90) {
echo "fail"; echo "A grade";
} }
else if ($marks>=34 && $m else if ($marks>=90 && $mar
arks<50) { echo "D grad ks<100) { echo "A+ grade
e"; ";
} }
else if ($marks>=50 && $m else {
arks<65) { echo "C grade echo "Invalid input";
"; }
} ?>
else if ($marks>=65 && $m
B Grade
arks<80) { echo "B grad
e";
}
PHP Conditional statements
PHP Switch Statement
<?php
$favcolor = "red";
switch ($favcolor) {
case "red": echo "Your favourite color is red!"; break;
case "blue": echo "Your favourite color is blue!"; break;
default: echo “Wrong Choice ";
}
?>
PHP Loop
In PHP, we have the following loop types:

• while - loops through a block of code as long as the specified


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

<?php <?php
$x = 1; $x = 1;

while($x <= 5)
do {
{
echo "The number is: $x echo "The number is: $x <br>";
<br>";
$x++;
$x++;
} } while ($x <= 5);
?>
?>
PHP Loop
PHP for Loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
PHP foreach Loop
?>
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) { red


echo “ $value <br>"; green
} blue
?> yellow
PHP Loop
PHP for Loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
PHP foreach Loop
?>
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) { red


echo “ $value <br>"; green
} blue
?> yellow
PHP Functions

• PHP function is a piece of code that can be reused


many times.
• It can take input as argument list and return value

Syntax Example
function functionname(){ <?php
//code to be executed function sayHello(){
echo "Hello PHP Functio
} n";
}
sayHello();//
calling function
?>
PHP Function Arguments

• pass the information in PHP function through


arguments which is separated by comma.
• PHP supports :
 Call by Value (default),
 Call by Reference
 Default argument values
PHP Function Arguments

PHP Call By Value

<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old
<br/>";
}
sayHello("Sai",27); Hello Sai, you are 27 years old
sayHello("Vimal",29); Hello Vimal, you are 29 years old
Hello John, you are 23 years old
sayHello("John",23);
?>
PHP Function Arguments

PHP Call By Reference


• To pass value as a reference, you need to
use ampersand (&) symbol before the
argument name.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';

}
$str = 'Hello ';
adder($str); Hello Call By Reference
echo $str;
?>
PHP Function Arguments

PHP Default Argument Value


• don't specify any argument, it will take the
default argument.
<?php
function sayHello($name="SA
I"){

Hello Rajesh echo "Hello $name<br/>";


Hello SAI
}
Hello John
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
PHP Function Arguments

PHP Returning Value


• PHP function that returns value.

<?php

function cube($n){
return $n*$n*$n;
}

echo "Cube of 3 is: ".cube(3 Cube of 3 is: 27


);
?>
PHP Function Arguments

PHP Parameterized Example 1


<html>
<head> <title>Parameter Addition and Subtraction Example<
/title> </head>
<body>
<?php
function add($x, $y) { //Adding two numbers
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>"
;
}
add(467, 943);
?>
</body>
</html>
PHP Function Arguments

PHP Parameterized Example 2 – using forms


<?php
function add($x,$y) {
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
if(isset($_POST[‘submit'])) {
add($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number"
name="first"/><br><br>
Enter second number: <input type="number"
name="second"/><br><br>
<input type="submit" name=“submit" value="ADDITION"/>
</form>
PHP Array

An array stores multiple values in one single


variable:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
PHP Array

Create an Array in PHP


• array(); - function is used to create an array

In PHP, there are three types of arrays:


•Indexed arrays - Arrays with a numeric index
•Associative arrays - Arrays with named keys
•Multidimensional arrays - Arrays containing one or
more arrays
PHP Array

Get The Length of an Array - The count()


Function
• The count() function is used to return the length
(the number of elements) of an array
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars); // 3
?>
PHP Array

PHP Indexed Arrays


• Here are two ways to create indexed arrays:
• The index can be assigned automatically .
$cars = array("Volvo", "BMW", "Toyota");

• The index can be assigned manually:


$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
PHP Array

Loop Through an Indexed Array


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

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


echo $cars[$x];
echo "<br>";
}
Volvo
?> BMW
Toyota
PHP Array

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

Loop Through an Associative Array


Example

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

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


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

PHP - Multidimensional Arrays

• A multidimensional array is an array containing one or


more arrays
PHP Array

Two-dimensional Arrays
A two-dimensional array is an array of arrays

$cars = array ( array("Volvo",22,18),


array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15) );
PHP Array

Two-dimensional Arrays
for ($row = 0; $row < 4; $row++)
Example
{
<?php echo "<p><b>Row number $row</b></p>";
$cars = array ( echo "<ul>";
array("Volvo",22,18), for ($col = 0; $col < 3; $col++)
array("BMW",15,13), {
array("Saab",5,2), echo "<li>".$cars[$row][$col]."</li>";
array("Land Rover",17,15) }
); echo "</ul>";
}
?>

Row number 0
•Volvo
•22
•18
CSE-367 Data Visualization 63
PHP Array

Sorting Arrays
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.

Sort Functions For Arrays


• 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
PHP Array
Sorting Arrays
The following example sorts the elements of the $cars array in
ascending alphabetical order:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength = count($cars);
sort($cars);
for($x =0; $x < $arrlength; $x++)
{
echo $cars[$x];
BMW
echo "<br>"; Toyota
} Volvo
?>
PHP Superglobals:
• Super global variables are built-in variables that are always
available in all scopes
• Some predefined variables in PHP are "superglobals", which means that
they are always accessible, regardless of scope - and you can access them
from any function, class or file without having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
PHP $GLOBALS

$GLOBALS is an associative array of references to all


globally defined variables. Names of variables form keys
and their contents are values of associative array.
Example #1 $GLOBALS example

<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
Example
<?php
echo $_SERVER['PHP_SELF’];/*Returns the filename of the currently executing script
echo "<br>";
echo $_SERVER['SERVER_NAME’];/*Returns the name of the host server (such as www.w3schools.com)
echo "<br>";
echo $_SERVER['HTTP_HOST’]; /*Host header from the current request
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>"; complete URL of the
current page
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>the path of the current script
PHP $_GET
The GET method is used to submit the
HTML form data. This data is collected by the
predefined $_GET variable for processing.

The information sent from an HTML form


using the GET method is visible to everyone
in the browser's address bar, which means
that all the variable names and their values
will be displayed in the URL.
localhost/gettest.php?
username=Harry&bloodgroup=AB+
PHP $_GET
The below code will display an HTML form containing
two input fields and a submit button. In this HTML
form, we used the method = "get" to submit the form
data.
<form action="welcome.php" method=“get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
<?php
echo $_GET["name"];
echo $_GET["email"];
?>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to
collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
<?php
echo $_POST["name"];
echo $_POST["email"];
?>
$_FILES – Superglobal Variable
$_FILES superglobal variable used when we upload files using
Form elements. All the necessary information including File
temporary name, File size, File Type are available in this $_FILES
variable.

Example
<form method="POST" action="action.php" enctype="multipart/form-
data">
<input type="text" name="name"/>
<input type="file" name="file" id="file" />
<input type="submit" value="Send"/>
</form>
<?php
echo "<pre>";
print_r($_FILES); echo "</pre>"; //prints uploaded File's information
echo $_POST['name'];
?>
PHP File Handling
• File handling is an important part of any web application. You
often need to open and process a file for different tasks.
Manipulating Files
• PHP has several functions for creating, reading, uploading, and
editing files.
readfile() Function
• The readfile() function reads a file and writes it to the output
buffer.
PHP File Handling

<?php
echo readfile("Hai.txt");
?>
PHP File Handling
Open File - fopen()
• A better method to open files is with the fopen() function.
• This function gives you more options than the readfile() function.
$myfile = fopen(“Hai.txt", "r") or die("Unable to open file!");

Read File - fread()


• The fread() function reads from an open file.
fread($myfile,filesize("webdictionary.txt"));

Close File - fclose()


• The fclose() function is used to close an open file.
fclose($myfile);
PHP File Handling
<!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen(“Hai.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize(“Hai.txt"));
fclose($myfile);
?>
</body>
</html>
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already
exists
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the
file to write to and the second parameter is the string to
be written.

<?php
$myfile = fopen("Haii.txt", "w") or
die(“Error!");
$txt = "Prabhu\n";
fwrite($myfile, $txt);
$txt = "Shankar\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
CSE-367 Data Visualization 79

You might also like