SlideShare una empresa de Scribd logo
1 de 66
PHP & MySQL
UNIT IV
Why PHP and MySQL?
 PHP is the most popular scripting language for web development.
 It is free, open source and server-side (the code is executed on the server).
 MySQL is a Relational Database Management System (RDBMS) that uses
Structured Query Language (SQL).
 It is also free and open source.
PHP MySQL Database
 With PHP, you can connect to and manipulate databases.
 What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 The data in a MySQL database are stored in tables.
 A table is a collection of related data, and it consists of columns and rows.
 Databases are useful for storing information categorically. A company may have a
database with the following tables:
 Employees
 Products
 Customers
 Orders
Server-side scripting
 Server-side scripting is a technique used in web development which involves
employing scripts on a web server which produce a response customized for each
user's (client's) request to the website.
 The alternative is for the web server itself to deliver a static web page. Scripts can be
written in any of a number of server-side scripting languages that are available.
 Server-side scripting is distinguished from client-side scripting where embedded
scripts, such as JavaScript, are run client-side in a web browser, but both techniques
are often used together.
Server-side scripting
PHP 5 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;
?>
 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)
Run a PHP program in Server
 It is server-side scripting language for producing dynamic Web pages.
 PHP was originally created by Rasmus Lerdorf in 1995.
 The full-form of PHP is a recursive name i.e. PHP Hypertext Preprocessor.
 PHP program can be run under various like WAMP, XAMPP etc.
 WAMP Server: this server is a web development platform which helps in creating
dynamic web applications.
 XAMPP Server: It is a free open source cross-platfrom web server package.
Steps to run PHP Script
 Install XAMPP
 Go to: C:xampphtdocs
 Create your own folder, name it for example as tutorialspoint.
 Now create your first php program in xampp and name it as “add.php”:
 Now double click on “XAAMP CONTROL PANEL” on desktop and START “Apache”
 Type localhost on your browser and press enter:
 Now type the following on browser:
http://localhost/tutorialspoint/
 Click on “add.php” and it will show the following:
Steps to run PHP Script
Add.php program
<html>
<head><title>Addition php</title></head>
<body>
<?php
# operator
print "<h2>php program to add two numbers...</h2><br />";
$val1 = 20;
$val2 = 20;
$sum = $val2 + $val2; /* Assignment operator */
echo "Result(SUM): $sum";
?>
</body>
Creating (Declaring) PHP Variables
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello
world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
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
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “Anna Leela College";
echo "I love $txt!";
?>
</body>
</html>
 The following example will output the
sum of two variables:
 Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
PHP Variables Scope
 In PHP, variables can be declared anywhere in the script.
 The scope of a variable is the part of the script where the
variable can be referenced/used.
 PHP has three different variable scopes:
 local
 global
 static
Global and Local Scope
 A variable declared outside a function
has a GLOBAL SCOPE and can only be
accessed outside a function:
 Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
 function myTest() {
// using x inside this function will generate an
error
echo "<p>Variable x inside function is:
$x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
Global and Local Scope
 A variable declared within a function has a
LOCAL SCOPE and can only be accessed within
that function:
 Example
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will
generate an error
echo "<p>Variable x outside
function is: $x</p>";
?>
</body>
</html>
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. You can use single or double quotes:
 Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
PHP Integer
 An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
 Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal
(16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
PHP Integer
 In the following example $x is an integer. The PHP var_dump() function returns
the data type and value:
 Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
PHP Float
 A float (floating point number) is a number with a decimal point or a number in
exponential form.
 In the following example $x is a float. The PHP var_dump() function returns the data
type and value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>
PHP Boolean
 A Boolean represents two possible states: TRUE or FALSE.
 $x = true;
 $y = false;
 Booleans are often used in conditional testing. You will learn more
about conditional testing in a later chapter of this tutorial.
PHP Array
 An array stores multiple values in one single variable.
 In the following example $cars is an array. The PHP var_dump() function returns
the data type and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Conditional Statements
 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
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
<?php
$t = date("H"); //H is 8th Letter in Alphabets… Date(“H”) will return value 07
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if Statement
<!DOCTYPE html>
<html>
<body>
<?php
$t = 10;
echo $t;
if ($t < "20") {
echo "No. is less than 20!";
}
?>
</body>
</html>
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!";
}
?>
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 this condition is
true;
} else {
code to be executed if all conditions are
false;
}
Example
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The PHP 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;
}
The PHP switch Statement
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
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!";
}
?>
</body>
</html>
PHP Loops
 Loops are used when you want the same block of code to run
