+ All Categories
Home > Education > PHP Presentation

PHP Presentation

Date post: 16-Sep-2014
Category:
View: 37 times
Download: 6 times
Share this document with a friend
Description:
This is Full Book in PPT of PHP
Popular Tags:
561
Author : Amit K. Lakhani Lecturer in Computer Engineering Department Tolani Foundation Gandhidham Polytechnic Adipur Faculty : Diploma Engineering Branch : Computer Engineering Subject Name: PHP & MySQL Subject Code : 360701
Transcript
Page 1: PHP Presentation

Author :

Amit K. LakhaniLecturer in Computer Engineering Department

Tolani Foundation Gandhidham PolytechnicAdipur

Faculty : Diploma EngineeringBranch : Computer EngineeringSubject Name: PHP & MySQLSubject Code : 360701

Page 2: PHP Presentation

Chapter - 1Introduction to

PHP

Page 3: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1.Introduction to PHPThis unit covers…

1.1 History of PHP, Apache web server, MySQL & Open source1.2 Relationship between Apache, MySQL and PHP (AMP module)1.3 PHP configurations in PHP1.4 Apache web server

Page 4: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1.1 History of PHP, Apache web server, MySQL &

Open source

Page 5: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

History of PHP• PHP is a general-purpose server-side scripting language originally designed for Web development to produce dynamic Web pages.• It is one of the first developed server-side scripting languages to be embedded into an HTML source document, rather than calling an external file to process data. • Ultimately, the code is interpreted by a Web server with a PHP processor module which generates the resulting Web page. It also has evolved to include a command-line interface capability and can be used in standalone graphical applications.

Page 6: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

History of PHP conti..• PHP can be deployed on most Web servers and also as a standalone shell on almost every operating system and platform free of charge.• PHP was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the formal reference to the PHP language. • PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) due to restrictions on the usage of the term PHP.• While PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext Preprocessor", a recursive acronym.

Page 7: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

History of MySQL• MySQL is the world's most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases. • It is named after developer Michael WideniusThe SQL phrase stands for Structured Query Language.• The open source database product that puts the "M" in LAMP, was created by MySQL AB, a company founded in 1995 in Sweden. In 2008, MySQL AB announced that it had agreed to be acquired by Sun Microsystems for approximately $1 billion.

Page 8: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

History of Apache web server

• The Apache Web Server Foundation was created in late February, 1994 by a team of eight core contributors, and three additional contributors. The first release was made in April, 1995.• The Apache Web (HTTP) Server is designed to provide static and dynamic web pages over the Internet. It is used by large enterprises, to students to home users for everything from mission critical applications to simple one page websites. Apache is the web server component of the popular LAMP (Linux, Apache, MySQL,Perl/Python / PHP) application stack.

Page 9: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

History of Apache web server conti..

• The web server is software that allows a computer to host web pages. The most popular Apache is a web server, an open source which runs on Windows, Linux and other operating systems.• The web server lets you write and test programs running from your local computer exactly the same way they will be seen on the internet.• Apache doesn’t serve up just HTML files it handles a wide range of files, from images and flash files to MP3 audio files, RSS feeds and so on.

Page 10: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Open source

• Refers to a program or software in which the source code (the form of the program when a programmer writes a program in a particular programming language) is available to the general public for use and/or modification from its original design free of charge.

• Open source code is typically created as a collaborative effort in which programmers improve upon the code and share the changes within the community.

Page 11: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Open source conti..

• The basics behind the Open Source Initiative is that when programmers can read, redistribute and modify the source code for a piece of software, the software evolves. Open source sprouted in the technological community as a response to proprietary software owned by corporations.

Page 12: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1.2 Relationship between Apache, MySQL and

PHP

Page 13: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Relationship Apache, MySQL and PHP

• AMP stands for Apache web server, MySQL database and PHP or Perl or Python language.• PHP is used to create web pages, MySQL is used to create database for the storage and Apache is used to run PHP pages.• The combination of these three allows us to create dynamic and interactive websites.• It can be used on cross platforms means we can install it on WINDOWS (WAMP) or on LINUX (LAMP).

Page 14: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1.3PHP configurations in

IIS

Page 15: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

PHP configuration in IISConfiguration of PHP on IIS includes following steps. This guide provides configuration about IIS 5.1 shipped with Window XP sp2.1- Download latest version of PHP from http://www.php.net/downloads.php. Note you should download installer version not the zip version. Installer version automatically performs all necessary configurations. If we use zip version, Environmental variables must be modified manually 2- Run the setup and choose installation directory for example C:\PHP3- On next screen choose your version of web server, here choose IIS ISAPI and click next.

Page 16: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

PHP configuration in IIS conti..4- On next screen in the extension portion choose extensions to be installed on local hard drive and click Install. You may add and remove extension later.

Page 17: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWSRun the installer file.

Page 18: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..In the license agreement click [I accept the agreement], then click next.

Page 19: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..Select the directory where you would like to install WAMP.

Page 20: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..Select the start menu folder where you would like to place WAMP’s shortcuts.

Page 21: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..In the additional tasks you may select if WAMP would be loaded on startup or no.

Page 22: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..This is the confirmation screen of the options you have selected. Click back to modify your install settings or click next to start the installation.

Page 23: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..Some time midway into the installation a window will pop-up asking for the directory where to save the document root folder. It is recommended that you leave it as it is and click ok to continue the installation.

Page 24: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..After the said pop-up another window will appear asking for you default browser. If you have no preference for browsers just hit Open. If not search for the .exe file of your preferred browser then click Open to continue the installation.

Page 25: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..Once the installation is finished, click finish.

Page 26: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Installing WAMP on WINDOWS conti..In your System Tray you should now see a “WAMP” icon.Click it, and select Put Online (Note: if it says Put Offline ignore this step and skip to the next one).

Page 27: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1.4 Apache Web server

Page 28: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver• Apache is generally recognized as the world's most popular Web server (HTTP server). Originally designed for Unix environments, the Apache Web server has been ported to Windows and other network operating systems.

• The name "Apache" derives from the word "patchy" that the Apache developers used to describe early versions of their software.

•The Apache Web server provides a full range of Web server features, including CGI, SSL, and virtual domains.

Page 29: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..• Apache also supports plug-in modules for extensibility. Apache is free software, distributed by the Apache Software Foundation that promotes various free and open source advanced Web technologies.Configuration Files• Apache uses a system of three text files for managing its configuration data. All three of these files (almost always) appear in Apache's ./conf directory and are designed to be edited by system administrators:

httpd.conf for general settings srm.conf for resource settings access.conf for security settings

Page 30: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..

• When Apache first starts, these files are processed in the order shown above. Originally, the initial installation of Apache included default entries within each of the three files. • In the most recent versions of Apache, however, the default installation has changed. Now httpd.conf is treated as the "master" configuration file and it contains all of the settings. Both srm.conf and access.conf still exist in the installation, but they contain no settings and are empty except for some comments.

Page 31: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..

• Like many UNIX-style programs, Apache will not re-read the .conf files after the Web server starts running. After making changes, an administrator must restart Apache for the new settings to take effect.

Inside Httpd.conf• Traditionaly httpd.conf contained general settings such as the ServerName and Port number. These entries appear as follows in the file:

ServerName localhostPort 80

Page 32: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..• The term "httpd" stands for HTTP Daemon. Recall that in a UNIX environment, the term daemon refers to a type of process designed to launch at system boot and continue running for very long periods of time. The name doesn't make much sense on a Windows platform, but the concept of a UNIX daemon can be compared to the concept of Windows services. • The Windows port of Apache allows for installation as a Windows service but does not require it. This file contains a number of other entries (technically called directives), but for most of these, modifications are optional.

Page 33: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..

• Probably the most useful of these entries is ServerAdmin – it allows the administrator to set the email address that will be displayed on error pages (such a "404 pages") in the client's browser, giving users a way to contact someone if a site problem occurs:

ServerAdmin [email protected] Access and Security Settings• It is recommended practice now for Apache administrators to manage their resource and security settings from httpd.conf. Administrators of older versions of Apache can simply cut their entries from srm.conf and access.conf and paste them into the master file.

Page 34: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Apache webserver conti..

• If an administrator wants to go one step further and delete the two empty files, they should also place the following entries in httpd.conf to prevent Apache from attempting to access them:

AccessConfig /dev/nullResourceConfig /dev/null Conclusion

• The family of .conf files supports most but not all of Apache's configuration options. Other important mechanisms for managing an Apache Web server include the .htaccess file, the mime.types file, and the family of log files. Look for discussion of these in a future article.

Page 35: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Summary

• History of PHP, Apache web server, MySQL & Open source• Relationship between Apache, MySQL and PHP (AMP module)• PHP configurations in PHP• Apache web server

Page 36: PHP Presentation

Chapter - 2

Basics of PHP

Page 37: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.Basics of PHPThis unit covers…

2.1 PHP Structure and syntax2.2 Creating the PHP pages2.3 Rules for PHP syntax2.4 Integrating HTML with PHP2.5 Constants, Variable: static and global variable2.6 Conditional structure and looping2.7 PHP operator2.8 Arrays foreach construct2.9 User defined function, argument function, variable function, return function, default argument, variable length argument

Page 38: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.1PHP structure and

syntax

Page 39: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

PHP structure and Syntax

PHP is a scripting language commonly used on web servers.

• Stands for “PHP: Hypertext Preprocessor”• Open source• Embedded code• Comparable with ASP• Multiple operating systems/web servers

Page 40: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

What can it do?

• Dynamic generation of web-page content• Database interaction• Processing of user supplied data• Email• File handling• Text processing• Network interaction• And more…

Page 41: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Fundamentals

• PHP is embedded within xhtml pages within the tags: <?php … ?>

• The short version of these tags can also be used: <? … ?>

• Each line of PHP is terminated, like MySQL, with a semi-colon.

Page 42: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.2Creating the PHP pages

Page 43: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.2 Creating the PHP pages

<html> <head> <title>PHP Test</title> </head> <body> <?php echo ‘<p>Hello World!</p>’; ?> </body> </html>

PHP statement

Page 44: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.3Rules for PHP syntax

Page 45: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Rules for PHP syntax•Just as with other programming languages, in PHP, you can create variables and process them in different in different ways.

• With PHP, variable names are preceded with a dollar sign, such as $amount. The variable name itself (after the $) can start with a letter or underscore, and then followed by any sequence of letters, digits, or underscores. (That’s like most languages – variables can have letters, digits, and underscores, but can’t start with a digit.) And technically, the dollar sign isn’t part of the variable name.

Page 46: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Rules for PHP syntax conti..• The semicolon signifies the end of a PHP statement and should never be forgotten. we would need to place a semicolon at the end of each statement.

• As with HTML, whitespace is ignored between PHP s tatements. This means it is OK to have one line of PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to indent your code and the PHP interpreter will ignore those spaces as well.

Page 47: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Literals..

• All strings must be enclosed in single of double quotes: ‘Hello’ or “Hello”.

• Numbers are not in enclosed in quotes: 1 or 45 or 34.564

• Booleans (true/flase) can be written directly as true or false.

Page 48: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Comments

// This is a comment# This is also a comment/* This is a commentthat is spread overmultiple lines */

Do not nest multi-line comments// recommended over #

Page 49: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Displaying Data• There are two language constructs available to display data: print() and echo().• They can be used with or without brackets.• Note that the data ‘displayed’ by PHP is actually parsed by your browser as HTML. View source to see actual output.

<?phpecho ‘Hello World!<br />’;echo(‘Hello World!<br />’);print ‘Hello World!<br />’;print(‘Hello World!<br />’);?>

Page 50: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Escaping Characters• Some characters are considered ‘special’

• Escape these with a backslash \

• Special characters will be flagged when they arise, for example a double or single quote belong in this group…

<?phpecho ‘Claire O\’Reilly ’;echo “said \”Hello\”.”; ?>

Page 51: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Variables: What are they?When we work in PHP, we often need a labelled place to store a value (be it a string, number, whatever) so we can use it in multiple places in our script.These labelled ‘places’ are called VARIABLES Variable naming Rules:• $ followed by variable name• Case sensitive

• $variable differs from $Variable• Stick to lower-case to be sure!

• Name must started with a letter or an underscore• Followed by any number of letters, numbers

and underscores

Page 52: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Variables: example

<?php$name = ‘Phil’;$age = 23;echo $name;echo ’ is ‘;echo $age;// Phil is 23 ?>

Page 53: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.4 Integrating HTML with

PHP

Page 54: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

integrating HTML with PHP

<html> <head> <title>PHP Test</title> </head> <body> <?php echo ‘<p>Hello World!</p>’; ?> </body> </html>

PHP statement

Page 55: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.5Constant variable:

constant and global variable

Page 56: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Constant variable• Constants (unchangeable variables) can also be defined.• Each constant is given a name (note no preceding dollar is applied here).• By convention, constant names are usually in UPPERCASE.

<?phpdefine(‘NAME’,‘Phil’);define(‘AGE’,23);echo NAME;echo ’ is ‘;echo AGE;// Phil is 23 ?>

Page 57: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.6Conditional

Structure and Looping

Page 58: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Control Structures

• if, elseif, else• while, do … while• for, foreach• switch• break, continue, return• require, include, require_once, include_once

Page 59: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

If statement

• To do something depending on a comparison, use an if statement.

if (comparison) {

expressions; // do if TRUE

}• NB: Notice the curly brackets – these are

important!

Page 60: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

If example

<?php

$a = 10;

$b = 13;

if ($a<$b)

{

echo ‘a is smaller than b’;

}

?>

Page 61: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Extending IF statements

• It is possible to add extra optional clauses to if statements..

if (comparison) {

expressions; // do if TRUE

} else {

expressions; // do otherwise

}

Page 62: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Extending If statements example

if (comparison1)

{

expressions;

}

elseif (comparison2)

{

expressions;

} else

{

expressions;

}

Page 63: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

An example..

$a = 10;$b = 13;if ($a<$b) {

echo ‘a is smaller than b’;} elseif ($a==$b) {

echo ‘a is equal to b’;} else {

echo ‘a is bigger than b’;}

Page 64: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

While loops

• Might want to do something repeatedly while a comparison is true..

while (comparison) {

expressions;}

Page 65: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

While loop example

• Lets count to 10! Displays 1,2,3,4,5,..,10:

$i = 1;while ($i <= 10) {

echo $i++; }

Page 66: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Do .. While

An alternative...

$i = 1;do {   echo $i++; } while ($i <= 10);

Page 67: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

For loop

Sometimes we want to loop around the same bit of code a number of times.. Use a for loop.

for (expr1; expr2; expr3) { statements; }

• expr1 evaluated/executed initially• expr2 evaluated at beginning of each

iteration (Continues if TRUE)• expr3 evaluated/executed at end of each

iteration

Page 68: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

For loop example

To count from 1 to 10:

for ($i=1; $i<=10; $i++) {

echo $i;}

initialiseContinue if true

Execute at end of loop

Page 69: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Foreach loop

A foreach loop is designed for arrays. Often you want to loop through each item in an array in turn..

$letters = array(‘a’,’b’,’c’);foreach ($letters as $value) {

echo $value; } // outputs a,b,c in turn

Page 70: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Foreach.. With keys

Sometimes we want to use the array ‘key’ value too:

$letters = array(‘a’,’b’,’c’);foreach ($letters as $key => $value) { echo “array $key to $value”; }

Page 71: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Switch statementswitch (expr) {

case (result1):statements;

break;case (result2):

statements;break;default:

statements;}

• expr is evaluated– Case corresponding

to result is executed– Otherwise default

case is executed• break

– Ensures next case isn’t executed

Page 72: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Switch Exampleswitch ($name) {

case ‘Rob’:echo ‘Your name is Rob’;

break;case ‘Fred’:

echo ‘You are called Fred’;break;default:

echo ‘Not sure what your name is’;}

Page 73: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

break, continue, return• break

• Ends execution of current for, foreach, do … while, while or switch structure

• Option: Number of nested structures to break out of

• continue• Skip rest of current loop• Option: Number of nested loops to skip

• return• Ends execution of current function/

statement / script

Page 74: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.7PHP operators

Page 75: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Expressions

• Using variables within expressions to do something is what PHP is all about.

<?php$name = ‘Rob’;echo $name;?>

Page 76: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Operators in PHP

• Arithmetic• Assignment• Bitwise• Comparison• Ternary• Incrementing

/decrementing• Logical• String

Page 77: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

String Operators

Use a dot to concatenate two strings:

e.g.$firstname = ‘Rob’;$surname = ‘Tuley’;// displays ‘Rob Tuley’ echo $firstname.’ ‘.$surname;

Page 78: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Arithmatic Operators

Example Name Result

$a + $b Addition Sum of $a and $b.

$a - $b Subtraction Difference of $a and $b.

$a * $b Multiplication Product of $a and $b.

$a / $b Division Quotient of $a and $b.

$a % $b Modulus Remainder of $a divided by $b.

Page 79: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Assignment Operators

Example Result

$a = $b Sets $b to the same value as $a.

$a += $b Equivalent to $a = $a + $b.

$a .= $b Equivalent to $a = $a.$b.

Page 80: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Combining Operators

Note that you can combine operators, for example use =, + and / in one expression:

$a = 4;$b = 2;$c = $a + $b + ($a/$b);// $c has value 4+2+(4/2) = 8

Brackets help group operators.

Page 81: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Comparison Operators

Example Name Result

$a == $b Equal TRUE if $a is equal to $b.

$a != $b Not equal TRUE if $a is not equal to $b.