over and over again in a row. Instead of adding several almost equal
code-lines in a script, we can use loops to perform a task like this.
 In PHP, we have the following looping statements:
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
The PHP while Loop
 The while loop executes a block of code as long as the specified condition is true.
 Syntax
while (condition is true) {
code to be executed;
}
 Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP while Loop
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
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;
} while (condition is true);
The PHP do...while Loop
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is:
$x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
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;
}
 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
The PHP for Loop
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
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.
The PHP foreach Loop
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
</body>
</html>
Loop termination in PHP: break
 break ends execution of the current for, foreach, while, do-
while or switch structure.
 break accepts an optional numeric argument
which tells it how many nested enclosing
structures are to be broken out of.
 The default value is 1, only the immediate enclosing structure is broken out of.
Loop termination in PHP: break
<html>
<head><title>Addition
php</title></head>
<body>
<?php
$arr = array('one', 'two',
'three', 'four', 'stop',
'five');
while (list(, $val) =
each($arr)) {
if ($val == 'stop') {
break; /* You could
also write 'break 1;' here.
*/ }
echo "$val<br />n"; }
?>
</body>
Break Using the optional argument
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
PHP User Defined Functions
 The real power of PHP comes from its functions; it has more than 1000
built-in functions.
 Besides the built-in PHP functions, we can create our own functions.
 A function is a block of statements that can be used repeatedly in a
program.
 A function will not execute immediately 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 can start with a letter or underscore (not a
number).
 Tip: Give the function a name that reflects what the function does!
Create a User Defined Function in PHP
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
PHP Function Arguments
 Information can be passed to functions through arguments. An argument is just like a variable.
 Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
 Example:
<?php
function familyName($fname) {
echo "$fname Welcome.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
PHP Function Arguments
<!DOCTYPE html>
<html> <body>
<?php
function familyName($fname) {
echo "Welcome $fname.<br>"; }
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
</body> </html>
PHP Functions - Returning values
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $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);
?>
</body>
</html>
PHP 5 Form Handling: GET, POST Methods
 When the user fills out the form and clicks the submit button, the form
data is sent for processing to a PHP file
 The form data is sent with the HTTP POST method.
 The same result could also be achieved using the HTTP GET method.
 Example: Continued…
When to use GET?
 Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL). GET
also has limits on the amount of information to send. The limitation is
about 2000 characters. However, because the variables are displayed in
the URL, it is possible to bookmark the page. This can be useful in some
cases.
 GET may be used for sending non-sensitive data.
 Note: GET should NEVER be used for sending passwords or other
sensitive information!
When to use POST?
 Information sent from a form with the POST method is invisible to
others (all names/values are embedded within the body of the HTTP
request) and has no limits on the amount of information to send.
 Moreover POST supports advanced functionality such as support for
multi-part binary input while uploading files to server.
 However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
 Developers prefer POST for sending form data.
GET vs. POST
 Both GET and POST create an array
(e.g. array( key => value, key2 => value2, key3 => value3, ...)).
 This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.
 Both GET and POST are treated as $_GET and $_POST. These 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.
 $_GET is an array of variables passed to the current script via the URL
parameters.
 $_POST is an array of variables passed to the current script via the HTTP POST