$a <> $b Not equal TRUE if $a is not equal to $b.

$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to

TRUE if $a is less than or equal to $b.

$a >= $b Gtr than or equal to

TRUE if $a is greater than or equal to $b.

Page 82: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Comparisons operator example

• Comparison expressions return a value of TRUE (or ‘1’) or FALSE (or ‘0’). e.g.

$a = 10;$b = 13;// result is true (‘1’) echo $a < $b;

Page 83: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Incrementing/Decrementing

Example Name Effect

++$a Pre-increment

Increments $a by one, then returns $a.

$a++ Post-increment

Returns $a, then increments $a by one.

--$a Pre-decrement

Decrements $a by one, then returns $a.

$a-- Post-decrement

Returns $a, then decrements $a by one.

Page 84: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Logical Operators

Example Name Result$a and $b And TRUE if both $a and $b are TRUE.

$a or $b Or TRUE if either $a or $b is TRUE.

$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.

!$a Not TRUE if $a is not TRUE.

$a && $b And TRUE if both $a and $b are TRUE.

$a || $b Or TRUE if either $a or $b is TRUE.

Page 85: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Ternary Operators

A single ? is the ternary operator.

(expr) ? if_expr_true : if_expr_false;

A test expression evaluates to TRUE or FALSE. TRUE gives first result (before colon)FALSE gives second result (after colon)

Page 86: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Ternary Operators example

<?php$a = 10;$b = 13;echo $a<$b ? ‘a smaller’:‘b smaller’;// string ‘a smaller’ is echoed // to the browser..?>

Page 87: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.8Arrays

Page 88: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array

• So far, we have stored ONE piece of data in each variable.

• It is also possible to store multiple pieces of data in ONE variable by using an array.

• Each piece of data in an array has a key..

Page 89: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Working with Array

• Note that trying to echo an entire array will not display the data. To print an entire array to screen (for debug, for example) use the function print_r instead.

print_r($letters);

Page 90: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array example

Normal Variable, no key:$name = ‘Rob’;

Array Variable, multiple pieces with ‘keys’:$name[0] = ‘Rob’;$name[1] = ‘Si’;$name[2] = ‘Sarah’;…

The ‘key’

Page 91: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array key

• Array keys can be strings as well as numbers..

$surname[‘rob’] = ‘Tuley’;$surname[‘si’] = ‘Lewis’;

• Notice the way that the key is specified, in square brackets following the variable name.

Array key

Page 92: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Types of Array

• Indexed / Numeric array• Indexed array have keys automatically assigned,

starting from 0.• Values are stored and accessed in linear fashion

• Associative array • Use keys that are manually specified and they

use string as index.• A key is some string value• Stores element values in association with key

values rather than in linear indexed order.

Page 93: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Indexed / Numeric Array• This array can store numbers, sting and objects but

their index represented by numbers and starts from 0.

//first method to create array by array() function<?php

$varArray= array(1,2,3,4);?>

//second method to create array<?php

$varArray[0]= 1$varArray[1]= 2$varArray[2]= 3

?>

Page 94: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of Indexed / Numeric Array<?php//first method to create array$varArray= array(1,2,3,4,5);foreach($varArray as $val){

print_r($val);}//second method to create array$varArray[0]= 1$varArray[1]= 2$varArray[2]= 3foreach($varArray as $val)

print_r($val);?>

Output:

Page 95: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Associative Array• associative will have their index as string so that

you can establish strong association between key and value.

<?php$dept['comp'] = "32";$dept['it'] = "30";$dept['ec'] = "34";print_r($dept['it']);?>

Array key Array value

Page 96: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of Associative Array// first method to create array

<?php$dept['comp'] = "32";$dept['it'] = "30";$dept['ec'] = "34";print_r($dept['it']);?>// second method to create array