method.
PHP 5 Form Handling: GET, POST Methods
<!DOCTYPE HTML>
<html>
<body>
<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>
</body>
</html>
<html>
<body>
Welcome
<?php
echo $_POST["name"]; ?><br>
Your email address is: <?php echo
$_POST["email"];
?>
</body>
</html>
Welcome.php
PHP 5 Form Handling: GET, POST Methods
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome_get.php"
method="get">
Name: <input type="text"
name="name"><br>
E-mail: <input type="text"
name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome
<?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo
$_GET["email"];
?>
</body>
</html>
Welcome_get.php
PHP Global Variables - Superglobals
Several 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
 $_ENV
 $_COOKIE
 $_SESSION
PHP $GLOBALS
 $GLOBALS is a PHP super global
variable which is used to access global
variables from anywhere in the PHP
script (also from within functions or
methods).
 PHP stores all global variables in an
array called $GLOBALS[index].
The index holds the name of the
variable.
<?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.
<!DOCTYPE html>
<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>
PHP Error Handling
 When creating scripts and web applications, error handling is an important part.
 If your code lacks error checking code, your program may look very unprofessional
and you may be open to security risks.
 The default error handling in PHP is very simple. An error message with filename,
line number and a message describing the error is sent to the browser.
 We will show different error handling methods:
 Simple "die()" statements
 Custom errors and error triggers
 Error reporting
Basic Error Handling: Using the die()
function
 The example shows a simple script that opens a text file:
 <?php
$file=fopen("welcome.txt","r");
?>
 If the file does not exist you might get an error like this:
 Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:webfoldertest.php on line 2
 To prevent the user from getting an error message like the one above, we test
whether the file exist before we try to access it.
Continued…
Basic Error Handling: Using the die()
function
<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
 Now if the file does not exist you get an error like this:
 File not found
<!DOCTYPE html>
<html>
<body>
<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
</body>
</html>
Creating a Custom Error Handler
 Creating a custom error handler is quite simple.
 We simply create a special function that can be called when an error occurs
in PHP.
 This function must be able to handle a minimum of two parameters (error level
and error message) but can accept up to five parameters (optionally: file, line-
number, and the error context):
 Syntax
error_function(error_level,error_message,error_file,error_line,error_context
)
Creating a Custom Error Handler
Parameter Description
error_level Required. Specifies the error report level for the user-defined error. Must be a
value number. See table below for possible error report levels
error_message Required. Specifies the error message for the user-defined error
error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their values, in use
when the error occurred
Error Report levels
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also
happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the
PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the
programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the
PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined
handle (see also set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
Set Error Handler
 The default error handler for PHP is the built in error handler.
 It is possible to change the error handler to apply for only some errors, that way
the script can handle different errors in different ways.
 set_error_handler("customError");
Set Error Handler
<!DOCTYPE html>
<html>
<head>
<title>PHP Demo</title>
</head>
<body>
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
</body>
</html>
Trigger an Error
 In a script where users can input data it is useful to trigger errors when an
illegal input occurs.
 In PHP, this is done by the trigger_error() function.
 Example
 In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
Trigger an Error
<!DOCTYPE html>
<html>
<head>
<title>PHP Demo</title>
</head>
<body>
<? php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or
below");
}
?>
</body>
</html>

Más contenido relacionado

La actualidad más candente

Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 