<?php$dept=array(“comp” => 32,

“it” => 30,“ec” => 34,

print_r($dept['it']);?>

Output:

Page 97: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Adding an element to Arrays

Page 98: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Adding an element to an Array

• Adding an element to indexed array using [ ] operator and array_push() function

• Adding an element to an associative array by specifying index

• Adding an element to to the beginning of an array using array_unshift() function.

Page 99: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Adding an element to an Array example• You can add automatically indexed element using [ ] operator

<?php$varArray=array();$varArray[]=1;$varArray[]=2;for($i=0;$i<=1;$i++){

echo $varArray[$i];}$varArray=array();array_push($varArray, 10,20);for($i=0;$i<=1;$i++){

echo $varArray[$i];}?>

Add an element to array

Output:

Page 100: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Adding an element to an Associative array

<?php$varArray=array();$varArray['one']=1;$varArray['two']=2;echo $varArray['one'];?>

Add an element to array

• You can specify the index when adding an element.

Output:

Page 101: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Adding an element using array_unshift()

<?phpvarArray=array('three');array_unshift($varArray, 'one');array_unshift($varArray, 'two');array_unshift($varArray, 'three');print_r("$varArray[0]");print_r("$varArray[1]");print_r("$varArray[2]");?>

Add an element to array

• You can add an element to the beginning of an array using array_unshift() function.

Output:

Page 102: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Removing an element from Arrays

Page 103: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Removing an element from array

• You can remove an element using unset() function

• You can remove the last element of an array using array_pop() function

• You can remove the first element of an array using array_shift() function

Page 104: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Removing an element from array conti..• You can remove an element using unset() function

<?php$varArray=array();$varArray[]=1;$varArray[]=2;for($i=0;$i<=1;$i++){

echo $varArray[$i];}unset($varArray[0]);for($i=0;$i<=1;$i++){

echo $varArray[$i];}?>

Unset the first elementOf an array

Output:

Page 105: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Removing an element from array conti..• You can remove last element using array_pop() function

<?php$varArray=array();$varArray[]=1;$varArray[]=2;for($i=0;$i<=1;$i++){

echo $varArray[$i];}$last=array_pop($varArray);for($i=0;$i<=1;$i++){

echo $varArray[$i];}?>

Remove last elementOf an array

Output:

Page 106: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Removing an element from array conti..• You can remove first element using array_shift() function

<?php$varArray=array();$varArray[]=1;$varArray[]=2;for($i=0;$i<=1;$i++){

echo $varArray[$i];}$first=array_shift($varArray);for($i=0;$i<=1;$i++){

echo $varArray[$i];}?>

Remove first elementOf an array

Output:

Page 107: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Counting and combining elements

of Arrays

Page 108: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Counting element of array• You can determine the sizeof an array using count() function

<?php$varArray=array(1,2,3,4,5);$varArray_1=array();

echo "The number of elements in first array=".count($varArray);

echo "The number of elements in second array=".count($varArray_1);?>

Counts the no of elements in array

Output:

Page 109: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Combining multiple array• You can combine multiple array using array_merge() function

<?php$varArray=array(1,2,3,4,5);$varArray_1=array(6,7,8,9);

$arr_merge = array_merge($varArray, $varArray_1);

print_r($arr_merge);?> Combines

Elements of arrayOutput:

Page 110: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching Array

Page 111: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching arrays

• You can see an element with a certain key exists using array_key_exists() function

• You can see an element with a certain key exists using isset() function

• You can check if a specific element exists in an array using in_array() function.

Page 112: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching arrays conti..

• You can see an element with a certain key exists using array_key_exists() function

<?php$varArray[0]=1;$varArray[1]=2;if(array_key_exists(1,$varArray)){

print_r($varArray[1]);}?>

key Array name

Output:

Page 113: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching arrays conti..

• You can see an element with a certain key exists using isset() function

<?php$varArray['one']=1;$varArray['two']=2;if(isset($varArray['one'])){

print_r($varArray['one']);}?>

Array name

Output:

Page 114: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching arrays conti..

• You can check if a specific element exists in an array using in_array() function.

<?phpecho"<font size=50>";$varArray['0']=1;$varArray['1']=2;if(in_array(1,$varArray)){

print_r($varArray[1]);}?>

key Array name

Output:

Page 115: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting Array

Page 116: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays

• PHP has a rich collection of sorting functions that allow you to sort by values and keys.

• Variants on most of these functions facilitate sorting in forward or reverse order and provide you with the option of preserving or resetting the associations between array keys and values.

• All of PHP’s array sorting functions work on arrays in place and return TRUE to indicates success or FALSE in the event of failure.

Page 117: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Sorting an Array by Its Values using sort()

• Sorting an Array by Its Values using asort()

• Sorting an Array by Its Keys using ksort()

• Reversing an Array Using arsort()

• Reversing an Array Using krsort()

• Reversing an Array Using array_reverse()

Page 118: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Sorting an Array by Its Values using sort():

To order an array’s elements using their values, use the sort() function. This function takes as its arguments the array to be sorted and an optional sort flag, and, like PHP’s other sorting functions, this one sorts the array in place.

<?php$varArray=array(100,25,1,45,15);print_r($varArray);sort($varArray);print_r($varArray);?>

Sort an array

Page 119: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Sorting an Array by Its Values using asort():

Because sort() resets all the indexes, you have lost the original keys. To get around this issue, you can use the asort() function instead. This works in the same way as sort() except in one respect: it preserves the array’s original key/value associations.

<?php$varArray['one']= "second";$varArray['two']= "first";$varArray['three']= "third";asort($varArray);print_r($varArray);?>

Sort an array

Page 120: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Sorting an Array by Its Keys using ksort():

Particularly with regard to associative arrays, it is just as important to be able to sort arrays by their keys as it is by their values. The ksort() function accomplishes this while maintaining the relationship between keys and values.

<?php$varArray['one']= "second";$varArray['two']= "first";$varArray['three']= "third";ksort($varArray);print_r($varArray);?>

Sort an arrayBy its keys

Page 121: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Reversing an Array Using arsort():

To sort an associative array by value in reverse order, use arsort(). Like asort(), this function preserves the array’s keys.

<?php$varArray_1['one']= "second";$varArray_1['two']= "first";$varArray_1['three']= "third";arsort($varArray_1);print_r($varArray_1);?>

Sort an arrayIn reverse order

Page 122: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Reversing an Array Using krsort():The krsort() function sorts an array by key in reverse order.

<?php$varArray_1['one']= "second";$varArray_1['two']= "first";$varArray_1['three']= "third";krsort($varArray_1);print_r($varArray_1);?>

Sort an arrayIn reverse order

Page 123: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays conti.. • Reversing an Array Using array_reverse()

The array_reverse() function does just what you would expect; it reverses the order in which the elements of an array are listed.

<?php$varArray_1['one']= "second";$varArray_1['two']= "first";$varArray_1['three']= "third";array_reverse($varArray_1);print_r($varArray_1);?> Sort an array

In reverse order

Page 124: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Sorting arrays example

Page 125: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Looping over arrays• The easiest way to loop over is foreach()• Each element in foreach() is a copy. i.e modifying the elements has no effect on the original array.

<?php$varArray= array(1,2,3,4,5);print_r($varArray);foreach($varArray as $val){

print_r("$val");echo"<br>";

}?>

Page 126: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array operators

Example Name Result

$a + $b Union Union of $a and $b.

$a==$b Equality TRUE if $a and $b have the same key/value pairs

$a===$b Identity TRUE if $a and $b have the same key/value pairs in the same order of the same type.

$a!=$b Inequality TRUE if $a is not equal to $b

$a<>$b Inequality TRUE if $a is not equal to $b

$a!==$b Non-identity TRUE if $a is not identical to $b

Page 127: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

2.9User defined function, argument

function, variable function, return function, default

argument, variable length argument

Page 128: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Functions

• User defined functions

• Argument functions

• Variable functions

• Return functions

• Default argument

• Variable length argument

Page 129: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

User defined functions

• Functions are defined using the keyword function by the function name • Functions may have 0 or more arguments• Code body appears between opening and closing paranthesis.• Functions name begins with a letter or underscore, followed by any letter, numbers or underscores.• Function is called using the function name.• Function do not need to be declared• Recursion is supported

Page 130: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of User defined functions

<?phpfunction first(){

echo "This is first function";}function sec(){

print "this is second function";}first();sec();?>

Output:

Page 131: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Functions argument• variables can be passed either by value of by reference

<?phpfunction addvalues ($value1 = 0, $value2 = 0, $value3 = 0){

$total = $value1 + $value2 + $value3;return $total;

}echo addvalues (1) . "<br />"; echo addvalues () . "<br />"; echo addvalues (1,2,3); ?>

Function arguments

Output:

Page 132: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Variable length argument• In addition to support default values for function argument PHP supports variable length argument with function such as func_get_args()

• Regardless of what the function definition dictates you can retrieve every single value passed to function using func_get_args()

• This functions returns an array where each element is corresponds to a single argument.

• This is useful when you want function to accept any number of arguments

Page 133: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of Variable length argument<?php

function display($name){

foreach(func_get_args() as $arg){echo $arg."<br>";}

}

display("computer","IT","EC");?>

Output:

Page 134: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Returning values

• You can return a value from an array using the return keyword.

• If there is no return executed then NULL is the default value

• You can return only a single value from a function by returning a more complex value such as an array or an object which encapsulate multiple values and using by reference arguments and update those value in your function.

Page 135: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of Returning values<?phpfunction addandsubtract ($firstvalue, $secondvalue){$firstreturnvalue = ($firstvalue + $secondvalue);$secondreturnvalue = ($firstvalue - $secondvalue);$myarray = array ();$myarray[0] = $firstreturnvalue;$myarray[1] = $secondreturnvalue;return $myarray;}$myarray = array ();$myarray = addandsubtract (10, 3);echo $myarray[0] . "<br />";echo $myarray[1]; ?>

Page 136: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Object oriented programming in PHP

Page 137: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Object oriented concepts• Class: User defined data type which includes local function as well as local data. • Object: An individual instance of the data structure defined by a class. They are also known as instance.• Member variable: variables defined inside the class. This data will be invisible to the outside of the class and can be accessed by the member functions.• Member Function: functions defined in the class and are used to access object data.• Inheritance: When a class is defined by inheriting existing functions of a parent class then it is called inheritance.

Page 138: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Object oriented concepts conti…• Parent class: A class that is inherited by other class. It is also known as base class or super class.• Child class: A class that inherits the property of other class(parent). It is also known as subclass or derived class.• Polymorphism: same function can be used for different purposes.• Overloading: A type of polymorphism in which some or all of operators have different implementation depending on the type of arguments.• Data abstraction: Data details are hidden.

Page 139: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Object oriented concepts conti…• Encapsulation: where data and member functions can be encapsulated together to form an object.• Constructor: special type of function which will be called automatically whenever there is an object formation from a class.• Destructor: special type of function which will be called automatically whenever there is an object deleted or goes out of scope.

Page 140: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

What is a class?Conceptually, a class represents an object, with associated methods and variables<?phpclass sample{ var $val; function getvalue() { $this->val=10; } function showvalue() { echo "you have entered”.$this->val; }};

$obj = new sample();$obj->getvalue();$obj->showvalue();?>

Output:

Page 141: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Constructor function • Constructor functions are special types of function which are called automatically whenever an object is created.

• PHP provides a special functions called __construct() to define a constructor, you can pass any number of arguments.

• Remember.. if the constructor requires arguments, they must be passed when it is instantiated!

Page 142: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Constructor function example <?phpclass sample{var $ID;var $name;function __construct($ID, $name){$this->ID= $ID;$this->name = $name;}function showvalue(){echo "ID:".$this->ID."<br>";echo "Name:".$this->name."<br>“;}};

$obj=new sample(100, "computer");$obj->showvalue();?>

Output:

Page 143: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Destructor function • Like constructor function you can define a destructor function using __destruct(). • You can release all the resources within destructor<?phpclass sample{function __construct(){echo "The constructor is called ";}function __destruct(){echo "The destructor is called ";}};

$obj=new sample();?>

Output:

Page 144: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Inheritance • The real power of using classes is the property of

inheritance – creating a hierarchy of interlinked classes.

Department

Computer Mechanical

parent

children

Page 145: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Inheritance conti….. • The child classes ‘inherit’ all the methods and variables of the parent class, and can add extra ones of their own.

• The effect of inheritance is that the child class has the following characteristics:

• Have all the member variable declarations of the parent class.

• Have all the same member functions as the parent, which will work the same way as those functions do in the parent.

Page 146: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Inheritance exampleclass pclass{ var $p_value; function p_getval() { $this->p_value = "parent"; } function p_showval() { echo "This is $this->p_value class"; }}

class cclass extends pclass{ var $c_val; function c_getval() { $this->c_val="child"; } function c_showval() { echo "This is $this->c_val class"; }}

$cobj= new cclass();$cobj->p_getval();$cobj->p_showval();$cobj->c_getval();$cobj->c_showval();?>

Parent classchild class

Object creation

Page 147: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Access specifier• Public member:

• By default properties and methods are public.• They may be accessed from outside of the class.• They may be accessed from within the class.• They may be accessed from within the class that

implements it in inheritance.

class sample{ var $count;}

Page 148: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Access specifier conti…• Private member:

• By designing a member private, you limit the accessibility to the class in which it is declared.

• The private member can’t be referred to from classes that inherit the class in which it is declared and can’t be accessed from outside of the class.

• A class member can be made private by using private keyword in front of the member.

class sample{

private $count;}

Page 149: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Access specifier conti…• Protected member:

• A protected property or method is accessible in the class in which it is declared, as well as in classes that extends that class.

• Protected members are not available outside of those two classes.

• A class member can be made protected using protected keyword in front of the member.

class sample{

protected $count;}

Page 150: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Interface

Page 151: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Interface concept• You can think of an interface as a template that tells you what methods a class should expose but leaves the details up to you.

• Interfaces are useful in that they can help you plan your classes without immediately getting bogged down in the details.

• You can also use them to distill the essential functionality from existing classes when it comes time to update and extend an application.

Page 152: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Interface concept• To declare an interface, simply use the interface keyword, followed by the name of the interface.

• Within the body of the interface, list declarations (delimited, as with classes, by braces, {...}) for any methods to be defined by classes that implement the Interface.

Page 153: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Interface example

<?php interface show{

function p_showval();}class pclass implements show{var $p_value; function p_getval(){ $this->p_value = "parent"; }

function p_showval() { echo "This is” $this->p_value ; }}$cobj= new pclass();$cobj->p_getval();$cobj->p_showval();?>

Output:

Page 154: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Constants• A constant is a variable which holds the value and the value does not change.•To declare a constant in a class, all you have to do is precede an identifier with the const keyword.• A class constant is always public and static, and for this reason you cannot use the keywords public, private, protected, or static when declaring one.

class sample{

const count;-----------------

}

Page 155: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Abstract classes

• An abstract class is one that can’t be instantiated only inherited.

• An abstract class is declared using abstract keyword.

• When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child and these methods must be defined with the same visibility.

Page 156: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Final keyword• PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final.• If the class itself is being defined final then it can’t be extended.

class sample{

final public getval(){

-----------------

}}

Page 157: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Summary• PHP Structure and syntax• Creating the PHP pages• Rules for PHP syntax• Integrating HTML with PHP• Constants, Variable: static and global variable• Conditional structure and looping• PHP operator• Arrays foreach construct• User defined function, argument function, variable function, return function, default argument, variable length argument

Page 158: PHP Presentation

Chapter - 3Working with

functions

Page 159: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Working with functions

PHP offers several built in functions for day to day uses in coding

3.1 Variable functions

3.2 String functions

3.3 Math functions

3.4 Date functions

3.5 Array functions

3.6 File functions

Page 160: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.1Variable functions

Page 161: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Variable functions• Gettype(): get the type of variable

• Settype(): set the type of variable

• Isset(): determine if the variable is set and not NULL

• Unset(): unset a given variable

• Strval(): get string value of variable

• Floatval(): get float value of variable

• Intval(): get the integer value of variable

• Print_r(): prints human readable information about a variable

Page 162: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Gettype() function• get the type of variable

• Syntax: string gettype($var)

• Returns the type of the variable

• Example:

<?php$var=21;echo gettype($var);?>

Output:

Page 163: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

settype() function• determine if a variable is set and is not NULL

•Syntax: bool settype($var)

• Returns TRUE on success otherwise false

• Example:

<?php$var=21;settype($var, "string");echo gettype($var);?>

Output:

Page 164: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

isset() function• set the type of variable• Syntax: bool isset($var, “type”)• Returns TRUE on success otherwise false

<?php$var=NULL;if (isset($var)=="TRUE"){echo "var is set";}else{echo "var is not set";}echo gettype($var);?>

Output:

Page 165: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

unset() function• unset a given variable

• Syntax: void unset($var)

• Example:

<?php$var="comp";echo "before unset<br>" .$var;echo gettype($var);unset($var);echo "after unset<br>".$var;echo gettype($var);?>

Page 166: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

•Get string value of a variable

•Syntax: strval ( mixed $var )

Example:

strval() function

<?php$var=25;echo strval($var);?>

Output:

Page 167: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

•Get float value of a variable

•Syntax: floatval ( mixed $var )

Example:

floatval() function

<?php$var=25;echo floatval($var);?>

Output:

Page 168: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?phpecho intval(42); echo "<br>";echo intval(4.2);?>

•Get integer value of a variable

•Syntax: intval ( mixed $var , [int base =10])

Example:

intval() function

Output:

Page 169: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$var=array(1,2,3,4,5);echo print_r($var);?>

•Prints human readable information about variable

•Syntax: print_r ($var)

•Example:

print_r() function

Output:

Page 170: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$var=1;$var2=40.50;echo var_dump($var);echo"<br>";echo var_dump($var2);?>

•Displays structured information (type and vale) about variable.

•Syntax: var_dump ($var)

Example:

Var_dump() function

Output:

Page 171: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.2String functions

Page 172: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

String functions• chr()- returns a one character string containing the character specified by ASCII value.

• ord()- returns the ASCII value of the first character of string.

• strtolower()- returns string with characters converted to lowercase

• strtoupper()-returns string with characters converted to uppercase

• strlen() -returns the length of the string

• ltrim()-strip whitespace from the beginning of a string

• rtrim()-strip whitespace from the end of a string

Page 173: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

String functions conti…• trim()-strip whitespace from the beginning and end of a string

• substr() -returns part of a string

• strcmp()-compares two inputs and returns an integer.

• strcasecmp()-compares two inputs and returns an integer.

• strncasecmp()-case sensitive string comparison for first n characters

• strpos() -find position of first occurrence of a string

• strrpos() -find position of last occurrence of a string

Page 174: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• strstr() -find first occurrence of a string and is case sensitive •stristr() - find first occurrence of a string inside another string and is case sensitive

• str_replace() -replace all occurrences of the search string with the replacement string.

• strrev() -reverse a string

• echo() -output one or more string

• print() -output a string

String functions conti…

Page 175: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

chr() function• returns one character string by ASCII value

•Syntax: string chr($var)

• Example:

<?phpecho "The character value of of 52 is: ".chr(52);?> Output:

Page 176: PHP Presentation

ord() function

Developed By: Amit Lakhani, TFGP Adipur

<?phpecho ord("computer");?>

• returns ASCII value of the first character of string

•Syntax: int ord($string)

• Example:

ord() function

Output:

Page 177: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strtolower() function

<?phpecho "The output of string lower function:<br>";echo strtolower("Computer DEPT.");?>

• returns string with characters converted to lowercase

•Syntax: string strtolower($str)

• Example:

Output:

Page 178: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strtoupper() function

<?phpecho "The output of string upper function:<br>";echo strtoupper("Computer DEPT.");?>

• returns string with characters converted to uppercase

•Syntax: string strtoupper($str)

• Example:

Output:

Page 179: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strlen() function

<?phpecho "The output of string length function:<br>";echo strlen("Computer");?>

• returns the length of the string

•Syntax: int strlen($str)

• Example:

Output:

Page 180: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

ltrim() function

<?phpecho "The output of ltrim function:<br>";$str = " Computer department";echo "Without ltrim: " . $str;echo "The length is:". strlen($str);echo "With ltrim: " . $str;echo "The length is:". strlen(ltrim($str));?>

• strip whitespace from the beginning of a string•Syntax: ltrim($str)• Example:

Page 181: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

rtrim() function

<?phpecho "The output of rtrim function:<br>";$str = "Computer department ";echo "Without rtrim: " . $str;echo "The length of the string is:". strlen($str);echo "With rtrim: " . $str;echo "The length of the string is:". Strlen(rtrim($str));?>

• strip whitespace from the end of a string

• Syntax: rtrim($str)

Page 182: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

trim() function

<?phpecho "The output of trim function:<br>";$str = “ Computer department ";echo "Without trim: " . $str;echo "The length of the string is:". strlen($str);echo "With trim: " . $str;echo "The length of the string is:". Strlen(trim($str));?>

• strip whitespace from the beginning and end of a string

• Syntax: string trim($str)

Page 183: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

substr() function

<?phpecho "The output of substring function:<br>";echo substr("Computer department!",3);echo substr("Computer department!",3,5);?>

• returns part of a string

• Syntax: string substr($str, int $start, [int $length])

• Example:

Output:

Page 184: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strcmp() function

<?phpecho "The output of string compare function:<br>";echo strcmp("Computer","Computer");?>

• compares two inputs and returns an integer.

• Syntax: int strcmp(string $str_1, string $str_2)

• Return values: returns < 0, if str_1 < str_2 returns > 0, if str_1 > str_2 returns 0, if str_1 = str_2

•Example:

Page 185: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strcasecmp() function

<?phpecho "The output of string compare function:<br>";echo strcasecmp("Computer","COMPUTER");?>

• compares two inputs and returns an integer.

• Syntax: int strcasecmp(string $str_1, string $str_2)

• Return values: returns < 0, if str_1 < str_2 returns > 0, if str_1 > str_2 returns 0, if str_1 = str_2

•Example:

Page 186: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strncasecmp() function

<?phpecho "The output of string compare function:<br>";echo strncasecmp("Computer","COMPUTER“, 3);?>

• case sensitive string comparison for first n characters

• Syntax: int strncasecmp(string $str_1, string $str_2, int len)

• Return values: returns < 0, if str_1 < str_2 returns > 0, if str_1 > str_2 returns 0, if str_1 = str_2

•Example:

Page 187: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strpos() function

<?phpecho "The output of string position function:<br>";echo strpos("Computer","m“, 2);?>

• find position of first occurrence of a string

• Syntax: int strpos(string $str, $needle, [ int $offset])

•Example:

Output:

Page 188: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strrpos() function

<?phpecho "The output of string position function:<br>";echo strrpos("Computer","m“, 2);?>

• find position of last occurrence of a string

• Syntax: int strrpos(string $str, $needle, [ int $offset])

•Example:

Output:The output of string position function:2

Page 189: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strstr() function

<?phpecho "The output of strstr() function:<br>";echo strstr("Computer","m“);?>

• find first occurrence of a string and is case sensitive

• Syntax: strstr($str,search)

•Example:

Output:

Page 190: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

stristr() function

<?phpecho "The output of stristr() function:<br>";echo stristr("Computer","m“);?>

• find first occurrence of a string inside another string and is case sensitive

• Syntax: stristr($str,search)

•Example:

Page 191: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

str_replace() function

<?phpecho "The output of string replace function with case sensitive: <br>";echo str_replace("department","engg.","computer department", $i);echo $i;?>

• replace all occurrences of the search string with the replacement string.

• Syntax: str_replace( find, replace, string, count )

•Example:

Page 192: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

strrev() function

<?phpecho "The output of strrev() function: <br>";echo strrev("computer department”);?>

• reverse a string

• Syntax: strrev( $string)

•Example:

Output:

Page 193: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

echo() function

<?phpecho "The output of echo function<br>";$i=1;echo $i;?>

• output one or more string

• Syntax: echo( $string)

•Example:

Page 194: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

print() function

<?phpprint (“The output of print function<br>“);$i=1;print $i;?>

• output a string

• Syntax: print( $string)

•Example:

Page 195: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.3Math functions

Page 196: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Maths function• abs()-returns absolute value of a number

• ceil() -returns the value of a number rounded UPWARDS to the nearest integer.

• floor()-returns the next lowest integer value by rounding down value.

• round() -returns the rounded value to specified precision.

• fmod() -returns the floating point remainder of dividing the dividend by the divisor.

•min() -returns smallest value

Page 197: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Maths function conti..

• max() -returns largest value

• pow() -returns base raised to the power of exp.

• sqrt() -returns the square root of the given number

• rand() -returns random value between min and max

Page 198: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

abs() function

<?phpecho "The output of abs() function<br>";echo(abs(6.99) . "<br />");echo(abs(-3) . "<br />");echo(abs(3));?>

• returns absolute value of a number

•Syntax: abs(num)

• Example:

Page 199: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

ceil() function

<?phpecho "The output of ceil() function<br>";echo(ceil(0.60) . "<br />");echo(ceil(0.40) . "<br />");echo(ceil(5) . "<br />");echo(ceil(5.1) . "<br />");?>

• returns the value of a number rounded UPWARDS to the nearest integer.• Syntax: float ceil(num)

• Example:

Page 200: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

floor() function

<?phpecho "The output of floor() function<br>";echo(floor(0.60) . "<br />");echo(floor(0.40) . "<br />");echo(floor(5.1) . "<br />");echo(floor(-5.1) . "<br />");?>

• returns the next lowest integer value by rounding down value.• Syntax: float floor(num)

• Example:

Page 201: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

round() function

<?phpecho "The output of round() function<br>";echo(round(0.60) . "<br />");echo(round(10.28765,2) . "<br />");echo(round(-4.40) . "<br />");echo(round(-4.60)); ?>

• returns the rounded value to specified precision.

• Syntax: float round(num)

• Example:

Page 202: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fmod() function

<?phpecho "The output of fmod() function to display remainder(modulo)<br>";$r = fmod(5,2);echo $r;?>

• returns the floating point remainder of dividing the dividend by the divisor.

• Syntax: float fmod($x,$y)

• Example:

Page 203: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

min() function

<?phpecho "The output of min() function <br>";$r = min(5,2);echo $r;?>

• returns smallest value

• Syntax: min($val1, $val2,….)

• Example:

Page 204: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

max() function

<?phpecho "The output of max() function <br>";echo(max(5,7) . "<br />");echo(max(-3,5) . "<br />");?>

• returns largest value

• Syntax: max($val1, $val2,….)

• Example:

Page 205: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

pow() function

<?phpecho "The output of pow() function <br>";echo pow(4,2) . "<br />";echo pow(6,2) . "<br />";?>

• returns base raised to the power of exp.

• Syntax: pow($base, $exp)

• Example:

Page 206: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

sqrt() function

<?phpecho "The output of sqrt() function <br>";echo(sqrt(1) . "<br />");echo(sqrt(9) . "<br />");?>

• returns the square root of the given number

• Syntax: float sqrt($arg)

• Example:

Page 207: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

rand() function

<?phpecho "The output of rand() function <br>";echo(rand() . "<br />");echo(rand(10,100));?>

• returns random value between min and max

• Syntax: int rand(void) int rand($min, $max)

• Example:

Page 208: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.4Date functions

Page 209: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function• Date() – format a local date/time

• Getdate() – get date time information

• Setdate() – sets the date

• Checkdate() – validates a date

• Time() – return current UNIX timestamp

• Mktime() – get the UNOX timestamp for a date

Page 210: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function

<?phpecho "The output of date() function”;echo date("d");echo date("D");echo date("j");?>

• returns a local time and date

•Syntax: string date($format, [int $timestap])

• Example:

Page 211: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function formatsRequired. Specifies how to return the result:

d - The day of the month (from 01 to 31) D - A textual representation of a day (three letters) j - The day of the month without leading zeros (1 to 31) l (lowercase 'L') - A full textual representation of a day N - The ISO-8601 numeric representation of a day (1 for Monday through 7 for Sunday) S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j) w - A numeric representation of the day (0 for Sunday through 6 for Saturday) z - The day of the year (from 0 through 365) W - The ISO-8601 week number of year (weeks starting on Monday)

Page 212: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function formats

Required. Specifies how to return the result:

F - A full textual representation of a month (January through December) m - A numeric representation of a month (from 01 to 12) M - A short textual representation of a month (three letters) n - A numeric representation of a month, without leading zeros (1 to 12) t - The number of days in the given month L - Whether it's a leap year (1 if it is a leap year, 0 otherwise) o - The ISO-8601 year number Y - A four digit representation of a year y - A two digit representation of a year

Page 213: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function formatsRequired. Specifies how to return the result:

a - Lowercase am or pm A - Uppercase AM or PM B - Swatch Internet time (000 to 999) g - 12-hour format of an hour (1 to 12) G - 24-hour format of an hour (0 to 23) h - 12-hour format of an hour (01 to 12) H - 24-hour format of an hour (00 to 23) i - Minutes with leading zeros (00 to 59) s - Seconds, with leading zeros (00 to 59) e - The timezone identifier (Examples: UTC, Atlantic/Azores) I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise) O - Difference to Greenwich time (GMT) in hours (Example: +0100)

Page 214: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

date() function formats

Required. Specifies how to return the result: T - Timezone setting of the PHP machine (Examples: EST, MDT) Z - Timezone offset in seconds. The offset west of UTC is negative, and the offset east of UTC is positive (-43200 to 43200) c - The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00) r - The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200) U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

Page 215: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

getdate() function• returns an array containing the date information of the timestap.

• Syntax: array getdate([int $timestap])

• Example:<?phpecho "The output of getdate() function<br>";print_r(getdate());?>

Page 216: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

setdate() function• Resets the current date of the datetime object to a different date.• Syntax: DateTime::setDate(int $y, int $m, int $y)

• Example:

<?phpecho "The output of setdate() function<br>";$d=new DateTime();$d->setDate(2011,4,2);echo $d->format('d-m-y');?>

Page 217: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

checkdate() function• Checks the validity of the date formed by the argument

• Syntax: bool checkdate(int $m, int $d, int $y)

• Returns TRUE if the given date is valid

• Example:

<?phpecho "The output of checkdate() function<br>";print_r(checkdate(11,30,2000));?>

Page 218: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

time() function• Returns the current UNIX timestamp

• Syntax: int time (void)

• Returns the current time measured in number of seconds ( Jan 1 1970 00:00:00 GMT)

• Example:

<?phpecho "The output of time() function<br>";echo time();?>

Page 219: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

mktime() function• Returns the UNIX timestamp corresponding to the arguments given.

• Syntax: int mktime($hrs, $mins, $sec, $mnt, $day, $yr)

•Example:

<?phpecho "The output of mktime() function<br>";echo mktime();echo(date("M-d-Y",mktime(0,0,0,12,36,2001)));echo(date("M-d-Y",mktime(0,0,0,14,1,2001)));?>

Page 220: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.5Array functions

Page 221: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array functionscount() -Counts all elements in an array, or properties in an object

array_count_values()-Returns an array of values from input as keys and their count as value.

list() -Assigns variables to values

In_array()-checks if a value exists in an array

current() -Return the current element in an array

next()-Advance the internal array pointer of an array

Page 222: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array functions conti..prev()-Rewind the internal pointer of an array

end()-Set the internal pointer of an array to its last element

each()-Returns the current key and value pair from an array and advances the array cursorsort()-Sorts an array

Array_merge()-Merges the elements of one or more array together so that the values of one or more are appended to the end of the previous array.

Page 223: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array functions conti..Array_reverse()-Returns the array with the order of the elements reversed.

Array_sum()- Returns the sum of values in an array

Page 224: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

count() function• Counts all elements in an array, or properties in an object

• Syntax: count($var)

• Example:

<?php$varArray=array(1,2,3,4,5);echo "The number of elements in first array=".count($varArray);?>Output:

Page 225: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array_count_values() function• Returns an array of values from input as keys and their count as value.

• Syntax: array array_count_values($var)

• Example:<?phpecho "The output of array_count_values() function<br>";$arr=array(1,2,3,4,5);print_r(array_count_values($arr));?>Output:

Page 226: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

list() function• Assigns variables to values

• Syntax: list($var1, $var2,…..)

Example:

<?phpecho "The output of list() function<br>";$arr=array(1,2,3);list($a,$b,$c)=$arr;echo “The list of values are:<br> $a <br> $b <br> $c ";?>

Page 227: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

In_array() function• checks if a value exists in an array

• Syntax: in_array($key, $array)

• Example:<?php$varArray=array(1,2,3);if(in_array(1,$varArray)){

print_r($varArray[1]);}?>

Page 228: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

current() function• Return the current element in an array

• Syntax: mixed current($array)

• Example:<?php$arr=array(1,2,3);echo "The current element is ". current($arr);?>

Output:

Page 229: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

next() function• Advance the internal array pointer of an array

• Syntax: mixed next($array)

• Example:<?php$arr=array(1,2,3);echo "The current element is ". current($arr);echo "<br>The next element is ". next($arr);?>Output:

Page 230: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

prev() function• Rewind the internal pointer of an array

• Syntax: mixed prev($array)

• Example:<?php$arr=array(1,2,3);echo "The current element is ". current($arr);echo "<br>The next element is ". next($arr);echo "<br>The next element is ". prev($arr);?> Output:

Page 231: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

end() function• Set the internal pointer of an array to its last element

• Syntax: mixed end($array)

• Example:

<?php$arr=array(1,2,3);echo "The last element is ". end($arr);?>Output:

Page 232: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

each() function• Returns the current key and value pair from an array and advances the array cursor

• Syntax: array each($array)

• Example:<?php$arr=array(1,2,3);$ele=each($arr);echo "The element is ";print_r($ele);?>

Page 233: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

sort() function• Sorts an array

• Syntax: bool sort($array)

• Example:

<?php$arr=array(1,2,3);sort($arr);print_r($arr);?>

Output:

Page 234: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array_merge() function• Merges the elements of one or more array together so so that the values of one or more are appended to the end of the previous array.

• Syntax: array array_merge($array1, $array2, …..)

• Example:<?php$arr=array(1,2,3);$arr_1=array(4,5,6);$arr_2=array_merge($arr, $arr_1);print_r($arr_2);?>

Page 235: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array_reverse() function• Returns the array with the order of the elements reversed.

• Syntax: array array_reverse($array)

• Example:<?php$arr=array(1,2,3);$arr_2=array_reverse($arr);print_r($arr_2);?>

Output:

Page 236: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Array_sum() function• Returns the sum of values in an array

• Syntax: number array_sum($array)

• Example:

<?php$arr=array(1,2,3);$arr_2=array_sum($arr);print_r($arr_2);?>

Output:

Page 237: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

3.6File functions

Page 238: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

File functions

fopen()- opens a file or URL

fread()- it reads from an open file

fwrite()- Writes the contents of string to the file stream

fclose()- closes an open file

Page 239: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fopen() function

• Opens a file

• Syntax: fopen(filename, mode)

• Example:

<?php$file = fopen("test.txt","w");echo fwrite($file,"computer department");fclose($file);?>

File name File mode

Page 240: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fopen() file modes

‘r’ Open for reading only. Start at beginning of file.

‘r+’ Open for reading and writing. Start at beginning of file.

‘w’ Open for writing only. Remove all previous content, if file doesn’t exist, create it.

‘w+’ Open for reading and writing. If file doesn’t exist, attempt to create it.

‘a’ Open writing, but start at END of current content.

Page 241: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fopen() file modes

‘a+’ Open for reading and writing, start at END and create file if necessary.

‘x’ Create and open for writing only.

‘x+’ Create and open for reading and writing .

Page 242: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fread() function

• Reads from an open file

• Syntax: fread(file,length)

• Example:<?php$file = fopen("test.txt","r");echo fread($file,5);fclose($file);?>

Page 243: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fwrite() function

• Writes the contents of the string

• Syntax: fwrite(filename, mode)

• Example:

<?php$file = fopen("test.txt","w");echo fwrite($file,"computer department");fclose($file);?>

Page 244: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

fclose() function

• Closes an open file.

• Syntax: fclose($filename)

• Example:

<?php$file = fopen("test.txt","w");echo fwrite($file,"computer department");fclose($file);?>

Page 245: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Summary

PHP offers several built in functions for day to day uses in coding

• Variable functions

• String functions

• Math functions

• Date functions

• Array functions

• File functions

Page 246: PHP Presentation

Chapter - 4

Working with Data

Page 247: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

4.1 FORM element, INPUT element

4.2 Processing the form

4.3 User Input

4.4 Adding Items

4.5 Validating the user input

4.6 Passing variables between pages

Working with Data• This unit covers….

Page 248: PHP Presentation

4.1FORM element,INPUT element

Developed By: Amit Lakhani, TFGP Adipur

Page 249: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• If you want to design a page , which accepts Information from users through various fields such as textbox, textarea, checkbox, radio buttons, drop down list etc at that time you have to use the form control.

• Form can be defined using <form> tag.

• Forms are used to pass data to a server.

• The syntax to put form control is: <form> </form>

Concept of Form element

Page 250: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Form element example

Form element

Form element

<html><form>First Name: <input type= "text" name="txtfname"><br>Last Name: <input type= "text" name="txtlname" ><br><input type= "submit" name="btnsubmit" value = "Send"></form></html>

Page 251: PHP Presentation

Form element output

Developed By: Amit Lakhani, TFGP Adipur

Page 252: PHP Presentation

Form attributesThe form attributes are as follows:

Action: - It is the URL program that is going to accept the data from the form, process it, and send a response back to the browser.Method:- GET(default) or POST specifies which HTTP method will be used to form’s content to the web server.Enctype:- This determines the mechanism used to encode the form content.Name:- This is form name.Target:- This is the target frame where the response page will show up.

Developed By: Amit Lakhani, TFGP Adipur

Page 253: PHP Presentation

Form elementsThe form elements are:

• Textboxes• Password boxes• Check boxes• Option buttons• Submit• Reset• File• Hidden• Image

Developed By: Amit Lakhani, TFGP Adipur

Page 254: PHP Presentation

Input elementsThe input elements are used to get input from the userIn various format:

• Type:- type of input entry field• Name:- variable name passed to application• Value:- the data associated with the variable name to be passed to the application• Checked :- Button/ box checked by default• Size:- number of character in text field • Maxlength :- maximum number of characters accepted

Developed By: Amit Lakhani, TFGP Adipur

Page 255: PHP Presentation

Input elements conti…..Following are the list of commonly used input fields:

• Hidden:- used to send data that you don’t want the web surfer to see.• Textbox:- used to provide input fields for text, phone numbers, dates etc.• Password:- used to allow entry of password.• Text area:- allows free form text entry.• Checkbox:- allows the user to select more than one option• Radio button:- allow users to select only one option.• Select:- used to select one or more option from given list

Developed By: Amit Lakhani, TFGP Adipur

Page 256: PHP Presentation

Input elements conti…..Following are the list of commonly used input fields:

• Option:- The list items are added to the <SELECT> element by inserting <OPTION> element.• Dropdown list:- it is used to select one option from list.• List :- it is used to select one option from list.• Push Button :- would cause an action to take place.• Submit:- it causes the browser to send the names and values of the other elements to the application specified by the ACTION attribute of the FORM element

Developed By: Amit Lakhani, TFGP Adipur

Page 257: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Input elements conti…..Following are the list of commonly used input fields:

• Image submit button:- allows to substitute an image for the standard submit button. • Reset:- It allows the user to clear all the input in the form.

Page 258: PHP Presentation

Hidden InputIt is used to send data to the application that you don’t Want the user to see or have to enter but is necessary for the application to process the form correctly.

Attributes: •Type:- hidden• Name:- variable name to be sent to the application• Value:- usually set to the value expected by the applicaton

<INPUT TYPE= “HIDDEN”>

Developed By: Amit Lakhani, TFGP Adipur

Page 259: PHP Presentation

Textbox InputIt is used to provide input fields for text, phone numbers,dates etc.

• Type:- text• Size:- determine the size of textbox in characters (default=20)• Maxsize :- determine the maximum number of characters that the field will accept• Name:- variable name to be sent to the application• Value:- will display its contents as the default value

<INPUT TYPE= “TEXT”>Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 260: PHP Presentation

Example of Textbox input

<html><form><font size=50>First Name: <input type= "text" name="txtfname“>Last Name: <input type= "text" name="txtlname" ><input type= "submit" name="btnsubmit" value = "Send"></form></html>

Textbox element

Developed By: Amit Lakhani, TFGP Adipur

Page 261: PHP Presentation

Output of Textbox example

Textbox

Developed By: Amit Lakhani, TFGP Adipur

Page 262: PHP Presentation

Password InputIt is used to allow entry of password

• Type:- password• Size:- determine the size of textbox in characters• Maxsize :- determine the maximum size of password

in characters.• Name:- variable name to be sent to the application• Value:- usually blank

<INPUT TYPE= “PASSWORD”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 263: PHP Presentation

Example of Password input

<html><form><font size=50>Username:<input type= "text" name="txtuname“>Password: <input type= “password" name="txtpwd”><input type= "submit" name="btnsubmit" value = "Send"></form></html> password

Developed By: Amit Lakhani, TFGP Adipur

Page 264: PHP Presentation

Output of Password example

password

Developed By: Amit Lakhani, TFGP Adipur

Page 265: PHP Presentation

Text area InputIt allows the user to type address, comments etc. having multiple lines.

• Name:- variable name to be sent to the application• Rows:- number of rows to the textbox• Cols:- number of columns to the textbox• Wrap:- default OFF. It is set so that the text wraps in the browser

<TEXTAREA> </TEXTAREA>Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 266: PHP Presentation

Example of textarea input

<html><form><font size=20>Name:<input type= "text" name="txtfname">Address:<textarea name="txtadd" rows=5 ></textarea><input type= "submit" name="btnsubmit" value = "Send" ></form></html>

Text area input

Developed By: Amit Lakhani, TFGP Adipur

Page 267: PHP Presentation

Output of textarea example

Text area

Developed By: Amit Lakhani, TFGP Adipur

Page 268: PHP Presentation

Checkbox InputIt allows the user to select more than one option.

• Type:- checkbox• Checked:- blank or CHECKED as the initial status• Name:- variable name to be sent to the application• Value:- usually set to a value

<INPUT TYPE= “CHECKBOX”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 269: PHP Presentation

Example of Checkbox input<html><form>Select Your Department:<br><input type= "checkbox" name="chkdept" value="dept">Computer<br><input type= "checkbox" name="chkdept" value="dept">Information Technology<br><input type= "checkbox" name="chkdept" value="dept">Mechanical<br><input type= "checkbox" name="chkdept" value="dept">Electrical</form></html>

Checkbox element

Developed By: Amit Lakhani, TFGP Adipur

Page 270: PHP Presentation

Output of checkbox example

checkbox

Developed By: Amit Lakhani, TFGP Adipur

Page 271: PHP Presentation

Radio button InputIt allows the user to select only one option.

• Type:- radio• Checked:- blank or CHECKED as the initial status. Only one radio button can be checked• Name:- variable name to be sent to the application• Value:- usually set to a value

<INPUT TYPE= “RADIO”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 272: PHP Presentation

Example of Radio button input

<html><form><font size=5>Select Your Gender:<input type= "radio" name="rdgender" value="male">Male<br><input type= "radio" name="rdgender" value="female">Female<br></form></html>

Radio button element

Developed By: Amit Lakhani, TFGP Adipur

Page 273: PHP Presentation

Output of Radio button example

Radio buttons

Developed By: Amit Lakhani, TFGP Adipur

Page 274: PHP Presentation

Select InputIt is used to select one or more option from given list of choice

•Name:- variable name to be sent to the application.• Size:- sets the number of visible choices.• Multiple:- presense of this attribute allow the user to make multiple selection

<SELECT> </SELECT>There are two types of select input:

• Dropdown list- it is like combobox control.• List box- it is like list control.

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 275: PHP Presentation

Option InputList items are added to the <OPTION> </OPTION> Element.

• Selected:- When this attribute presents, the option is selected when the document is initially loaded.

• Value:- Specifies the value the variable named in the select element.

<OPTION> </OPTION>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 276: PHP Presentation

Example of select input with dropdown menu

<html><form>Select Your Gender:<br><select name="lang">

<option > English</option><option selected> Hindi</option><option> Gujarati</option>

</select></html>

Select with option elementDeveloped By: Amit Lakhani, TFGP Adipur

Page 277: PHP Presentation

Output of select example with dropdown menu

Select input with dropdown box

Selected value

Developed By: Amit Lakhani, TFGP Adipur

Page 278: PHP Presentation

Example of select input with list box

<html><form>Select Your Language:<br><select name="lang" size=3 multiple="true">

<option > English</option><option selected > Hindi</option><option> Gujarati</option>

</select></html>

Select with option elementDeveloped By: Amit Lakhani, TFGP Adipur

Page 279: PHP Presentation

Output of select example with list box

Select input with list box

Multiple Selected value

Developed By: Amit Lakhani, TFGP Adipur

Page 280: PHP Presentation

Push ButtonThis element would be used to cause an action to take place

• Type:- Button• Name:- Specifies the name to be used in scripting.• Value:- determine the text label on the button.

<INPUT TYPE=“BUTTON”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 281: PHP Presentation

Example of push button

<html><form>First Name: <input type= "text" name="txtfname">Last Name: <input type= "text" name="txtlname" ><input type= “button" name="btnsubmit" value = "Send"></form></html> Push button input

Developed By: Amit Lakhani, TFGP Adipur

Page 282: PHP Presentation

Output of push button

button

Developed By: Amit Lakhani, TFGP Adipur

Page 283: PHP Presentation

Submit buttonThis element causes the browser to send the names ofAnd values of the other elements to the application Specified by the ACTION attribut of the FORM element

• Type:- submit• Name:- Specifies the name to be used in scripting.• Value:- determine the text label on the button.

<INPUT TYPE=“SUBMIT”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 284: PHP Presentation

Example of submit button

<html><form>First Name: <input type= "text" name="txtfname">Last Name: <input type= "text" name="txtlname" ><input type= “submit" name="btnsubmit" value = "Send"></form></html> submit button input

Developed By: Amit Lakhani, TFGP Adipur

Page 285: PHP Presentation

Output of submit button

Submit button

Developed By: Amit Lakhani, TFGP Adipur

Page 286: PHP Presentation

Image Submit buttonAllows user to substitute an image for the standard Submit button.

• Type:- image• Name:- Specifies the name to be used in scripting.• SRC:- URL of the image file.

<INPUT TYPE=“IMAGE” SRC= …URL>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 287: PHP Presentation

Example of image submit button

<html><form>First Name: <input type= "text" name="txtfname">Last Name: <input type= "text" name="txtlname" ><input type= “image“ src=”…” name="btnsubmit" value = "Send"></form></html> submit button input

Developed By: Amit Lakhani, TFGP Adipur

Page 288: PHP Presentation

Output of image submit button

image button

Developed By: Amit Lakhani, TFGP Adipur

Page 289: PHP Presentation

Reset buttonAllows user to clear all the input in the form.

• Type:- reset• Value:- determine the text label on the button.

<INPUT TYPE=“RESET”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 290: PHP Presentation

Example of reset button

<html><form>First Name: <input type= "text" name="txtfname">Last Name: <input type= "text" name="txtlname" ><input type= "submit"><input type= "reset"></form></html> reset button input

Developed By: Amit Lakhani, TFGP Adipur

Page 291: PHP Presentation

Output of reset button

reset button

Developed By: Amit Lakhani, TFGP Adipur

Page 292: PHP Presentation

4.2Processing the form

Developed By: Amit Lakhani, TFGP Adipur

Page 293: PHP Presentation

Concept of Processing the form• We can use any of the form elements to send or retrieve the data to or from PHP pages. You can store values Retrieved from form into variables in order to use these values.

• When you create a form you have two choices for the METHOD attribute. You can use one of the following two methods to pass information between pages.

• GET method• POST method

• They both pass the data entered into the form along with the form field name to the web server.

Developed By: Amit Lakhani, TFGP Adipur

Page 294: PHP Presentation

Processing the form• GET method

When GET method is used in the METHOD attribute of FORM element, the value entered in the input elements are displayed in URL.

Developed By: Amit Lakhani, TFGP Adipur

Page 295: PHP Presentation

• POST methodWhen POST method is used in the METHOD

attribute of FORM element, the value entered in the input elements are not passed in the URL.

Processing the form

Output of post method

Developed By: Amit Lakhani, TFGP Adipur

Page 296: PHP Presentation

Example of form processing using GET method

<html><body><form action="get.php" method="get">Name: <input type="text" name="fname" />Age:<input type="text" name=“surname" /><input type="submit" value=“Send”/></form></body></html>

Form_get.php

Developed By: Amit Lakhani, TFGP Adipur

<?phpecho "Name:".$_GET['fname'];echo "<br>";echo "Surname:".$_GET['surname'];?>

get.php

Page 297: PHP Presentation

Output of form

When “Send” button is clicked, value in the text box is sent to the get.php and are displayed in browser

Developed By: Amit Lakhani, TFGP Adipur

Output of form_get.php

Output of get.php

Page 298: PHP Presentation

Example of form processing using POST method

<html><body><form action=“post.php" method=“post">Name: <input type="text" name="fname" />Age:<input type="text" name=“surname" /><input type="submit" value=“Send”/></form></body></html>

Form_post.php

Developed By: Amit Lakhani, TFGP Adipur

<?phpecho "Name:".$_POST['fname'];echo "<br>";echo "Surname:".$_POST['surname'];?>

post.php

Page 299: PHP Presentation

Output of form

When “Send” button is clicked, value in the text box is sent to the post.php and are displayed in browser

Developed By: Amit Lakhani, TFGP Adipur

Output of form_post.php

Output of post.php

Page 300: PHP Presentation

4.3User input

Developed By: Amit Lakhani, TFGP Adipur

Page 301: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

4.3 User input

4.3.1 INPUT checkbox type4.3.2 One form multiple processing4.3.3 Radio INPUT element4.3.4 Multiple submit buttons4.3.5 Basic input testing4.3.6 Dynamic page title4.3.7 Manipulating string as an array

Page 302: PHP Presentation

4.3.1INPUT checkbox type

Developed By: Amit Lakhani, TFGP Adipur

Page 303: PHP Presentation

Checkbox InputIt allows the user to select more than one option.

• Type:- checkbox• Checked:- blank or CHECKED as the initial status• Name:- variable name to be sent to the application• Value:- usually set to a value

<INPUT TYPE= “CHECKBOX”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 304: PHP Presentation

Example of Checkbox input<html><form>Select Your Department:<br><input type= "checkbox" name="chkdept" value="dept">Computer<br><input type= "checkbox" name="chkdept" value="dept">Information Technology<br><input type= "checkbox" name="chkdept" value="dept">Mechanical<br><input type= "checkbox" name="chkdept" value="dept">Electrical</form></html>

Checkbox element

Developed By: Amit Lakhani, TFGP Adipur

Page 305: PHP Presentation

Output of checkbox example

checkbox

Developed By: Amit Lakhani, TFGP Adipur

Page 306: PHP Presentation

4.3.2One form

multiple processing

Developed By: Amit Lakhani, TFGP Adipur

Page 307: PHP Presentation

Concept of One form, multiple processing

• You can create a single form having many submit button for a variety of actions to be performed.

• For, example, you can have a database application in which a form may contain more than one buttons for insertion, deletion, searching etc. The page which receives the form data will then process the operations accordingly.

Developed By: Amit Lakhani, TFGP Adipur

Page 308: PHP Presentation

4.3.3Radio INPUT element

Developed By: Amit Lakhani, TFGP Adipur

Page 309: PHP Presentation

Radio button InputIt allows the user to select only one option.

• Type:- radio• Checked:- blank or CHECKED as the initial status. Only one radio button can be checked• Name:- variable name to be sent to the application• Value:- usually set to a value

<INPUT TYPE= “RADIO”>

Attributes:

Developed By: Amit Lakhani, TFGP Adipur

Page 310: PHP Presentation

Example of Radio button input

<html><form><font size=5>Select Your Gender:<input type= "radio" name="rdgender" value="male">Male<br><input type= "radio" name="rdgender" value="female">Female<br></form></html>

Radio button element

Developed By: Amit Lakhani, TFGP Adipur

Page 311: PHP Presentation

Output of Radio button example

Radio buttons

Developed By: Amit Lakhani, TFGP Adipur

Page 312: PHP Presentation

4.3.4Multiple submit button

Developed By: Amit Lakhani, TFGP Adipur

Page 313: PHP Presentation

Concept of multiple submit button

• You can create a single form having many submit button for a variety of actions to be performed.

• The submit button can share the same name but supply different values.

• Clicking one of these buttons will cause the browser to submit the form accordingly

Developed By: Amit Lakhani, TFGP Adipur

Page 314: PHP Presentation

Example of form with multiple submit<html><body><form action="multiple_submit_post.php" method="post" >Name:<input type="text" name="fname" />Address: <textarea name="address"> </textarea><input type="submit" name="display" value="Show Name" /><input type="submit" name="display" value="Show Address" /></form></body></html>

Multiple submit in a form, each button must have same name

Developed By: Amit Lakhani, TFGP Adipur

Page 315: PHP Presentation

Example of form with multiple submit

<?phpif ($_POST['display']=="Show Name"){

echo "Your name is:" .$_POST['fname'];}else{

echo " Your Address is:" .$_POST['address'];}?>

Here, we just check for the value submitted for the Submit button

Developed By: Amit Lakhani, TFGP Adipur

Multiple_submit_post.php

Page 316: PHP Presentation

Output of form with multiple submit

Depending on the button you click and the data you chooseTo enter , this code outputs different information.

Developed By: Amit Lakhani, TFGP Adipur

Output of form_multiple_submit.php

Output of multiple_submit_post.php

Page 317: PHP Presentation

4.3.5Basic Input testing

Developed By: Amit Lakhani, TFGP Adipur

Page 318: PHP Presentation

Concept of input testing• Input testing involves verification that the data you receive from a client is in fact in the form you planned on receiving.

• Invalid data cause two major problems in code• Trash data- that does not match the specification• Altered data- intentionally obscured

Developed By: Amit Lakhani, TFGP Adipur

• A common tactic is used to address this is to use drop down boxes to provide users a choice of state.

Page 319: PHP Presentation

Concept of input testing• In PHP script input testing is done using the same way as JavaScript validation.

• Before using user input for processing we need to check the following information:

• Does the user supply all mandatory information?• Is the information provided contains valid and

meaningful data?• Is the submitted information conforming to the

standard? (dd/mm/yyyy)

Developed By: Amit Lakhani, TFGP Adipur

Page 320: PHP Presentation

Concept of input testing

• Check whether a variable is a number or numeric string:$result = is_numeric($string);

• Check whether a string contains only alphanumeric characters(alphabetic/numeric):

$result = ctype_alnum($ string);

• Check whether a string contains simply alphabetic characters(letters a to z):

$result = ctype_alpha($ string);

Developed By: Amit Lakhani, TFGP Adipur

Basic input test are:

Page 321: PHP Presentation

Concept of input testing

• Check whether a string contains only digits:$result = ctype_digit($ string);

• Check whether a string contains only hexadecimal digits:$result = ctype_xdigit($ string);

• Check whether a string is completely upper/lower case: characters(letters a to z):

$result = ctype_upper($ string);$result = ctype_lower($ string);

Developed By: Amit Lakhani, TFGP Adipur

Basic input test are:

Page 322: PHP Presentation

Concept of input testing

• Forces a variable to be a specific type:$result = settype($variable, $type);

• Interpret a variable as a certain type using type-casting:$result = (datatype) $variable;

Developed By: Amit Lakhani, TFGP Adipur

Basic input test are:

Page 323: PHP Presentation

Example of input testing

Check whether a string contains only digitsDeveloped By: Amit Lakhani, TFGP Adipur

Form_validation.php <html><body><form action="validation_post.php" method="post" >Name:<input type="text“ name="fname" />Surname: <input type="text" name="surname" /><input type="submit" value="Send" /></form></body></html>

<?php$result=$_POST['fname'];if (ctype_digit($result)=="TRUE")

echo "Please enter alphabets only in Name";else

echo "You have entered correct informaion";?>

Validation_post.php

Page 324: PHP Presentation

Example of Input testing

Check whether a string contains only digits, if the digits are entered in name, it warns user to enter only alphabet in name

Developed By: Amit Lakhani, TFGP Adipur

Output of form_validation.php

Output of validation_post.php

Page 325: PHP Presentation

4.3.6Dynamic Page Title

Developed By: Amit Lakhani, TFGP Adipur

Page 326: PHP Presentation

Concept of dynamic page title

• When displaying the web page to the user we can change the title of the page dynamically using <title> tag with a little bit effort of PHP code within <title></title> .

• There are two ways to display title of the page dynamically:

• When title of the page is set• When title of the page is not set

Developed By: Amit Lakhani, TFGP Adipur

Page 327: PHP Presentation

Example of dynamic title when title is set

Dynamic title is set

Developed By: Amit Lakhani, TFGP Adipur

Dynamic_title.php<html><head><?php isset($title) ? $title : "Default title";?></head><body><?php $title="Example of dynamic title";require_once("dynamic_title_header.php");?></body></html>

<title><?php if (isset($title))

print $title;Else

print "default title";?></title>

Dynamic_title_header.php

output

Page 328: PHP Presentation

Example of dynamic title when title is not set

default title is set

Developed By: Amit Lakhani, TFGP Adipur

Dynamic_title.php<html><head><?php isset($title) ? $title : "Default title";?></head><body><?php require_once("dynamic_title_header.php");?></body></html>

<title><?php if (isset($title))

print $title;Else

print "default title";?></title>

Dynamic_title_header.php

output

Page 329: PHP Presentation

4.3.7Manipulating the string

as an array

Developed By: Amit Lakhani, TFGP Adipur

Page 330: PHP Presentation

• In PHP, two types of data need special attention and a more complete explanation i.e. array and string

• Actually strings are array of characters i.e. group of • characters, it means following two statements are same:

$string=“computer”;$string=array(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’);

• This states that we can use string as an array and we can manipulate string as an array using functions.

Developed By: Amit Lakhani, TFGP Adipur

Concept of string as an array

Page 331: PHP Presentation

• str_split() :- it splits string into an array.

• explode():- it breaks a string into an array.

• implode() :- returns a string from the element of an array.

Developed By: Amit Lakhani, TFGP Adipur

Functions that is used to convert string as array

Page 332: PHP Presentation

Str_split() function• splits a string into an array.

• Syntax: str_split(string, length)

• Example:

<?phpPrint_r(str_split(“computer”));?>

Output:

Splits the string

Developed By: Amit Lakhani, TFGP Adipur

Page 333: PHP Presentation

explode() function• breaks a string into an array.

• Syntax: explode(separator, string, limit)

• Example:

<?php$str="Hi, This is computer department";print_r(explode(",",$str));print_r(explode(" ",$str));print_r(explode(" ",$str,3));?>

breaks the string

Developed By: Amit Lakhani, TFGP Adipur

Page 334: PHP Presentation

Output of explode() functionbreaks the string with seperator “,”

breaks the string with seperator “ ”

breaks the string with seperator “ ”

Developed By: Amit Lakhani, TFGP Adipur

Page 335: PHP Presentation

implode() function• returns a string from the element of an array

• Syntax: implode(separator, array)

• Example:

<?php$arr=array('computer', 'department');echo implode(" ",$arr);?>

Output:

return string with space

Developed By: Amit Lakhani, TFGP Adipur

Page 336: PHP Presentation

4.4Adding Items

Developed By: Amit Lakhani, TFGP Adipur

Page 337: PHP Presentation

Adding items to an array and copy whole array• to add an item to an array use [ ] operator

• to copy a whole array

• Example:

<?php$dept[0]="IT";$dept[1]="Computer";$dept[2]="Mech";$department=$dept;echo $department[1];?>

Copy whole array

Developed By: Amit Lakhani, TFGP Adipur

Page 338: PHP Presentation

4.5Validating user input

Developed By: Amit Lakhani, TFGP Adipur

Page 339: PHP Presentation

Client side validation•You can write scripting code that will verify form fields contain good data before being submitted to the server.• Most client side validation is completed using the special “onSubmit” event of a form, which allows you to run Java script code to handle form validation when your visitor attempts to submit the form.• If you return false from your code in “onSubmit”, web browser will not proceed with submitting the form, which allows you to prompt visitors to correct any error before submission.

Developed By: Amit Lakhani, TFGP Adipur

Page 340: PHP Presentation

Server side validation

• It means using PHP to verify that good values have been sent to the script.• It is more secure and works seamlessly with all browser, but it does so at the cost of higher server load and slower feedback for users.• Any sensible site should include server side validation of variables, because they are harder to hack and they will work no matter what browser your visitors are using.

Developed By: Amit Lakhani, TFGP Adipur

Page 341: PHP Presentation

4.6Passing variables

Between pages

Developed By: Amit Lakhani, TFGP Adipur

Page 342: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

4.6 Passing variables between pages

4.6.1 Passing variable through URL4.6.2 Passing variable through sessions4.6.3 Passing variable through cookie4.6.4 Passing variable through forms

Page 343: PHP Presentation

4.6.1Passing variables

with URL

Developed By: Amit Lakhani, TFGP Adipur

Page 344: PHP Presentation

Passing variables through URL

•There are various ways to pass data between pages, one of the way is to use the URL to pass the values through GET method.

• The advantage is we can pass data to a different sites running at different server.

• Main concern is the data gets exposed in address bar of the browser and can be easily accessed by using browser history.

Developed By: Amit Lakhani, TFGP Adipur

Page 345: PHP Presentation

4.6.2Passing variables

with session

Developed By: Amit Lakhani, TFGP Adipur

Page 346: PHP Presentation

Passing variables with session

• HTTP is stateless protocol which means that each server request knows nothing about the others.

• A PHP session variable is used to store information about, or change settings for a user session.

• Session variables hold information about one single user, and are available to all pages in one application.

Developed By: Amit Lakhani, TFGP Adipur

Page 347: PHP Presentation

Passing variables with session conti..

• When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are.

• It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

Developed By: Amit Lakhani, TFGP Adipur

Page 348: PHP Presentation

Passing variables with session conti..• A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc).

• However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

• Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. the UID is either stored in a cookie or is propagated in the URL.

Developed By: Amit Lakhani, TFGP Adipur

Page 349: PHP Presentation

Starting a session

<?php session_start(); ?><html><body></body></html>

Developed By: Amit Lakhani, TFGP Adipur

• Before you can store user information in your PHP session, you must first start up the session.

• The session_start() function must appear BEFORE the <html> tag:

ExampleStart the session using function

Page 350: PHP Presentation

Storing a session variable

<?phpsession_start();// store session data$_SESSION['views']=1;?>

Developed By: Amit Lakhani, TFGP Adipur

• The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:Example Store session variable using

$_SESSION[] superglobal

Page 351: PHP Presentation

Destroy a session variable

<?phpunset($_SESSION['views']);?> Developed By: Amit Lakhani, TFGP Adipur

• If you wish to delete some session data, you can use the unset() or the session_destroy() function.•You can completely destroy the session by calling the session_destroy() function:

<?phpsession_destroy();?>

•The unset() function is used to free the specified session variable:

Page 352: PHP Presentation

Session example

<html><body><form action="session_post.php" method="post">Name: <input type="text" name="fname" /><input type="submit" name="btnsub"/></form></body></html>

Developed By: Amit Lakhani, TFGP Adipur

Session_form.phpWhen submit is clicked session_post.php is called

Page 353: PHP Presentation

Session example

<?phpsession_start();$_SESSION['name']=$_POST['fname'];$myname=$_SESSION['name'];echo "Wel come:<b>" .$myname."<b><br>";if(isset($_SESSION['views']))

$_SESSION['views']=$_SESSION['views']+1;else

$_SESSION['views']=1;echo "You visited this page=". $_SESSION['views'];echo " times.";?>

Developed By: Amit Lakhani, TFGP Adipur

Session_post.phpUser input is fetched in session variable

Page 354: PHP Presentation

Session example output

Developed By: Amit Lakhani, TFGP Adipur

Session_form.php

When submit is clicked session_post.php is called and session variable is called

Session_post.php

Page 355: PHP Presentation

4.6.3Passing variables

with cookies

Developed By: Amit Lakhani, TFGP Adipur

Page 356: PHP Presentation

Passing variables with cookies

• A cookie is often used to identify a user. • A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

• With PHP, you can both create and retrieve cookie values.

Developed By: Amit Lakhani, TFGP Adipur

Page 357: PHP Presentation

Setting cookies• The setcookie() function is used to set a cookie.

• The setcookie() function must appear BEFORE the <html> tag.

Syntaxsetcookie(name, value, expire, path, domain);

•Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

Developed By: Amit Lakhani, TFGP Adipur

Page 358: PHP Presentation

Setting cookies conti..

Developed By: Amit Lakhani, TFGP Adipur

Parameters Meaningname The name of the cookie.value The value of the cookie.

This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']

• cookie parameters:

Page 359: PHP Presentation

Setting cookies conti..

Developed By: Amit Lakhani, TFGP Adipur

Parameters Meaningexpire The time the cookie

expires. This is a Unix timestamp so is in number of seconds since the epoch. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

• cookie parameters:

Page 360: PHP Presentation

Setting cookies conti..

Developed By: Amit Lakhani, TFGP Adipur

Parameters Meaningpath The path on the server in

which the cookie will be available on. The default value is the current directory that the cookie is being set in.

• cookie parameters:

Page 361: PHP Presentation

Setting cookies

Developed By: Amit Lakhani, TFGP Adipur

Parameters Meaningdomain The domain that the cookie

is available to. Setting the domain to www will make the cookie only available in the www subdomain.

secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.

• cookie parameters:

Page 362: PHP Presentation

Creating Cookie

<?phpsetcookie("user", "Amit Lakhani", time()+3600);?><html><form action="wc1.php" method="post"><input type="submit"></form</html>

Developed By: Amit Lakhani, TFGP Adipur

cookie.phpCookie name

Cookie value

Cookie expiry

When submit is clicked wc1.php is called

Page 363: PHP Presentation

Accessing Cookie using $_COOKIE

<html><body><?phpif (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />";else echo "Welcome guest!<br />";?></body></html>

Developed By: Amit Lakhani, TFGP Adipur

wc1.php Accessing Cookie value

Page 364: PHP Presentation

Destroying Cookie

When deleting a cookie you should assure that the expiration date is in the past.

Example:<?php// set the expiration date to one hour agosetcookie("user", “Amit Lakhani", time()-3600);?>

Developed By: Amit Lakhani, TFGP Adipur

expiration date to one hour ago

Page 365: PHP Presentation

4.6.4Passing variables

with forms

Developed By: Amit Lakhani, TFGP Adipur

Page 366: PHP Presentation

Concept of $_REQUEST variable•The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.

•The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.

Example<?php echo $_REQUEST["fname"]; ?>!<br />?>

Developed By: Amit Lakhani, TFGP Adipur

Page 367: PHP Presentation

$_REQUEST example

<html><body><form action="request.php" method="post" >Name:<input type="text“ name="fname" />Surname: <input type="text" name="surname" /><input type="submit" value="Send" /></form></body></html>

Developed By: Amit Lakhani, TFGP Adipur

Form_request.php

<?phpecho “Name:”$_REQUEST['fname'];echo "Surname:”$_REQUEST['surname'];?>

request.php Get the value of input

Page 368: PHP Presentation

Output of $_REQUEST example

Developed By: Amit Lakhani, TFGP Adipur

Form_request.php

Get the value of input using $_REQUEST

request.php

Page 369: PHP Presentation

Self processing HTML Forms

Developed By: Amit Lakhani, TFGP Adipur

Page 370: PHP Presentation

Concept of $_PHP_SELF superglobal• The PHP default variable $_PHP_SELF is used for the PHP script name and when you click “submit” button then the same PHP script will be called and will produce the result.

• Example:

Developed By: Amit Lakhani, TFGP Adipur

<html><body><form action="<?php $_PHP_SELF ?>" method="post"></form></body></html>

Value of action property is set to $_PHP_SELF

Page 371: PHP Presentation

Example of $_PHP_SELF superglobal

Developed By: Amit Lakhani, TFGP Adipur

<?phpif (isset($_POST['fname'])){

echo "welcome:".$_POST['fname'];exit();

}?><html><body><form action="<?php $_PHP_SELF ?>" method="post">Name:<input type="text“ name="fname" />Surname: <input type="text" name="surname" /><input type="submit" value="Send" /></form></body></html>

When submit is clicked it executes the above script

Page 372: PHP Presentation

Browser Redirection

Developed By: Amit Lakhani, TFGP Adipur

Page 373: PHP Presentation

Concept of browser redirection

• The header() function sends a raw HTTP header to a client.

• It is important to notice that header() must be called before any actual output is sent

• Syntaxheader(string,replace,http_response_code)

Developed By: Amit Lakhani, TFGP Adipur

Page 374: PHP Presentation

Concept of browser redirection

Developed By: Amit Lakhani, TFGP Adipur

Parameter Description string Required. Specifies the header string

to send replace Optional. Indicates whether the

header should replace previous or add a second header. Default is TRUE (will replace). FALSE (allows multiple headers of the same type)

http_response_code Optional. Forces the HTTP response code to the specified value (available in PHP 4.3 and higher)

header parameters:

Page 375: PHP Presentation

Example of header() function

Developed By: Amit Lakhani, TFGP Adipur

<?phpheader("Content-Type: image/jpeg");header("Content-Disposition: attachment; filename=file.jpg");?>

Page 376: PHP Presentation

Example of header() function

Developed By: Amit Lakhani, TFGP Adipur

<?phpheader("Location:http://www.google.com");?>

Page 377: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• FORM element, INPUT element

• Processing the form

• User Input

• Adding Items

• Validating the user input

• Passing variables between pages

Summary

Page 378: PHP Presentation

Chapter - 5

Error Handling

Page 379: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

5.1 Error types in PHP

5.2 Generating PHP errors

5.3 Exceptions

5.4 Not meeting conditions

5.5 Parse errors

Error handling• This unit covers….

Page 380: PHP Presentation

Error Handling

Developed By: Amit Lakhani, TFGP Adipur

Page 381: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Error handling is the process of catching errors raised by your program and then taking appropriate action. • 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.

Concept of error

Page 382: PHP Presentation

5.1Error Types in PHP

Developed By: Amit Lakhani, TFGP Adipur

Page 383: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Types of error • There are main four categories of errors in PHP

• Fatal error – critical errors ( instantiating an object of a non existence class or calling a non existence function). It cause the immediate termination of the script and PHP’s default behavior is to display them to the user when they take place.

• Notice – trivial or non critical errors that PHP encounters when executing a script. E.g accessing a variable that has not yet been defined. Such errors are not displayed to users.

Page 384: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Types of error • There are main four categories of errors in PHP

• Warning – serious errors, e.g attempt to include a file which does not exists. This errors are displayed to users but they don’t result in script termination.

• Parse– compile time errors. When we make mistake in code e.g missing a semicolon or any unexpected symbol then paneraterse errors are generated.

Page 385: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Error predefined constantsE_NOTICE Detection of a situation that could indicate a

problem, but might be normal.

E_USER_NOTICE User triggered notice.

E_WARNING Actionable error occurred during execution.

E_USER_WARNING User triggered warning.

E_COMPILE_WARNING

Error occurred during script compilation (unusual)

E_CORE_WARNING Error during initialization of the PHP engine.

E_ERROR Fatal run-time error

E_USER_ERROR User triggered fatal error.

E_COMPILE_ERROR Critical error occurred while trying to read script.

E_CORE_ERROR Occurs if PHP engine cannot startup/etc.

E_PARSE Raised during compilation in response to syntax error

Page 386: PHP Presentation

5.2Generating PHP

errors

Developed By: Amit Lakhani, TFGP Adipur

Page 387: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Generating error

<?php$str="This is error example";$string=strtoupper();?>

Error warning

Page 388: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Error handling using die() functionThe first 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:\webfolder\test.php on line 2

Page 389: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Error handling using die() function conti..To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:

<?phpif(!file_exists("welcome.txt")) {

die("File not found"); }else {

$file=fopen("welcome.txt","r"); }?>

handle error using die()

Page 390: PHP Presentation

5.3Exception Handling

Developed By: Amit Lakhani, TFGP Adipur

Page 391: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of exception• Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.• This is what normally happens when an exception is triggered:

• The current code state is saved• The code execution will switch to a predefined

(custom) exception handler function• Depending on the situation, the handler may

then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.

Page 392: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of exception conti..

• Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point. • The different error handling methods:

• Basic use of Exceptions• Creating a custom exception handler• Multiple exceptions• Re-throwing an exception• Setting a top level exception handler

Page 393: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Basic Use of Exceptions

• PHP uses try/catch method to handle exception. • When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.

• If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Page 394: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Exception example<?php//create function with an exceptionfunction checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }checkNum(2);?>

throw an uncaught exception

Page 395: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Exception example output

throw an uncaught exception

Page 396: PHP Presentation

Use try, throw, catch

Developed By: Amit Lakhani, TFGP Adipur

Page 397: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Using try, throw and catch • To avoid the error to be handled by the PHP engine, we need to create the proper code to handle an exception. • Proper exception code should include:

• Try - A function using an exception should be in a "try" block. If the exception does not trigger, the

code will continue as normal. However if the exception triggers, an exception is "thrown"

• Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"

• Catch - A "catch" block retrieves an exception and creates an object containing the exception information

Page 398: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Exception example<?phpfunction checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }try { checkNum(2); echo 'If you see this, the number is 1 or below'; }catch(Exception $e) { echo 'Message: ' .$e->getMessage(); }?>

throw an exception

caught exception

1

2

3

Page 399: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Exception example explaindThe code above throws an exception and catches it:1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown.2. The checkNum() function is called in a "try" block3. The exception within the checkNum() function is thrown4. The "catch" block retrives the exception and creates an object ($e) containing the exception information5. The error message from the exception is echoed by calling $e->getMessage() from the exception object

Page 400: PHP Presentation

Creating custom exception class

Developed By: Amit Lakhani, TFGP Adipur

Page 401: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating custom exception class• It is simple to create a special class with functions that can be called when an exception occurs in PHP. • The class must be an extension of the exception class.• The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.

class customException extends Exception {

public function errorMessage()

Page 402: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Custom exception class example<?phpclass customException extends Exception { public function errorMessage() { $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid denominator; return $errorMsg; } }

try {$a=25;$b=0 if($b==0) { //throw exception if email is not valid throw new customException($b); } }catch (customException $e) { //display custom message echo $e->errorMessage(); }?>

Page 403: PHP Presentation

Nesting Exception

Developed By: Amit Lakhani, TFGP Adipur

Page 404: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of nesting exception

• We can also put one try block inside another try block, this is called nesting of exceptions.

• In nested exception when the inner try block will be executed and exception is thrown then the matching inner catch block will be executed.

• If no inner catch block can handle the generated exception than the outer catch block will handle the exception.

Page 405: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of nesting exception conti..Class sample {Public function testing(){

try{

try { };catch {

};}catch(){}

}}

inner block

outer block

Page 406: PHP Presentation

Multiple Exception

Developed By: Amit Lakhani, TFGP Adipur

Page 407: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of multiple exception

• It is possible for a script to use multiple exceptions to check for multiple conditions.

• It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages.

Page 408: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of multiple exception<?phpclass Exception1 extends Exception {}class Exception2 extends Exception1 {}class test{public function testing(){try {throw new Exception1("PHP exception handling"); }

multiple catch block

catch (Exception1 $e) { echo $e->getMessage(); }

catch(Exception2 $e) { echo $e->getMessage(); }catch (Exception $e) { echo $e->getMessage(); }}};$ob= new test;$ob->testing();?>

Page 409: PHP Presentation

Rethrowing Exception

Developed By: Amit Lakhani, TFGP Adipur

Page 410: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of rethrowing exception• Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way.

• It is possible to throw an exception a second time within a "catch" block. • A script should hide system errors from users.

• System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message.

Page 411: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Example of rethrowing exception<?phpclass exc extends Exception {}class test{public function testing(){try {

try{throw new Exc("PHP

exception handling");}catch (Exc $e) {

throw $e; }

}

re-throw an exception

catch (exc $e) { echo $e->getMessage(); }

}};$ob= new test;$ob->testing();?>

Page 412: PHP Presentation

Set a top level exception handler

Developed By: Amit Lakhani, TFGP Adipur

Page 413: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of top level exception handlerThe set_exception_handler() function sets a user-defined function to handle all uncaught exceptions.

<?phpfunction customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; }set_error_handler("customError");echo($test);?>

Page 414: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Rules for exception

• Code may be surrounded in a try block, to help catch potential exceptions• Each try block or "throw" must have at least one corresponding catch block• Multiple catch blocks can be used to catch different classes of exceptions• Exceptions can be thrown (or re-thrown) in a catch block within a try block

A simple rule: If you throw something, you have to catch it.

Page 415: PHP Presentation

5.4Not meeting conditions

Developed By: Amit Lakhani, TFGP Adipur

Page 416: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of not meeting condition

• Error trapping can not catch all problems in your code. It will catch only problems related to PHP itself.

• Any problem you are having with conditions it your code will not be caught by simple error traping.

• You will have to do this manually, by using several different methods of troubleshooting in your code.

Page 417: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of not meeting conditionSome common problems are:

• IF statement block not getting executed:While you are submitting a form, you are

checking whether or not the submit button has been pressed.

• Variable values are not getting displayed:Another common problem occurs when

variables are not being output. Mostly variables are just fine but the programmer can not figure out why they are not being output.

Page 418: PHP Presentation

5.5Parse error

Developed By: Amit Lakhani, TFGP Adipur

Page 419: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Concept of parse error• It occurs when

• you forget a semicolon,• Curly braces are mismatched,• square brackets are not used properly.

• These parse errors usually don’t have to do with a condition statement, they are mainly syntax error that will cause the script to halt execution. •Parse error are worst error than fatal error because they will not let the script run at all, they merely give you the error information.

Page 420: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Error types in PHP

• Generating PHP errors

• Exceptions

• Not meeting conditions

• Parse errors

Summary

Page 421: PHP Presentation

Chapter - 6

Images with PHP

Page 422: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

6.1 working with GD library

6.2 File types with GD and PHP

6.3 Compiling PHP with GD

6.4 Creating the image table

6.5 uploading the image

Images with PHP• This unit covers….

Page 423: PHP Presentation

6.1 Working with GD

library

Developed By: Amit Lakhani, TFGP Adipur

Page 424: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• GD stands for “Graphics Draw”.

• GD is an open source code library for the dynamic creation of images by programmers. GD creates PNG, JPEG and GIF images, among other formats. • GD is commonly used to generate charts, graphics, thumbnails, and most anything else, on the fly. • While not restricted to use on the web, the most common applications of GD involve web site development.

What is GD library?

Page 425: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• If you have the GD library (available at http://www.libgd.org/) you will also be able to create and manipulate images. • The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. • Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

What is GD library? Conti…

Page 426: PHP Presentation

6.2 Files types in GD

and PHP

Developed By: Amit Lakhani, TFGP Adipur

Page 427: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Supported image formatsImage format

Notes

gif

Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.

jpeg

When building the jpeg library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP.

png Only supported in GD versions greater than gd-1.6.

xpmIt's likely you have this library already available, if your system has an installed X-Environment.

Page 428: PHP Presentation

6.3 Compiling PHP with

GD

Developed By: Amit Lakhani, TFGP Adipur

Page 429: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• In windows, first make sure the php_gd.dll file is in the ext folder within the PHP installation’s directory. • e.g. if PHP is installed in C:\, then look in C:\PHP\ext and find following line in php.ini file: ;extension=phpgd2.dll• Remove the leading semicolon to uncomment it, save the change and restart Apache.• To test GD installation, run the following code: <?php

print_r(gd_info());?>

Enabling GD in PHP

Page 430: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• ImageCreate ($width, $height) - creates an image handle/object of specified width and height.• ImageColorAllocate ($handle, $R, $G, $B) – set the background color of handle with specified amount of RGB. The value of RGB must be between 0 – 255.• ImageString ($handle, $font, $x,&y,“text“,$txt_color) enter the text in graphics. Font must be of 1-5.• ImagePng ($handle) – creates PNG image.• ImageTTFText($h,$size,$rotation,$x,$y,$color, $font,$text) – allows to choose fonts which is in TTF format

Image functions

Page 431: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/png"); $handle = ImageCreate (130, 50) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 0, 0); $txt_color = ImageColorAllocate ($handle, 0, 0, 0); ImageString ($handle, 5, 5, 18, "This is PHP image", $txt_color); ImagePng ($handle);?>

Creating Rectangle with textSet content type to png/jpeg/gif

Page 432: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/gif"); $handle = ImageCreate (130, 50) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 0, 0); $txt_color = ImageColorAllocate ($handle, 0, 0, 0); ImageTTFText ($handle, 20, 15, 30, 40, $txt_color, "C:/Windows/Fonts/Verdana.ttf", "PHP"); ImageGif ($handle); ?>

Working with fonts

Page 433: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/png"); $handle = ImageCreate (530, 150) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 0, 0); $txt_color = ImageColorAllocate ($handle, 255, 255, 255); $line_color = ImageColorAllocate ($handle, 0, 0, 0); ImageLine($handle, 65,0, 530, 150, $line_color); ImageString ($handle, 5, 5, 18, "PHP", $txt_color); ImagePng ($handle); ?>

Drawing Lines

Page 434: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/png"); $handle = ImageCreate (1300, 550) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 255, 255); $txt_color = ImageColorAllocate ($handle, 255, 255, 255); $line_color = ImageColorAllocate ($handle, 0, 0, 0); for($i=0;$i<=1300;$i=$i+10) {

ImageLine($handle, 550, 0, $i, 550, $line_color); } ImageString ($handle, 5, 5, 18, "PHP", $txt_color); ImagePng ($handle); ?>

Drawing Lines with loops

Page 435: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/png"); $handle = ImageCreate (1300, 550) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 255, 255); $txt_color = ImageColorAllocate ($handle, 255, 255, 255); $line_color = ImageColorAllocate ($handle, 0, 0, 0); imageellipse ($handle, 650, 275, 1000, 400, $line_color); ImageString ($handle, 5, 5, 18, "PHP.About.com", $txt_color); ImagePng ($handle); ?>

Drawing an ellipse

Page 436: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header ("Content-type: image/png"); $handle = ImageCreate (1300, 550) or die ("Cannot Create image"); $bg_color = ImageColorAllocate ($handle, 255, 255, 255); $txt_color = ImageColorAllocate ($handle, 255, 255, 255); $line_color = ImageColorAllocate ($handle, 0, 0, 0); imagefilledellipse ($handle, 650, 225, 500, 200, $line_color); ImageString ($handle, 5, 5, 18, "PHP.About.com", $txt_color); ImagePng ($handle); ?>

Drawing an ellipse with fill

Page 437: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<? header('Content-type: image/png'); $handle = imagecreate(1000, 1000); $background = imagecolorallocate($handle, 255,0, 0); $red = imagecolorallocate($handle, 255, 0, 0); $green = imagecolorallocate($handle, 0, 255, 0); $blue = imagecolorallocate($handle, 0, 0, 255); imagefilledarc($handle, 50, 50, 100, 50, 0, 90,$red, IMG_ARC_PIE); imagefilledarc($handle, 50, 50, 100, 50, 90, 225,$blue, IMG_ARC_PIE); imagefilledarc($handle, 50, 50, 100, 50, 225, 360,$green,IMG_ARC_PIE);

imagepng($handle); ?>

Arcs & Pies

Page 438: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header('Content-type: image/png'); $h = ImageCreate(100, 100); $bg = ImageColorAllocate($h, 255,255, 255); $r = ImageColorAllocate($h, 255, 0, 0); $g = ImageColorAllocate($h, 0, 255, 0); $b = ImageColorAllocate($h, 0, 0, 255); Imagefilledarc($h,50,50,100,50,0,90,$r,IMG_ARC_CHORD); Imagefilledarc($h,50,50,100,50,90,225,$b,IMG_ARC_CHORD); Imagefilledarc($h,50,50,100,50,225,360,$g,IMG_ARC_CHORD); ImagePng($h); ?>

Arcs & Chords

Page 439: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header('Content-type: image/png'); $h = ImageCreate(100, 100); $bg = ImageColorAllocate($h, 255,255, 255); $r = ImageColorAllocate($h, 255, 0, 0); $g = ImageColorAllocate($h, 0, 255, 0); $b = ImageColorAllocate($h, 0, 0, 255); Imagefilledarc($h,50,50,100,50,0,90,$r,IMG_ARC_NOFILL); Imagefilledarc($h,50,50,100,50,90,225,$b,IMG_ARC_NOFILL); Imagefilledarc($h,50,50,100,50,225,360,$g,IMG_ARC_NOFILL); ImagePng($h); ?>

Arcs & No fill

Page 440: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php header('Content-type: image/png'); $h = ImageCreate(100, 100); $bg = ImageColorAllocate($h, 255,255, 255); $r = ImageColorAllocate($h, 255, 0, 0); $g = ImageColorAllocate($h, 0, 255, 0); $b = ImageColorAllocate($h, 0, 0, 255); Imagefilledarc($h,50,50,100,50,0,90,$r,IMG_ARC_EDGED); Imagefilledarc($h,50,50,100,50,90,225,$b,IMG_ARC_EDGED); Imagefilledarc($h,50,50,100,50,225,360,$g,IMG_ARC_EDGED); ImagePng($h); ?>

Arcs & edged

Page 441: PHP Presentation

Manipulating imagesWith PHP

Developed By: Amit Lakhani, TFGP Adipur

Page 442: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

To begin any manipulation, one must access an image resource. • imagecreate($width, $height) – creates a blank image resource of the specified size.• imagecreatefromgif($filename) – creates an image resource from the specified GIF format file.• imagecreatefromjpeg($filename) – creates an image resource from the specified JPEG format file.• imagecreatefromPNG($filename) – creates an image resource from the specified PNG format file. All of these functions return ‘resources’ which are used in GD library.

Manipulating images

Page 443: PHP Presentation

6.4Creating image table

Developed By: Amit Lakhani, TFGP Adipur

Page 444: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• To store images in database, large BLOB is a suitable format, provided in MySQL.

• Example: CREATE TABLE ‘images’(‘imageID’ INT(10) NOT NULL AUTO INCREMENT, ‘imagedata’ LONGBLOBNOT NULL, PRIMARY KEY (‘imageID’));

Image table

Page 445: PHP Presentation

6.5Uploading image

Developed By: Amit Lakhani, TFGP Adipur

Page 446: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<html><body><form action="upload_file.php" method="post"enctype="multipart/form-data"><label>Filename:</label><input type="file" name="file" id="file" /> <input type="submit" name="submit" value="Upload" /></form></body></html>

Upload_form.php

Page 447: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$link=mysql_connect("localhost","root","");if(!$link){

die('Not connected:'.mysql_error());} $db=mysql_select_db('upload',$link);if(!$db){

die('Database error:‘.mysql_error());}

Upload_img.php Connect to mysql server

Connect to database server

Page 448: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Upload_img.php$max="1000000";$img_array=array("image/jpeg","image/jpg","image/gif","image/bmp","image/png");$file=$_FILES['file']['type'];//if submit is clickedif(@$_POST['submit']){

//check for the image type before uploadingif(in_array($file,$img_array)){//check whether the file is uploadedif(is_uploaded_file($_FILES['file']['tmp_name'])){//check whether the file size is below 1MBif($_FILES['file']['size']<$max){//reading image data$imgdata=addslashes(file_get_contents($_FILES['file']['tmp_name']));

Page 449: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Upload_img.php//insert into database

$sql="insert into image(imgdata) values($imgdata)";mysql_query($sql,$link) or die(mysql_error());$msg="Database successfully updated";}else{$msg="file size exceed";}}}

else{

$msg="not valid image";}}?>

Page 450: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Working with GD library

• File types with GD and PHP

• Compiling PHP with GD

• Creating the image table

• Uploading the image

Summary

Page 451: PHP Presentation

Chapter - 7Introduction to

MySQL

Page 452: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

7.1 MySQL structure and syntax7.2 Types of MySQL tables and storage engine7.3 MySQL commands7.4 Integration of PHP with MySQL7.5 Connection to the MySQL server7.6 Working with PHP and arrays of data7.7 Referencing two tables7.8 Joining two tables

7 Introduction to MySQL• This unit covers….

Page 453: PHP Presentation

7.1 MySQL structure

and syntax

Developed By: Amit Lakhani, TFGP Adipur

Page 454: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.• In computing, databases are sometimes classified according to their organizational approach.•The most prevalent approach is the relational database, a tabular database in which data is defined so that it can be reorganized and accessed in a number of different ways.• In RDBMS the data is stored in different tables and relations are established using primary keys and foreign keys.

What is Database?

Page 455: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• A RDBMS is software that:• Enables you to implement a database with tables,

columns and indices.• Guarantees the referential integrity between rows

of various tables.• Update the indices automatically.• Interprets an SQL query.

What is Database? Conti…

Page 456: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Before we proceed to explain MySQL database system, lets revise few definitions related to database.

• Database: A database is a collection of tables, with related data. • Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet. • Column: One column (data element) contains data of one and the same kind, for example the column ID.

RDBMS Terminology

Page 457: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Row: A row (= tuple, entry or record) is a group of related data, for example the data of one subscription. • Redundancy: Storing data twice, redundantly to make the system faster. • Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key you can find at most one row. • Foreign Key: A foreign key is the linking pin between two tables.

RDBMS Terminology conti…

Page 458: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique. • Index: An index in a database resembles an index at the back of a book. • Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row.

RDBMS Terminology conti…

Page 459: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• SQL stands for Structured Query Language

• SQL lets you access and manipulate databases

• SQL is an ANSI (American National Standards Institute) standard

• SQL can execute queries against a database

• SQL can retrieve data from a database

• SQL can insert, update and delete records in a database

Introduction to SQL

Page 460: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• SQL can create new databases

• SQL can create new tables in a database

• SQL can create stored procedures in a database

• SQL can create views in a database

• SQL can set permissions on tables, procedures, and views

Introduction to SQL conti…

Page 461: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL is an open-source database system with which we can do the following things:

• design the structure of the tables (called schema) and how they relate to one another • add, edit and delete data • sort and manipulate data • query the database (that is, ask questions about the data) • produce listings based on queries

Introduction to MySQL

Page 462: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

To interact with MySQL, we enter commands on a command line. These commands, such as CREATE, INSERT, UPDATE, etc. are based on a more general language called SQL (Structured Query Language).

Introduction to MySQL conti…

Page 463: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

1. Scalability and Flexibility:The MySQL database server provides the Ultimate in scalability, sporting the capacity to handle deeply embedded applications with a massive data warehouses holding terabytes of information. the open source nature of MySQL allows complete customization for those wanting to add unique requirements to the database server. 2. High Performance:

A unique storage-engine architecture allows database professionals to configure the MySQL database server specifically for particular applications

Uses of MySQL

Page 464: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Uses of MySQL conti…3. High Availability

MySQL offers a variety of high-availability Options from high-speed master/slave replication configurations, to specialized Cluster servers offering instant failover, to third party vendors offering unique high-availability solutions for the MySQL database server. 4. Robust Transactional Support

MySQL offers one of the most powerful transactional database engines on the market. Features include complete ACID (atomic, consistent,isolated, durable) transaction support,

Page 465: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

5. Web and Data Warehouse StrengthsMySQL is the de-facto standard for high-traffic

web sites because of its high-performance query engine, tremendously fast data insert capability, and strong support for specialized web functions like fast full text searches. 6. Strong Data Protection

Because guarding the data assets of corporations is the number one job of database professionals, MySQL offers exceptional security features that ensure absolute data protection.

Uses of MySQL conti…

Page 466: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

7. Comprehensive Application DevelopmentOne of the reasons MySQL is the world's most

popular open source database is that it provides comprehensive support for every application development need. Within the database, support can be found for stored procedures, triggers, functions, views, cursors, ANSI-standard SQL, and more. 8. Management Ease

MySQL offers exceptional quick-start capability with the average time from software download to installation completion being less than fifteen minutes. This rule holds true whether the platform is Microsoft Windows, Linux, Macintosh, or UNIX.

Uses of MySQL conti…

Page 467: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

9. Open Source Freedom and 24 x 7 Support Many corporations are hesitant to fully commit

to open source software because they believe they can't get the type of support or professional service safety nets they currently rely on with proprietary software to ensure the overall success of their key applications. 10. Lowest Total Cost of Ownership

By migrating current database-drive applications to MySQL, or using MySQL for new development projects, corporations are realizing cost savings that many times stretch into seven figures.

Uses of MySQL conti…

Page 468: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Relational Database System: MySQL is a relational database system.• Client/Server Architecture: MySQL is a client/server system. There is a database server (MySQL) and arbitrarily many clients (application programs), which communicate with the server; that is, they query data, save changes, etc. The clients can run on the same computer as the server or on another computer (communication via a local network or the Internet).• SQL compatibility: MySQL supports as its database language -- as its name suggests – SQL (Structured Query Language).

Features of MySQL

Page 469: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• User interface: There are a number of convenient user interfaces for administering a MySQL server.• Full-text search: Full-text search simplifies and accelerates the search for words that are located within a text field.• Replication: Replication allows the contents of a database to be copied (replicated) onto a number of computers.• Transactions: In the context of a database system, a transaction means the execution of several database operations as a block. The database system ensures that either all of the operations are correctly executed or none of them.

Features of MySQL conti..

Page 470: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Foreign key constraints: These are rules that ensure that there are no cross references in linked tables that lead to nowhere. MySQL supports foreign key constraints for InnoDB tables.• Programming languages: There are quite a number of APIs (application programming interfaces) and libraries for the development of MySQL application.• ODBC: MySQL supports the ODBC interface Connector/ODBC. This allows MySQL to be addressed by all the usual programming languages that run under Microsoft Windows (Delphi, Visual Basic, etc.).

Features of MySQL conti..

Page 471: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Platform independence: It is not only client applications that run under a variety of operating systems; MySQL itself (that is, the server) can be executed under a number of operating systems.• Speed: MySQL is considered a very fast database program. This speed has been backed up by a large number of benchmark tests

Features of MySQL conti..

Page 472: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL Architecture

Page 473: PHP Presentation

7.2Types of MySQL tables

and storage engine

Developed By: Amit Lakhani, TFGP Adipur

Page 474: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL supports various of table types or storage engines to allow you to optimize your database. The table types are available in MySQL are:

• ISAM

• MyISAM

• InnoDB

MySQL table types and storage engine

• BerkeleyDB (BDB)

• MERGE

• HEAP

Page 475: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• The most important feature to make all the table types above distinction is transaction-safe or not.

• Only InnoDB and BDB tables are transaction safe and only MyISAM tables support full-text indexing and searching feature.

• MyISAM is also the default table type when you create table without declaring which storage engine to use.

MySQL table types and storage engine conti..

Page 476: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Here are some major features of each table types:• ISAM-ISAM had been deprecated and removed from version 5.x. All of its functionality entire replace by MyISAM. ISAM table has a hard disk size 4GB and is not portable. •MyISAM-MyISAM table type is default when you create table. MyISAM table work very fast but not transaction-safe. The size of MyISAM table depends on the operating system and the data file are portable from system to system. With MyISAM table type, you can have 64 keys per table and maximum key length of 1024 bytes.

Features of MySQL table types

Page 477: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Here are some major features of each table types:• InnoDB-Different from MyISAM table type, InnoDB table are transaction safe and supports row-level locking. Foreign keys are supported in InnoDB tables. The data file of InnoDB table can be stored in more than one file so the size of table depends on the disk space. Like the MyISAM table type, data file of InnoDB is portable from system to system. The disadvantage of InnoDB in comparison with MyISAM is it take more disk space.• BDB-BDB is similar to InnoDB in transaction safe. It supports page level locking but data file are not portable.

Features of MySQL table types conti..

Page 478: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Here are some major features of each table types:

• MERGE-Merge table type is added to treat multiple MyISAM tables as a single table so it remove the size limitation from MyISAM tables.

• HEAP-Heap table is stored in memory so it is the fastest one. Because of storage mechanism, the data will be lost when the power failure and sometime it can cause the server run out of memory. Heap tables do not support columns with AUTO_INCREMENT, BLOB and TEXT characteristics.

Features of MySQL table types conti..

Page 479: PHP Presentation

MySQL Data Types

Developed By: Amit Lakhani, TFGP Adipur

Page 480: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL provides you many more specific data types than just "numeric" or "string". Each data type in MySQL can be determined by the following characteristics:

• What kind of value it can represent.• The space values take up and whether the

values are fixed-length or variable-length.• The values of a data type can be indexed.• How MySQL compare values of that data

types.

MySQL Data Types

Page 481: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Numeric Data Types

You can find all SQL standard numeric types in MySQL including exact number data type and approximate numeric data types including integer, fixed-point and floating point. In addtion, MySQL also supports BIT data type for storing bit field values. Numeric types can be signed or unsigned except BIT type.

MySQL Data Types conti…

Page 482: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL Data Types (Numeric)Numeric Types DescriptionTINYINT A very small integerSMALLINT A small integerMEDIUMINT A medium-sized integerINT A standard integerBIGINT A large integerDECIMAL A fixed-point number

FLOAT A single-precision floating-point number

DOUBLE A double-precision floating-point number

BIT A bit field

Page 483: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• String Data Types

In MySQL, string can hold anything from plain text to binary data such as images and files. String can be compared and searched based on pattern matching by using LIKE clause or regular expression.

MySQL Data Types conti…

Page 484: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL Data Types (String)String Types DescriptionCHAR A fixed-length non-binary (character) stringVARCHAR A variable-length non-binary stringBINARY A fixed-length binary stringVARBINARY A variable-length binary stringTINYBLOB A very small BLOB (binary large object)BLOB A small BLOBMEDIUMBLOB A medium-sized BLOBLONGBLOB A large BLOBTINYTEXT A very small non-binary stringTEXT A small non-binary stringMEDIUMTEXT A medium-sized non-binary stringLONGTEXT A large non-binary string

ENUM An enumeration; each column value may be assigned one enumeration member

SET A set; each column value may be assigned zero or more set members

Page 485: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Date and Time Data Types

MySQL provides types for date and time and combination of date and time. In addition, MySQL also provide timestamp data type for tracking last change on a record. If you just want to store the year without date and month, you can use YEAR data type.

MySQL Data Types conti…

Page 486: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL Data Types (Date and Time)Date and Time Types Description

DATE A date value in 'CCYY-MM-DD' format

TIME A time value in 'hh:mm:ss' format

DATETIMEA date and time value in 'CCYY-MM-DD hh:mm:ss' format

TIMESTAMP A timestamp value in 'CCYY-MM-DD hh:mm:ss' format

YEAR A year value in CCYY or YY format

Page 487: PHP Presentation

7.3MySQL Commands

Developed By: Amit Lakhani, TFGP Adipur

Page 488: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

MySQL Commands

• CREATE-create databases and tables

• SELECT-select table rows based on certain conditions

• DELETE- delete one or more rows of a table

• INSERT- insert a new row in a table

• UPDATE- update rows in a table

• ALTER- alter the structure of a table

Page 489: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Commands to login to MySQL consoleClick on wampserver -> MySQL -> MySQL console

Enter password

Command line

Page 490: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Login using phpMyAdminClick on wampserver -> phpMyAdmin

Page 491: PHP Presentation

7.4Integration of PHP

With MySQL

Developed By: Amit Lakhani, TFGP Adipur

Page 492: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Integration of PHP with MySQLTo connect to the database one should implement the following steps:

• Connecting to a Database server• Create new database• Select MySQL database• Fetch and show tables and records of database• Execute queries though PHP script• Manipulate records, tables and database• Error handling• Closing connection

Page 493: PHP Presentation

7.5Connection to MySQL server

Developed By: Amit Lakhani, TFGP Adipur

Page 494: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Connecting to database• Before you can access data in a database, you must create a connection to the database.

Syntax: mysql_connect(servername,username,password);

Parameter Descriptionservername Optional. Specifies the server to connect to.

Default value is "localhost:3306"username Optional. Specifies the username to log in with.

Default value is the name of the user that owns the server process

password Optional. Specifies the password to log in with. Default is ""

Page 495: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Connecting to database example

<?php$con = mysql_connect("localhost",”root",”");if (!$con) { die('Could not connect: ' . mysql_error()); } echo “Database connection successed”;// some codemysql_close($con); ?>

$con object stores the connectionstring

Closing connection

Page 496: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• To get PHP to execute the statement we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.• Syntax:

mysql_query(query, link)

Parameter Description query Required. SQL query to create or delete

database. link Optional. If not specified last opened connection

will be used

Creating database using PHP script

Page 497: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating database using PHP script<?php$con = mysql_connect("localhost","peter","abc123");$sql=“CREATE DATABASE sample”;if (!$con) { die('Could not connect: ' . mysql_error()); }if(mysql_query($sql,$con)) { echo "Database created"; }mysql_close($con);?>

Get the query

Query Connection string

Page 498: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• PHP provides mysql_select_db() function to select a database. It returns TRUE on success and FALSE on failure.• Syntax:

mysql_select_db(db_name, connection)

Parameter Description db_name Required. MySQL database name to be selected connection Optional. If not specified last opened connection

will be used

Selecting database using PHP script

Page 499: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Selecting database using PHP script <?php$con = mysql_connect("localhost","peter","abc123");if (!$con) { die('Could not connect: ' . mysql_error()); }if(mysql_query("CREATE DATABASE sample",$con)) { echo "Database created"; }mysql_select_db(‘sample’,$con);mysql_close($con);?>

Database name

Connection string

Page 500: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Drop database using PHP script <?php$con = mysql_connect("localhost","peter","abc123");if (!$con) { die('Could not connect: ' . mysql_error()); }if(mysql_query(“DROP DATABASE sample",$con)) { echo "Database Deleted successfully"; }mysql_close($con);?>

Page 501: PHP Presentation

7.6Working with PHP and

Array of data

Developed By: Amit Lakhani, TFGP Adipur

Page 502: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• The following functions are used to display the selected data correctly in PHP which you can use to retrieve data from MySQL database result set.

• mysql_fetch_assoc()- fetch a result row in an associative array.

• mysql_fetch_row()- fetch a result row in an enumerated array.

• mysql_fetch_array()- fetch a result row in an associative or numeric or

both array. The functions returns only one record.

Working with array of data

Page 503: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$link=mysql_connect(“localhost”,”root”,””);mysql_select_db($db,$link);$sql="SELECT name,age FROM persondetail";$result=mysql_query($sql,$link);while($rowarray=mysql_fetch_array($result))

{echo ($rowarray['name']);echo ($rowarray['age']);}mysql_close($link);

?>

Mysql_fetch_array() function

Page 504: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Mysql_fetch_array() function conti..

Page 505: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$link=mysql_connect(“localhost”,”root”,””);mysql_select_db($db,$link);$sql="SELECT name,age FROM persondetail";$result=mysql_query($sql,$link);while($rowarray=mysql_fetch_row($result))

{echo ($rowarray[0]);echo ($rowarray[1]);}mysql_close($link);

?>

Mysql_fetch_row() function

Page 506: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Mysql_fetch_row() function

Page 507: PHP Presentation

7.7Referencing two table

Developed By: Amit Lakhani, TFGP Adipur

Page 508: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• To get information from more than one table reference the individual table in query and link them temporarily through a common field. • formally JOIN the individual tables in query.

Referencing two tables

Page 509: PHP Presentation

7.8Joining two tables

Developed By: Amit Lakhani, TFGP Adipur

Page 510: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• One of the great characteristics of SQL is the fact that one can develop access and modify data across various table.

• A join command unites some or all of the data from two or more tables into one set. The joining capability allows creating small, compact relational tables that can influence database performance.

Joining two tables

Page 511: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• One can use one of the following JOINS:

• Cross join• Equi-Join• Non equi join• The right join• The full join• Self join

Joining two tables

Page 512: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• MySQL structure and syntax• Types of MySQL tables and storage engine• MySQL commands• Integration of PHP with MySQL• Connection to the MySQL server• Working with PHP and arrays of data• Referencing two tables• Joining two tables

Summary

Page 513: PHP Presentation

Chapter - 8Working with

database

Page 514: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

8.1 Creating a table8.2 Manipulating the table

8.2.1 Filling the table with data8.2.2 Adding links to the table8.2.3 Adding data the table8.2.4 Displaying information8.2.5 Displaying the movie detail

8.3 Editing the database8.4 Inserting record8.5 Deleting record8.6 Editing data

Working with database• This unit covers….

Page 515: PHP Presentation

8.1Creating table

Developed By: Amit Lakhani, TFGP Adipur

Page 516: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating database

WAMPSERVER in Quick launch bar

Click on WAMPSERVER->localhost

Page 517: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating database

List of database Write database name here and click on create

Page 518: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating table

List of database Write table nameAnd no. of fieldhere and click on Go

Page 519: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating fields

Write field nameAnd its attributeshere and click on save or Go

Page 520: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Inserting values

Click insert tab, Insert values here and click on Go

Page 521: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Displaying records

Display inserted record

Query executed

Page 522: PHP Presentation

Creating database And

Table Using PHP

Developed By: Amit Lakhani, TFGP Adipur

Page 523: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating database using PHP<?php$con = mysql_connect("localhost","root“,””);if (!$con) { die('Could not connect: ' . mysql_error()); }if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; }else { echo "Error creating database: " mysql_error(); }?>

Create database

Page 524: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Creating table using PHP<?php$con = mysql_connect("localhost","root");if (!$con) { die('Could not connect: ' . mysql_error()); }if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; }else { echo "Error creating database: " . mysql_error(); }

mysql_select_db("my_db", $con);$sql = "CREATE TABLE Persons(FirstName varchar(15),LastName varchar(15),Age int)";mysql_query($sql,$con);mysql_close($con);?>

Create table

Page 525: PHP Presentation

8.2Manipulating the

table

Developed By: Amit Lakhani, TFGP Adipur

Page 526: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Inserting record

• Deleting record

• Updating data

• Searching record

Manipulating table

• We can perform various operations on table like:

Page 527: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$con = mysql_connect("localhost","root");if (!$con){die('Could not connect: ' . mysql_error());}

mysql_select_db("my_db", $con);mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')");mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')");echo"Data added successfully<br>";$numrows=mysql_affected_rows($con);echo "Numbers of rows affected:".$numrows;mysql_close($con);?>

Inserting records

Insert record

Page 528: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$con = mysql_connect("localhost","root");if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("my_db", $con);mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");echo "Data deleted successfully<br>";$numrows=mysql_affected_rows($con);echo "Numbers of rows affected:".$numrows;mysql_close($con);?>

Deleting record

delete record

Page 529: PHP Presentation

8.2.1Filling/Inserting

data using forms

Developed By: Amit Lakhani, TFGP Adipur

Page 530: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Filling data using forms

Page 531: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Filling data using forms code<html><body><form action=“mysql_form_input.php" method="post" ><table><tr><td>Roll No:</td><td><input type="text" name="rollno" /></td></tr><tr><td>Name:</td><td><input type="text" name="name" /></td></tr><tr><td>Address:</td><td><textarea name="add"> </textarea></td></tr><tr><td>Contact_No: </td><td><input type="text" name="phone" /></td></tr><tr><td colspan="2" align="center"><input type="submit" value="Submit“ name="btnsave" /></td></tr></form></body></html>

Mysql_form_input.php is called when button is clicked

Page 532: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Insert data using forms <?phpif($_POST['btn']=="Save"){

$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$rollno=$_POST['rollno'];$name=$_POST['name'];$address=$_POST['add'];$phoneno=$_POST['phone'];$sql="INSERT INTO stu_entry (Roll_no,Name,Address,phone_no)VALUES('$rollno','$name','$address','$phoneno')";if(mysql_query($sql,$con)){echo"Data added successfully<br>";$numrows=mysql_affected_rows($con);echo "Numbers of rows affected:".$numrows;}else{die("could not insert:".mysql_error());}mysql_close($con);}}

mysql_form_input.php

Data is inserted in table

Page 533: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Insert data using forms output

Enter records

Press submit

Inserts one record to database

Page 534: PHP Presentation

8.2.2Adding links to the

table

Developed By: Amit Lakhani, TFGP Adipur

Page 535: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Display records as links<?php$con = mysql_connect("localhost","root","");if ($con){

mysql_select_db("student_info", $con);$result=mysql_query("SELECT * FROM stu_entry ");echo "Click to get details";if(mysql_num_rows($result)>0){

echo "<table border=1><tr><th>Rollno</th></tr>";while($row=mysql_fetch_row($result)){

echo "<tr>";echo "<td><a href=\"table_detail_link.php? id={$row

[0]}\">" .$row[0]."</a></td>";echo "</tr>";

}echo "</table>";

}mysql_close($con);}?>

Creates link to Table_detail_link.php

mysql_table_link.php

Page 536: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Display records as links conti..<?php$con = mysql_connect("localhost","root","");if ($con){

mysql_select_db("student_info", $con);$rno=$_REQUEST['id'];$result=mysql_query("SELECT * FROM stu_entry WHERE Roll_no LIKE '%$rno'");echo "<table border=1><tr><th>Rollno</th><th>Name</th><th>Address</th><th>Contact_No</th></tr>";while($row=mysql_fetch_row($result)){

echo "<tr>";echo "<td>" .$row[0]."</td>";echo "<td>" .$row[1]."</td>";echo "<td>" .$row[2]."</td>";echo "<td>" .$row[3]."</td>";echo "</tr>";

}echo "</table>";

}mysql_close($con);?>

Displays clicked record

Table_detail_link.php

Select linked field

Page 537: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Display record as links output

Click on the linkAnd it will displayClicked record

Page 538: PHP Presentation

8.2.3Adding to the table

Developed By: Amit Lakhani, TFGP Adipur

Page 539: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Insert data using forms <?phpif($_POST['btn']=="Save"){

$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$rollno=$_POST['rollno'];$name=$_POST['name'];$address=$_POST['add'];$phoneno=$_POST['phone'];$sql="INSERT INTO stu_entry (Roll_no,Name,Address,phone_no)VALUES('$rollno','$name','$address','$phoneno')";if(mysql_query($sql,$con)){echo"Data added successfully<br>";$numrows=mysql_affected_rows($con);echo "Numbers of rows affected:".$numrows;}else{die("could not insert:".mysql_error());}mysql_close($con);}}

mysql_form_input.php

Data is inserted in table

Page 540: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Insert data using forms output

Enter records

Press submit

Inserts one record to database

Page 541: PHP Presentation

8.2.4Display new information

Developed By: Amit Lakhani, TFGP Adipur

Page 542: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Display data using forms if($_POST['btn']=="Display"){

$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$result=mysql_query("SELECT * FROM stu_entry");echo "<table border=1><tr><th>Roll no</th><th>Name</th> <th>Address</th><th>Contact_No</th></tr>";while($row=mysql_fetch_row($result)){echo "<tr>";echo "<td>" .$row[0]."</td>";echo "<td>" .$row[1]."</td>";echo "<td>" .$row[2]."</td>";echo "<td>" .$row[3]."</td>";echo "</tr>";}echo "</table>";mysql_close($con);}

}

mysql_form_input.php

Data is selected andDisplayed in table

Page 543: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Display data using forms

Display all recordsWhen display is clicked

Page 544: PHP Presentation

Searching data using forms

Developed By: Amit Lakhani, TFGP Adipur

Page 545: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Searching data using forms

<?phpif($_POST['btn']=="Search"){$con = mysql_connect("localhost", "root","");if ($con){mysql_select_db("student_info", $con);$rollno=$_POST['rollno'];$name=$_POST['name'];$address=$_POST['add'];$phoneno=$_POST['phone'];

Data is selected andDisplayed in table

if($_POST['rollno']==$rollno){$result=mysql_query("SELECT * FROM stu_entry WHERE Roll_no LIKE '%$rollno'");if(mysql_num_rows($result)>0){echo "<table border=1><tr><th>Roll no</th><th>Name</th> <th>Address</th> <th>Contact_No</th></tr>";while($row=mysql_fetch_row($result)){echo "<tr>";echo "<td>" .$row[0]."</td>";echo "<td>" .$row[1]."</td>";echo "<td>" .$row[2]."</td>";echo "<td>" .$row[3]."</td>";echo "</tr>";}echo "</table>“;}

Page 546: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Search data using forms output

Press search

Enter roll no. to search

It displays selected record

Page 547: PHP Presentation

8.3Edit the database

Developed By: Amit Lakhani, TFGP Adipur

Page 548: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Edit records from the table

Page 549: PHP Presentation

Edit records from the table<?php$con = mysql_connect("localhost","root","");if ($con){

mysql_select_db("student_info", $con);$result=mysql_query("SELECT * FROM stu_entry ");echo "Click to Edit details";if(mysql_num_rows($result)>0){

echo "<table border=1><tr><th>Rollno</th><th>Name</th> <th>Address</th> <th>Phone_no</th> </tr>";while($row=mysql_fetch_row($result)){

echo "<tr>";echo "<td><a href=\"mysql_edit_detail.php? id={$row

[0]}\">" .$row[0]."</a></td>";echo "<td>" .$row[1]."</td>";echo "<td>" .$row[2]."</td>";echo "<td>" .$row[3]."</td>";echo "</tr>";

}echo "</table>“;mysql_close($con);}?>

Mysql_edit.php

Page 550: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Click on the linkAnd it will displayClicked record on Other page

Edit records from the table conti..Mysql_edit.php

Page 551: PHP Presentation

Edit records from the table conti..<?php$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$rno=$_REQUEST['id'];$result=mysql_query("SELECT * FROM stu_entry WHERE Roll_no LIKE '%$rno'");while($row=mysql_fetch_row($result));{echo "<form action=\"mysql_save_detail.php\" method=\"post\">";echo “Roll No:<input type=\"text\" name=\"rollno\" value={$row[0]}>";echo “Name:<input type=\"text\" name=\"name\" value={$row[1]}>";echo “Address:<textarea name=\"add\" rows=\"5\" cols=\"20\">" .$row[2]. "</textarea>";echo “Phone No:<input type=\"text\" name=\"phoneno\" value={$row[3]}>";echo “<input type=\"submit\" name=\"btn\" value=\"Save\“>";echo "</form>";

}}mysql_close($con);?>

Mysql_edit_detail.php

Developed By: Amit Lakhani, TFGP Adipur

Page 552: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

update with new Entries and click on Save button and form will call mysql_save_detail.phppage

Edit records from the table conti..Mysql_edit_detail.php

Page 553: PHP Presentation

Edit records from the table conti..<?phpif(isset($_POST['btn'])){

$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$rno=$_POST['rollno'];$name=$_POST['name'];$add=$_POST['add'];$phno=$_POST['phoneno'];$update= "UPDATE stu_entry SET Roll_no='$rno', Name='$name', Address='$add', phone_no='$phno' WHERE Roll_no LIKE '%$rno%'";if(mysql_query($update,$con)){

echo "Records updated successfully";}mysql_close($con);

}}

Mysql_save_detail.php

Developed By: Amit Lakhani, TFGP Adipur

Page 554: PHP Presentation

8.4Inserting record

Developed By: Amit Lakhani, TFGP Adipur

Page 555: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

<?php$con = mysql_connect("localhost","root");if (!$con){die('Could not connect: ' . mysql_error());}

mysql_select_db("my_db", $con);mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')");mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')");echo"Data added successfully<br>";$numrows=mysql_affected_rows($con);echo "Numbers of rows affected:".$numrows;mysql_close($con);?>

Inserting records

Insert record

Page 556: PHP Presentation

8.5Delete records from the table

Developed By: Amit Lakhani, TFGP Adipur

Page 557: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

Delete records from the table

Page 558: PHP Presentation

Delete records from the table conti..<?php$con = mysql_connect("localhost","root","");if ($con){mysql_select_db("student_info", $con);$result=mysql_query("SELECT * FROM stu_entry ");echo "Click to Delete Records";if(mysql_num_rows($result)>0){echo "<table border=1><tr><th>Rollno</th><th>Name</th> <th>Address</th> <th>Phone_no</th> </tr>";while($row=mysql_fetch_row($result)){

echo "<tr>";echo "<td><a href=\"delete_record.php? id={$row[0]}\">"

.$row[0]."</a></td>“;echo "<td>" .$row[1]."</td>";echo "<td>" .$row[2]."</td>";echo "<td>" .$row[3]."</td>";echo "</tr>";

}

Mysql_delete.php

Page 559: PHP Presentation

Delete records from the table conti..

echo "<td colspan=4><a href=\"delete_record.php?id=All\">Delete

All</a></td>";echo "</tr>";echo "</table>";

} else {

echo "<br>Table is empty"; }

mysql_close($con);}

?>

Mysql_delete.php

Developed By: Amit Lakhani, TFGP Adipur

Page 560: PHP Presentation

Delete records from the table conti..<?php$con = mysql_connect("localhost","root","");if ($con){

mysql_select_db("student_info", $con);$deletereq=$_REQUEST['id'];if($deletereq=="All"){

$delete="DELETE FROM stu_entry";}else{

$delete="DELETE FROM stu_entry WHERE Roll_no LIKE '%$deletereq%'";}if(mysql_query($delete, $con)){

echo "Record(s) deleted successfully";}

mysql_close($con);}?>

Delete_record.php

Developed By: Amit Lakhani, TFGP Adipur

Page 561: PHP Presentation

Developed By: Amit Lakhani, TFGP Adipur

• Creating a table• Manipulating the table

• Filling the table with data• Adding links to the table• Adding data the table• Displaying information• Displaying the movie detail

• Editing the database• Inserting record• Deleting record• Editing data

Summary


Recommended