La actualidad más candente (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
01 Php Introduction
01 Php Introduction01 Php Introduction
01 Php Introduction
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
PHP
PHPPHP
PHP
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
Operators php
Operators phpOperators php
Operators php
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Laravel
LaravelLaravel
Laravel
 

Similar a FYBSC IT Web Programming Unit IV PHP and MySQL

Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
Swanand Pol
 

Similar a FYBSC IT Web Programming Unit IV PHP and MySQL (20)

Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php
PhpPhp
Php
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
PHP-Part1
PHP-Part1PHP-Part1
PHP-Part1
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 

Más de Arti Parab Academics

Más de Arti Parab Academics (20)

COMPUTER APPLICATIONS Module 4.pptx
COMPUTER APPLICATIONS Module 4.pptxCOMPUTER APPLICATIONS Module 4.pptx
COMPUTER APPLICATIONS Module 4.pptx
 
COMPUTER APPLICATIONS Module 1 HPSY - Copy.pptx
COMPUTER APPLICATIONS Module 1 HPSY - Copy.pptxCOMPUTER APPLICATIONS Module 1 HPSY - Copy.pptx
COMPUTER APPLICATIONS Module 1 HPSY - Copy.pptx
 
COMPUTER APPLICATIONS Module 5.pptx
COMPUTER APPLICATIONS Module 5.pptxCOMPUTER APPLICATIONS Module 5.pptx
COMPUTER APPLICATIONS Module 5.pptx
 
COMPUTER APPLICATIONS Module 1 CAH.pptx
COMPUTER APPLICATIONS Module 1 CAH.pptxCOMPUTER APPLICATIONS Module 1 CAH.pptx
COMPUTER APPLICATIONS Module 1 CAH.pptx
 
COMPUTER APPLICATIONS Module 3.pptx
COMPUTER APPLICATIONS Module 3.pptxCOMPUTER APPLICATIONS Module 3.pptx
COMPUTER APPLICATIONS Module 3.pptx
 
COMPUTER APPLICATIONS Module 2.pptx
COMPUTER APPLICATIONS Module 2.pptxCOMPUTER APPLICATIONS Module 2.pptx
COMPUTER APPLICATIONS Module 2.pptx
 
Health Informatics- Module 5-Chapter 2.pptx
Health Informatics- Module 5-Chapter 2.pptxHealth Informatics- Module 5-Chapter 2.pptx
Health Informatics- Module 5-Chapter 2.pptx
 
Health Informatics- Module 5-Chapter 3.pptx
Health Informatics- Module 5-Chapter 3.pptxHealth Informatics- Module 5-Chapter 3.pptx
Health Informatics- Module 5-Chapter 3.pptx
 
Health Informatics- Module 4-Chapter 3.pptx
Health Informatics- Module 4-Chapter 3.pptxHealth Informatics- Module 4-Chapter 3.pptx
Health Informatics- Module 4-Chapter 3.pptx
 
Health Informatics- Module 3-Chapter 2.pptx
Health Informatics- Module 3-Chapter 2.pptxHealth Informatics- Module 3-Chapter 2.pptx
Health Informatics- Module 3-Chapter 2.pptx
 
Health Informatics- Module 4-Chapter 1.pptx
Health Informatics- Module 4-Chapter 1.pptxHealth Informatics- Module 4-Chapter 1.pptx
Health Informatics- Module 4-Chapter 1.pptx
 
Health Informatics- Module 4-Chapter 2.pptx
Health Informatics- Module 4-Chapter 2.pptxHealth Informatics- Module 4-Chapter 2.pptx
Health Informatics- Module 4-Chapter 2.pptx
 
Health Informatics- Module 3-Chapter 3.pptx
Health Informatics- Module 3-Chapter 3.pptxHealth Informatics- Module 3-Chapter 3.pptx
Health Informatics- Module 3-Chapter 3.pptx
 
Health Informatics- Module 5-Chapter 1.pptx
Health Informatics- Module 5-Chapter 1.pptxHealth Informatics- Module 5-Chapter 1.pptx
Health Informatics- Module 5-Chapter 1.pptx
 
Health Informatics- Module 3-Chapter 1.pptx
Health Informatics- Module 3-Chapter 1.pptxHealth Informatics- Module 3-Chapter 1.pptx
Health Informatics- Module 3-Chapter 1.pptx
 
Health Informatics- Module 2-Chapter 2.pptx
Health Informatics- Module 2-Chapter 2.pptxHealth Informatics- Module 2-Chapter 2.pptx
Health Informatics- Module 2-Chapter 2.pptx
 
Health Informatics- Module 1-Chapter 1.pptx
Health Informatics- Module 1-Chapter 1.pptxHealth Informatics- Module 1-Chapter 1.pptx
Health Informatics- Module 1-Chapter 1.pptx
 
Health Informatics- Module 2-Chapter 3.pptx
Health Informatics- Module 2-Chapter 3.pptxHealth Informatics- Module 2-Chapter 3.pptx
Health Informatics- Module 2-Chapter 3.pptx
 
Health Informatics- Module 2-Chapter 1.pptx
Health Informatics- Module 2-Chapter 1.pptxHealth Informatics- Module 2-Chapter 1.pptx
Health Informatics- Module 2-Chapter 1.pptx
 
Health Informatics- Module 1-Chapter 2.pptx
Health Informatics- Module 1-Chapter 2.pptxHealth Informatics- Module 1-Chapter 2.pptx
Health Informatics- Module 1-Chapter 2.pptx
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 

FYBSC IT Web Programming Unit IV PHP and MySQL

  • 2. Why PHP and MySQL?  PHP is the most popular scripting language for web development.  It is free, open source and server-side (the code is executed on the server).  MySQL is a Relational Database Management System (RDBMS) that uses Structured Query Language (SQL).  It is also free and open source.
  • 3. PHP MySQL Database  With PHP, you can connect to and manipulate databases.  What is MySQL?  MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications  MySQL is very fast, reliable, and easy to use  MySQL uses standard SQL  MySQL compiles on a number of platforms  MySQL is free to download and use  MySQL is developed, distributed, and supported by Oracle Corporation  The data in a MySQL database are stored in tables.  A table is a collection of related data, and it consists of columns and rows.  Databases are useful for storing information categorically. A company may have a database with the following tables:  Employees  Products  Customers  Orders
  • 4. Server-side scripting  Server-side scripting is a technique used in web development which involves employing scripts on a web server which produce a response customized for each user's (client's) request to the website.  The alternative is for the web server itself to deliver a static web page. Scripts can be written in any of a number of server-side scripting languages that are available.  Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.
  • 6. PHP 5 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; ?>  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)
  • 7. Run a PHP program in Server  It is server-side scripting language for producing dynamic Web pages.  PHP was originally created by Rasmus Lerdorf in 1995.  The full-form of PHP is a recursive name i.e. PHP Hypertext Preprocessor.  PHP program can be run under various like WAMP, XAMPP etc.  WAMP Server: this server is a web development platform which helps in creating dynamic web applications.  XAMPP Server: It is a free open source cross-platfrom web server package.
  • 8. Steps to run PHP Script  Install XAMPP  Go to: C:xampphtdocs  Create your own folder, name it for example as tutorialspoint.  Now create your first php program in xampp and name it as “add.php”:  Now double click on “XAAMP CONTROL PANEL” on desktop and START “Apache”  Type localhost on your browser and press enter:  Now type the following on browser: http://localhost/tutorialspoint/  Click on “add.php” and it will show the following:
  • 9. Steps to run PHP Script
  • 10. Add.php program <html> <head><title>Addition php</title></head> <body> <?php # operator print "<h2>php program to add two numbers...</h2><br />"; $val1 = 20; $val2 = 20; $sum = $val2 + $val2; /* Assignment operator */ echo "Result(SUM): $sum"; ?> </body>
  • 11. Creating (Declaring) PHP Variables <!DOCTYPE html> <html> <body> <?php $txt = "Hello world!"; $x = 5; $y = 10.5; echo $txt; echo "<br>"; echo $x; echo "<br>"; echo $y; ?> </body> </html>
  • 12. 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 <!DOCTYPE html> <html> <body> <?php $txt = “Anna Leela College"; echo "I love $txt!"; ?> </body> </html>  The following example will output the sum of two variables:  Example <!DOCTYPE html> <html> <body> <?php $x = 5; $y = 4; echo $x + $y; ?> </body> </html>
  • 13. PHP Variables Scope  In PHP, variables can be declared anywhere in the script.  The scope of a variable is the part of the script where the variable can be referenced/used.  PHP has three different variable scopes:  local  global  static
  • 14. Global and Local Scope  A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:  Example <!DOCTYPE html> <html> <body> <?php $x = 5; // global scope  function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>
  • 15. Global and Local Scope  A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:  Example <!DOCTYPE html> <html> <body> <?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>
  • 16. 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
  • 17. PHP String  A string is a sequence of characters, like "Hello world!".  A string can be any text inside quotes. You can use single or double quotes:  Example <!DOCTYPE html> <html> <body> <?php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; ?> </body> </html>
  • 18. PHP Integer  An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.  Rules for integers:  An integer must have at least one digit  An integer must not have a decimal point  An integer can be either positive or negative  Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
  • 19. PHP Integer  In the following example $x is an integer. The PHP var_dump() function returns the data type and value:  Example <!DOCTYPE html> <html> <body> <?php $x = 5985; var_dump($x); ?> </body> </html>
  • 20. PHP Float  A float (floating point number) is a number with a decimal point or a number in exponential form.  In the following example $x is a float. The PHP var_dump() function returns the data type and value: <!DOCTYPE html> <html> <body> <?php $x = 10.365; var_dump($x); ?> </body> </html>
  • 21. PHP Boolean  A Boolean represents two possible states: TRUE or FALSE.  $x = true;  $y = false;  Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.
  • 22. PHP Array  An array stores multiple values in one single variable.  In the following example $cars is an array. The PHP var_dump() function returns the data type and value: Example <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?>
  • 23. PHP Conditional Statements  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
  • 24. 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 <?php $t = date("H"); //H is 8th Letter in Alphabets… Date(“H”) will return value 07 if ($t < "20") { echo "Have a good day!"; } ?>
  • 25. PHP - The if Statement <!DOCTYPE html> <html> <body> <?php $t = 10; echo $t; if ($t < "20") { echo "No. is less than 20!"; } ?> </body> </html>
  • 26. 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!"; } ?>
  • 27. 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 this condition is true; } else { code to be executed if all conditions are false; } Example <?php $t = date("H"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
  • 28. The PHP 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; }
  • 29. The PHP switch Statement <!DOCTYPE html> <html> <body> <?php $favcolor = "red"; 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!"; } ?> </body> </html>
  • 30. PHP Loops  Loops are used when you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.  In PHP, we have the following looping statements: 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
  • 31. The PHP while Loop  The while loop executes a block of code as long as the specified condition is true.  Syntax while (condition is true) { code to be executed; }  Example <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
  • 32. The PHP while Loop <!DOCTYPE html> <html> <body> <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?> </body> </html>
  • 33. 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; } while (condition is true);
  • 34. The PHP do...while Loop <!DOCTYPE html> <html> <body> <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 5); ?> </body> </html>
  • 35. 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; }  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
  • 36. The PHP for Loop <!DOCTYPE html> <html> <body> <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> </body> </html>
  • 37. 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.
  • 38. The PHP foreach Loop <!DOCTYPE html> <html> <body> <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> </body> </html>
  • 39. Loop termination in PHP: break  break ends execution of the current for, foreach, while, do- while or switch structure.  break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.  The default value is 1, only the immediate enclosing structure is broken out of.
  • 40. Loop termination in PHP: break <html> <head><title>Addition php</title></head> <body> <?php $arr = array('one', 'two', 'three', 'four', 'stop', 'five'); while (list(, $val) = each($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br />n"; } ?> </body>
  • 41. Break Using the optional argument $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />n"; break 2; /* Exit the switch and the while. */ default: break; } }
  • 42. PHP User Defined Functions  The real power of PHP comes from its functions; it has more than 1000 built-in functions.  Besides the built-in PHP functions, we can create our own functions.  A function is a block of statements that can be used repeatedly in a program.  A function will not execute immediately when a page loads.  A function will be executed by a call to the function.
  • 43. 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 can start with a letter or underscore (not a number).  Tip: Give the function a name that reflects what the function does!
  • 44. Create a User Defined Function in PHP <!DOCTYPE html> <html> <body> <?php function writeMsg() { echo "Hello world!"; } writeMsg(); ?> </body> </html>
  • 45. PHP Function Arguments  Information can be passed to functions through arguments. An argument is just like a variable.  Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.  Example: <?php function familyName($fname) { echo "$fname Welcome.<br>"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?>
  • 46. PHP Function Arguments <!DOCTYPE html> <html> <body> <?php function familyName($fname) { echo "Welcome $fname.<br>"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?> </body> </html>
  • 47. PHP Functions - Returning values <!DOCTYPE html> <html> <body> <?php function sum($x, $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); ?> </body> </html>
  • 48. PHP 5 Form Handling: GET, POST Methods  When the user fills out the form and clicks the submit button, the form data is sent for processing to a PHP file  The form data is sent with the HTTP POST method.  The same result could also be achieved using the HTTP GET method.  Example: Continued…
  • 49. When to use GET?  Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.  GET may be used for sending non-sensitive data.  Note: GET should NEVER be used for sending passwords or other sensitive information!
  • 50. When to use POST?  Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.  Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.  However, because the variables are not displayed in the URL, it is not possible to bookmark the page.  Developers prefer POST for sending form data.
  • 51. GET vs. POST  Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)).  This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.  Both GET and POST are treated as $_GET and $_POST. These 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.  $_GET is an array of variables passed to the current script via the URL parameters.  $_POST is an array of variables passed to the current script via the HTTP POST method.
  • 52. PHP 5 Form Handling: GET, POST Methods <!DOCTYPE HTML> <html> <body> <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> </body> </html> <html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html> Welcome.php
  • 53. PHP 5 Form Handling: GET, POST Methods <!DOCTYPE HTML> <html> <body> <form action="welcome_get.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html> <html> <body> Welcome <?php echo $_GET["name"]; ?><br> Your email address is: <?php echo $_GET["email"]; ?> </body> </html> Welcome_get.php
  • 54. PHP Global Variables - Superglobals Several 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  $_ENV  $_COOKIE  $_SESSION
  • 55. PHP $GLOBALS  $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).  PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?>
  • 56. PHP $_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. <!DOCTYPE html> <html> <body> <?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME']; ?> </body> </html>
  • 57. PHP Error Handling  When creating scripts and web applications, error handling is an important part.  If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.  The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser.  We will show different error handling methods:  Simple "die()" statements  Custom errors and error triggers  Error reporting
  • 58. Basic Error Handling: Using the die() function  The example shows a simple script that opens a text file:  <?php $file=fopen("welcome.txt","r"); ?>  If the file does not exist you might get an error like this:  Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:webfoldertest.php on line 2  To prevent the user from getting an error message like the one above, we test whether the file exist before we try to access it. Continued…
  • 59. Basic Error Handling: Using the die() function <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>  Now if the file does not exist you get an error like this:  File not found <!DOCTYPE html> <html> <body> <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> </body> </html>
  • 60. Creating a Custom Error Handler  Creating a custom error handler is quite simple.  We simply create a special function that can be called when an error occurs in PHP.  This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line- number, and the error context):  Syntax error_function(error_level,error_message,error_file,error_line,error_context )
  • 61. Creating a Custom Error Handler Parameter Description error_level Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels error_message Required. Specifies the error message for the user-defined error error_file Optional. Specifies the filename in which the error occurred error_line Optional. Specifies the line number in which the error occurred error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred
  • 62. Error Report levels Value Constant Description 2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
  • 63. Set Error Handler  The default error handler for PHP is the built in error handler.  It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways.  set_error_handler("customError");
  • 64. Set Error Handler <!DOCTYPE html> <html> <head> <title>PHP Demo</title> </head> <body> <?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> </body> </html>
  • 65. Trigger an Error  In a script where users can input data it is useful to trigger errors when an illegal input occurs.  In PHP, this is done by the trigger_error() function.  Example  In this example an error occurs if the "test" variable is bigger than "1": <?php $test=2; if ($test>=1) { trigger_error("Value must be 1 or below"); } ?>
  • 66. Trigger an Error <!DOCTYPE html> <html> <head> <title>PHP Demo</title> </head> <body> <? php $test=2; if ($test>=1) { trigger_error("Value must be 1 or below"); } ?> </body> </html>