Download Workshop Lecture

157
Web Development Workshop May 24-25, 2008 Presenter: Md. Mahbubul Islam Lecturer Dept. of Computer Science and Engineering, University of Rajshahi. Organized By: Web Club, CSE, RU

Transcript of Download Workshop Lecture

Page 1: Download Workshop Lecture

Web Development WorkshopMay 24-25, 2008

Presenter: Md. Mahbubul Islam

LecturerDept. of Computer Science and Engineering,

University of Rajshahi.

Organized By:

Web Club, CSE, RU

Page 2: Download Workshop Lecture

Web Development Workshop 2

Course Outline (Day1)

• WWW Basic• HTML Basic• Introduction to PHP• Why use PHP• Data Types• Constants• Expressions• Arrays• Control Structures• PHP functions• Intro to HTML Forms• PHP Configuration• PHP Cookies

and Sessions

• String Manipulation• Sending email• File Handling• Handling file uploads• Introduction To Database• MySQL Introduction• Basic MySQL Operations• Accessing MySQL• Graphics in PHP• Tricks and Tips

Page 3: Download Workshop Lecture

Web Development Workshop 3

Course Outline (Day2)

• Using Dreamweaver• Using FTP Software• Using Hosting Cpanel• Using PHPMyAdmin• Developing a data driven dynamic

web site.

Page 4: Download Workshop Lecture

Web Development Workshop 4

Tools and Language

• Macromedia Dreamweaver8.0

• Adobe Photoshop• HTML• PHP• MySQL• Apache• Cute FTP

• CSS• Java Script• Coffee Cup Menu

Builder

XAMPP

Page 5: Download Workshop Lecture

Web Development Workshop 5

History of the WWW

• Issues that drove development of the Web– No transparent way to link documents or objects

• References by citation or ftp address

– No automatic way to retrieve linked documents• Downloading via ftp required human intervention

– No standard document format• Each format required its own application

– Even with links, no way to find documents• except by being told where to find them, following

links

Page 6: Download Workshop Lecture

Web Development Workshop 6

History of the WWW

• Web beginnings– 1989: Tim Berners-Lee

• URLs, http, first browser– 1993: NCSA Mosaic

• Then Netscape, then Mozilla– 1994: World Wide Web Consortium

• http://w3.org/• Standards organization for Web protocols and

formats– 1994-5: Web crawlers and search engines

• WebCrawler, Lycos, AltaVista, Yahoo

Page 7: Download Workshop Lecture

Web Development Workshop 7

World Wide Web

• World Wide Web (WWW) is a collection of servers (subset of Internet computers) and the info they give access to using the HTTP protocol– WWW is not the same as the Internet– The “server” is a web site computer and the “client” is

a web browser (like Internet Explorer)– Many Web server’s domain names begin with www by

tradition, but any name is OK– Often multiple servers map to the same site:

yahoo.com and www.yahoo.com

Page 8: Download Workshop Lecture

Web Development Workshop 8

Essential Components of WWW

• URL -- uniform resource locator – Strings of characters represent generalized addresses that may contain

instructions for accessing the identified resource– http://www.ru.ac.bd is used to identify the RU homepage

• HTTP -- hypertext transfer protocol– Conventions that regulate the communication between a browser (web

user agent) and a server

• HTML -- hypertext markup language– Conceptual mappings to concrete or abstract entities.– ex: website (web pages and other kinds of files)– Other Resources..

Page 9: Download Workshop Lecture

Web Development Workshop 9

Client/Server Interaction

• For Web pages, the client requests a page the server returns it: there’s no permanent connection, just a short conversation– Details of the conversation are specified by HTTP

Client

Server Client

ClientClient

Client

Client Client

Server

Client

ServerServer

Server

ServerServer

Serverrequest

response

Page 10: Download Workshop Lecture

Web Development Workshop 10

Markup Language - HTML

• HyperText Markup Language– a language for describing the content and

presentation of a web page• content: The meaning and structure of the web page• presentation: How the page is to be presented

– HTML pages have a basic hierarchical structure defined by the tags

• <html>, <head>, <body>, and so on

– Basic HTML describes a static page• once parsed and rendered, the page doesn’t change• hyperlinking was the big step forward in basic HTML

Page 11: Download Workshop Lecture

Web Development Workshop 11

HTML Functionalities

• HTML gives authors the means to:• Publish online documents with headings, text,

tables, lists, photos, etc– Include spread-sheets, video clips, sound clips, and other

applications directly in their documents

• Link information via hypertext links, at the click of a button

• Design forms for conducting transactions with remote services, for use in searching for information, making reservations, ordering products, etc

Page 12: Download Workshop Lecture

Web Development Workshop 12

Accessing HTML Files

Note: The file is just

retrieved no code is executed on server

Note2: HTML tags

interpreted on client by browser.

http protocolYour PC

(Internet connected)Web Server

(Internet connected)

URL:www.myserver.com/funstuff.html

Web browser

Find Web server at www.myserver.comWeb server receives

request

Sends file withfunstuff.html

The file funstuff.htmlHere are some funthings to do:

1. Play baseball.2. Go swimming.3. Go to a concert.

Web browser

Page 13: Download Workshop Lecture

Web Development Workshop 13

Basic HTML

• HTML uses tags to specify the formatting– The tags are not displayed in the browser, they tell the browser how to

display the document– Tags in HTML appear as angle brackets:

<the tag format>– Each Tag needs to have an end:

</the tag format>– Tags can be used to apply formatting to individual words, sentences,

paragraphs or the whole HTML page

<center><u> This is a sample <b>HTML</b> line formatted</u></center>

Is displayed in the internet browser as the following:

This is a sample HTML line formatted

Page 14: Download Workshop Lecture

Web Development Workshop 14

Basic HTML

• Important Points1. All file names need to be in the correct case (html page names, image

names etc), – Cars.html is treated differently than cars.html– Myphoto.jpg is treated differently than myphoto.jpg

– Page names should be meaningful not just Noname.html or page1.html– Don’t use a whitespace character in the file name like ‘my page.html’

use an underscore instead like ‘my_page.html’ – Acceptable Characters: (A-Z) (a-z)(0-9) or _ .

1. First pages of a website need to be called index.html

2. HTML TAGS use American spelling like color not colour

Page 15: Download Workshop Lecture

Web Development Workshop 15

Basic HTML Page

<HTML><HEAD><TITLE> </TITLE>

</HEAD>

<BODY>

</BODY></HTML>

All HTML pages require the following basic structured tags

The text is added here

These tags must appear at the end of the HTML page

These basic structured tags should only appear once per HTML pagei.e: only one <body> tag and one </body> tag etc

Page 16: Download Workshop Lecture

Web Development Workshop 16

Basic HTML Page

<HTML><HEAD><TITLE> My Dublin Homepage </TITLE>

</HEAD>

<BODY>Dublin is a city......<center><u> This is a sample <b>HTML</b> line formatted</u></center>

</BODY></HTML>

Page 17: Download Workshop Lecture

Web Development Workshop 17

HTML Formatting

• Font Formatting– To bold text the following tag is used: <B> … </B>– To underline text use the following: <U> … </U>– To italics text: <I> …. </I>

• The size, colour and font face type can also be modified<FONT SIZE="7" COLOR="#FF0000" FACE=""> The font test </FONT>

HTML 4.0: <font style="font-family:verdana;font-size:60;color:#660000">

This is the text </font>Some Acceptable fontscourier, courier newcomic sans msarial, garamond verdana

Some Acceptable ColoursRed, green, blue, yellow, orange….

Specific codes can also be used for colour:#FFFFFF= white#000000=black#FF0000=red#808080=Navy

Page 18: Download Workshop Lecture

Web Development Workshop 18

HTML Formatting

• Text Formatting– To move text onto a new line use <BR>– To start a new paragraph use <P>– To add more than one white space character use the

following: &nbsp;

– To add a line separating text use <HR> or <HR color="#330000" width="80%">

Unordered List (bullet points)<UL>

<LI>Part 1 <BR><LI>Part 2 <BR><LI> Part 3 <BR>

</UL>

Ordered List (Numbers)<OL>

<LI>Part 1 <BR><LI>Part 2 <BR><LI> Part 3 <BR>

</OL>

Page 19: Download Workshop Lecture

Web Development Workshop 19

HTML Formatting

• Hyperlinking Webpages:– External page:

<a href="http://www.google.ie" > Link to google </a>– Internal page:

<a href="MyPage.html" > MyPage </a>– Linking within page: <a href="#C4"> Images </a> (Link)

• Section to link to: <a name="C4"><h2>Chapter 4</h2></a>

• Inserting an Image:– Using an Image as a link:

<IMG SRC=“picture.jpg" WIDTH="2272" HEIGHT="1704" BORDER="0" ALT="text">

– Using an Image as a link:<a href=“nextpage.html"><img border="0" src="nextpage.jpg" width="65" height="38"></a>

Page 20: Download Workshop Lecture

Web Development Workshop 20

HTML Background

• Modifying Background Colour– Instead of <BODY> use: <BODY bgcolor="#FFFF99" >

– The Colour of hyperlinks can also be modified:<BODY bgcolor="#FFFF99" link="#330000"

alink="#330000" vlink="#330000" >

• Embedding video, shockwave flash…<embed width=100 height=168

pluginspage="http://quicktime.apple.com/" src="2002.mpg" width=192 loop="true" controller="true" autoplay="true"></embed>

Page 21: Download Workshop Lecture

Web Development Workshop 21

HTML Tables

• Tables in HTML consist ‘cells’ of rows and columns – Very important method of formatting– A Table of one row two columns could place an image in one cell and text

in the other…– Things can get very complicated like tables within tables

<table border="1" bordercolor="#330000"cellpadding="10"><tr> <td bgcolor="#FF3300" width="300">First</td> <td>Row</td></tr> <tr> <td>Second</td> <td>Row</td></tr></table>

Page 22: Download Workshop Lecture

Web Development Workshop 22

Worried about HTML code?

• Use Editor like – Dreamweaver– Frontpage– Coffee cup HTML editor– And many more….

Page 23: Download Workshop Lecture

Web Development Workshop 23

Client Side Scripting

• Client-side programming is based on the idea that the computer which the client is using to browse the web has quite a bit of CPU power sitting there doing nothing.

• Meanwhile, web servers are being tasked to death handling hundreds of CGI requests above and beyond their regular duties.

• Thus, it makes sense to share some of that burden between the client and server by taking some of the processing load off the server and giving it to the client.

Page 24: Download Workshop Lecture

Web Development Workshop 24

What Client side scripts can do?

• Scripts can be used to add interesting (Interactive Web Pages) and useful effects to Web pages (Dynamic pages)

• Validations and error checking• Maintaining state• Creating Dynamic Forms with Client-Side

Scripting. • Instant Feedback to Users• Client-Side Scripts Move Processing Tasks

back to the Client

Page 25: Download Workshop Lecture

Web Development Workshop 25

Disadvantages of Client Side Scripting

• Browser-Dependent Client-Side Scripts• Different set of codes for both the

browsers• Secure Source Code of Client-Side

Scripts.• Pages Take Longer to Download• Program Scope Is Limited to a Single

HTML Page• No Direct Access to System Objects

Page 26: Download Workshop Lecture

Web Development Workshop 26

Which Should I Use? Client- or Server-Side?

• If you want to have dynamic client forms with client-side validation, you must use client-side scripting.

• If you want your site to have highly interactive pages, you should use client-side scripting.

• If you need to provide your client with advanced functionality that can be created only using ActiveX controls, you must use client-side scripting.

Page 27: Download Workshop Lecture

Web Development Workshop 27

Which Should I Use? Client- or Server-Side? Cont…

• If you want to control the user's browser (that is, you want to turn off the menus and place the browser in kiosk mode), you must use client-side scripting

• If your Web site must work with every browser on the market, and you do not want to create several different versions for different browsers, you should avoid client-side scripting

• If you want to protect your source code, you must use only server-side scripting. All client-side source code is transferred to the browser.

Page 28: Download Workshop Lecture

Web Development Workshop 28

Which Should I Use? Client- or Server-Side? Cont…

• If you need to track user information across several Web pages to create a "Web application," you must use server-side scripting

• If you need to interact with server-side databases, you must use server-side scripting.

• If you need to use HTTP server variables or check the capabilities of the user's browser, you must use server-side scripting

Page 29: Download Workshop Lecture

Web Development Workshop 29

Server and Client Side Scripting

• Client Side– Java script– VB Script

• Server Side– PHP– JSP– ASP– ASP.NET

Page 30: Download Workshop Lecture

Web Development Workshop 30

Brief History of PHP

• PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP originally stood for “Personal Home Page”.

• PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.

• PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans .

• PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added.

• PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP . Last version is PHP 5.2.6

Page 31: Download Workshop Lecture

Web Development Workshop 31

Why is PHP used?

• Easy to UseCode is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode".

– <html>   <head>       <title>Example</title>   </head>   <body>

       <?php        echo "Hi, I'm a PHP script!";        ?>

   </body></html>

Page 32: Download Workshop Lecture

Web Development Workshop 32

Why is PHP used?

Cross PlatformRuns on almost any Web server on several operating systems.One of the strongest features is the wide range of supported databases

Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server. 30% of web servers on Internet have PHP installed Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003

Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm

Page 33: Download Workshop Lecture

Web Development Workshop 33

Why is PHP used?

• Cost BenefitsPHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free.

PHP

Software Free

Platform Free (Linux)

Development Tools

FreePHP Coder, jEdit

Page 34: Download Workshop Lecture

Web Development Workshop 34

PHP and ASP market share (February 2008)

• Source: http://www.nexen.net/• PHP dominates ASP by a wide margin.• Note: PHP runs on Windows and *n*x.

Page 35: Download Workshop Lecture

Web Development Workshop 35

PHP Adoption by Country

Page 36: Download Workshop Lecture

Web Development Workshop 36

Web servers distribution

Page 37: Download Workshop Lecture

Web Development Workshop 37

Apache adoption by country

Page 38: Download Workshop Lecture

Web Development Workshop 38

How PHP Pages are Accessed and Interpreted

2. Send Request for PHP file

6. Return Results

Please EnterAPhoneNumber

Submit Erase

1. Web Browser

Web Browser

Phone QueryResults:

That isJohn Doe'sPhoneNumber

7. Web Browser

Your PC(Internet connected)

WebServer(Internet connected)

Web ServerSoftware

3. Receiverequest, find

file and read it.

4. ExecutePHP

statements

5. Sendresultsback.

Page 39: Download Workshop Lecture

Web Development Workshop 39

HTML in a PHP page

<head><title>PHP Info</title><?phpprint("PHP Stats on the Server");?> </head>

<body><?phpphpinfo();?>And print some more text here!</body></html>

<script> blockin <head>

<script> blockin <body>

Language we areusing is PHP

Generate HTML “on the fly” with

print(...);

Page 40: Download Workshop Lecture

Web Development Workshop 40

Data Types in PHP

• PHP supports eight primitive data types– There are four scalar types

• boolean• integer• floating-point number• string

– There are two structured types• array• object

– There are two special data types• resource• NULL

– The programmer does not need to specify the type of a variable

• a variable’s type is determined from the context of its usage

Page 41: Download Workshop Lecture

Web Development Workshop 41

Booleans

• The boolean data type admits two values– true (case-insensitive)– false (case-insensitive)

• Example$itIsRainingToday = true;$thePrinterIsBusy = True;$theQueueIsEmpty = FALSE;

Page 42: Download Workshop Lecture

Web Development Workshop 42

Integers

• Integers can be specified in decimal, hexadecimal or octal notation, optionally preceded by a sign– In octal notation, the number must have a leading 0– In hexadecimal notation, the number must have a leading

0x. • Examples

$a = 1234;# decimal number$a = 0123;# octal number (i.e., 83 decimal)$a = -123;# a negative number$a = 0x1B;# hexadecimal number (i.e., 27 decimal)

• The maximum size of an integer is platform-dependent, but usually it’s 32 bits signed – about 2,000,000,000

• PHP does not support unsigned integers.

Page 43: Download Workshop Lecture

Web Development Workshop 43

Floating Point Numbers

• Specified using any of these forms$a = 1.234;$a = 1.2e3; $a = 7E-10;

• The maximum size of a float is platform-dependent, although most support a maximum of about 1.8e308 with a precision of roughly 14 decimal digits

Page 44: Download Workshop Lecture

Web Development Workshop 44

Strings

• Specified in different ways– single quoted

• In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash

echo 'this is a simple string';echo 'You can embed newlines in strings,

just like this.';echo ‘Douglas MacArthur said "I\'ll be back” when leaving the

Phillipines';echo 'Are you sure you want to delete C:\\*.*?';

– double quoted In double-quoted strings, – variables are interpreted to their values, and– various characters can be escaped

» \n linefeed» \r carriage return» \t horizontal tab» \\ backslash» \$ dollar sign» \” double quote» \[0-7]{1,3} a character in octal notation» \x[0-9A-Fa-f]{1,2} a character in hexadecimal notation

Page 45: Download Workshop Lecture

Web Development Workshop 45

Variables Names

• In PHP variable starts with a $• Followed by letter or underscore• Can contain letters, numbers,

underscores, or dashes• No spaces• Case-sensitive

– $student and $Student are different as it is case sensitive

Page 46: Download Workshop Lecture

Web Development Workshop 46

Assign a value to a variable

The universal form of the assignment statementPHP uses the single equals sign =

$greeting = "Hello World!";$balance = 52;$isMatch = false;

– variable gets valuegreeting gets the value “Hello World!”balance gets the value 52isMatch gets the value false

NOTE: The equals sign = is used differently in math and

programming.

Page 47: Download Workshop Lecture

Web Development Workshop 47

Predefined variables

• $GLOBALS• $_SERVER• $_GET• $_POST• $_COOKIE• $_FILES• $_ENV• $_REQUEST• $_SESSION

Page 48: Download Workshop Lecture

Web Development Workshop 48

Variable Scope

• Local – declared Inside a function• global – declared Outside a function• static – retains value between calls• Parameters and variables declared inside a function are

available only inside the function– They come into existence when the function is called– They disappear when the function exits

• Variables declared outside a function are not available inside the function

• Automatically global– $_POST, $_GET– $_SERVER, $_ENV

• The keyword global – Makes internal variables available externally– Makes external variables available internally– global $fred

Page 49: Download Workshop Lecture

Web Development Workshop 49

Constants

• A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

<?php

// Valid constant namesdefine("FOO",     "something");define("FOO2",    "something else");define("FOO_BAR", "something more");

// Invalid constant namesdefine("2FOO",    "something");

// This is valid, but should be avoided:// PHP may one day provide a magical constant// that will break your scriptdefine("__FOO__", "something"); 

?>

Page 50: Download Workshop Lecture

Web Development Workshop 50

Constants & Magic constants

• PHP_VERSION • PHP_OS • PHP_INT_MAX • PHP_INT_SIZE • DEFAULT_INCLUDE_PATH • __LINE__ • __FILE__ • __FUNCTION__

Page 51: Download Workshop Lecture

Web Development Workshop 51

Expressions

• The right-hand side of an assignment statement can be any valid expression

• Expressions are “formulas” saying how to manipulate existing values to compute new values– $balance = $balance - $transaction;– $seconds = 60*$minutes;– $message = 'Status code is '.$codeValue;

Page 52: Download Workshop Lecture

Web Development Workshop 52

Comments

<html> <head><title>Don't forget your comments</title></head> <body><!–- Start HTML page here --><h2>A few words about comments</h2><?php// Start PHP script here

$string1 = "Welcome";/* Another way to add some comments to your PHP code*/$string2 = "$string1 stranger!";?>…

Page 53: Download Workshop Lecture

Web Development Workshop 53

Operators

• Addition (+)• Subtraction (-)• Multiplication (*)• Division (/)• Modulus (%)• Negation (-)• String concatenation (.)• Pre- & Post-increment (++)• Pre & Post-decrement (--)

• Equality (==)• Identical (===)• Inequality (!= or <>)• Not identical (!==)• Greater than (>)• Less that (<)• Greater than or equal (>=)• Less than or equal (<=)• Logical AND (&&, and)• Logical OR (||, or)• Logical XOR (xor)• Logical negation (!)

Page 54: Download Workshop Lecture

Web Development Workshop 54

Operators (Cont..)

Assignment• Assignment (=)• Plus-equals (+=)• Minus-equals (-=)• Divide-equals (/=)• Multiply-equals (*=)• Modulus-equals

(%=)

Miscellaneous• Error suppression

(@)• Conditional or

Ternary operator (?:)

Page 55: Download Workshop Lecture

Web Development Workshop 55

Arrays

$dog1 = "Flash";$dog2 = "Buffy";$bird = "Mr. Bird";

$pets = array($dog1, $dog2, $bird);where $pets[0] is "Flash";where $pets[1] is "Buffy";and where $pets[2] is "Mr. Bird";

Associate Arrays$FlashDog = array(name=>"Flash", color=>"black",

age=>17);print $FlashDog["color"];

Page 56: Download Workshop Lecture

Web Development Workshop 56

Multi-dimensional Arrays

$animals = array (array (name=>"Flash",

type=>"dog",color=>"black"),

array (name=>"Buffy",type=>"dog",color=>"blond"),

array (name=>"Mr. Bird",type=>"bird",color=>"blue")

);

print $animals[2]["type"];

Page 57: Download Workshop Lecture

Web Development Workshop 57

"SuperGlobal" Variables in PHP

• $_SERVER is an array containing data like headers, paths, etc…

• It has several usual elements– PHP_SELF– SERVER_NAME– REQUEST_METHOD– DOCUMENT_ROOT– HTTP_REFERER– HTTP_USER_AGENT

• $_ENV• $_GET/$_POST• $_COOKIE• $_SESSION

Page 58: Download Workshop Lecture

Web Development Workshop 58

Control Structures

• if• else• elseif• while• do-while• for• foreach• break• continue• switch• require• include• require_once• include_once

Page 59: Download Workshop Lecture

Web Development Workshop 59

The if / else statement

The if statement is a conditional statement– a conditional expression is evaluated as being true or false

• the expression is a boolean expression (ie, returns true or false)

– if the condition is true, then one set of statements is executed

– if the statement is false, then a different set of statements is executed

if (<boolean expression>) { <statements>} else { <statements>}

Page 60: Download Workshop Lecture

Web Development Workshop 60

The tricky one

• The reason this works:if ($a = $b)

• The value assigned to a is returned as the result

• This will be interpreted as false if zero and true otherwise

• Allows us to both assign and drive an if at the same time

• However, it is usually a mistake, a left out =

Page 61: Download Workshop Lecture

Web Development Workshop 61

While Loops

<?php/* example 1 */

$i = 1;while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */}

/* example 2 */

$i = 1;while ($i <= 10): echo $i; $i++;endwhile;?>

Page 62: Download Workshop Lecture

Web Development Workshop 62

do-while

• do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.

<?php$i = 0;do {    echo $i++;} while ($i > 0);

?>

Page 63: Download Workshop Lecture

Web Development Workshop 63

The for loop

A counting loop is usually implemented with for

for ($i=0; $i < $count; $i++) { print("<br>index value is : $i");}

initialize check for limitupdate loop control index

shorthand for i=i+1

one or more statements in the loop body

Page 64: Download Workshop Lecture

Web Development Workshop 64

foreach loops

• For looping over an arrayforeach (array_expression as $value) statement foreach (array_expression as $key => $value) statement

<?php$arr = array(1, 2, 3, 4);foreach ($arr as $key=$value) {

   echo "$key = $value";}

?>

0 = 11 = 22 = 33 = 4

Page 65: Download Workshop Lecture

Web Development Workshop 65

break

• break ends execution of the current for, foreach, while, do-while or switch structure.

<?php for ($i = 0; $i < 10; ++$i) { if ($i == 5) break; print "$i<br>"; }?>

01234

Page 66: Download Workshop Lecture

Web Development Workshop 66

continue

• continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

<?php for ($i = 0; $i < 6; ++$i) { if ($i == 3) continue; print "$i<br>"; }?>

01245

Page 67: Download Workshop Lecture

Web Development Workshop 67

switch

<?php$i=2;

switch ($i) {case 0:    echo "i equals 0";    break;case 1:    echo "i equals 1";    break;case 2:    echo "i equals 2";    break;default:    echo "i is not equal to 0, 1 or 2";}?>

i equals 2

Page 68: Download Workshop Lecture

Web Development Workshop 68

require()

• The require() statement includes and evaluates the specific file.

• use require() if you want a missing file to halt processing of the page

<?phprequire 'prepend.php';require $somefile;require ('somefile.txt');?>

Page 69: Download Workshop Lecture

Web Development Workshop 69

• The include() statement includes and evaluates the specified file.

• script will continue in case of missing file

include()

vars.php<?php$color = 'green';$fruit = 'apple';?>

test.php<?phpecho "A $color $fruit"; // Ainclude 'vars.php';echo "A $color $fruit"; // A green apple?>

Page 70: Download Workshop Lecture

Web Development Workshop 70

PHP functions

•What are Functions?A function structure:

<?php

function myname( $1arg, $2arg,….. $narg){   echo "Example function.\n";   return $retval;}

?>

Page 71: Download Workshop Lecture

Web Development Workshop 71

Example For Global

<?php

$a = 1;$b = 2;

function Sum(){

   global $a, $b;

   $b = $a + $b;}

Sum();echo $b;

?>

b=3

Page 72: Download Workshop Lecture

Web Development Workshop 72

Example For Static

<?php

function Tables(){

   static $count = 0; static $x=0;

$y=2; $count++;

 $x= $x + $y; echo “$x <br>”;

  If ($count < 5) {

        Tables();    }} Tables();

?>

2 4 6 8 10

Page 73: Download Workshop Lecture

Web Development Workshop 73

Nested Functions

<? function fname()

{echo "fname<br>";function lname(){

echo "lname<br>";}

}

//lname(); not accesible

fname();lname();

?>

Here lname() can only be called after calling fname()

Page 74: Download Workshop Lecture

Web Development Workshop 74

Function Arguments

Passing By ValueEg:<?

function add($num){

$sum=$num[0]+$num[1];echo "$sum<br>";

}

$num = array(0,1);add($num);echo $num[0];

?>

Passing By Reference<?php

function name(&$string){ $string .= 'lname.';}

$str = 'fname ';name($str);echo $str; // outputs ‘fname

lname‘

?>

Page 75: Download Workshop Lecture

Web Development Workshop 75

Use Of Default Parameters

Ex:<?php

function comname ($lname="Softech") { return "company name is $lname<br>";

}

echo comname();echo comname("Relyon");//prints Relyon

?><?

function comname ($fname, $lname="Softech") {

return "company name is $fname $lname"; }

echo comname("Relyon");//prints Relyon Softech

?>

Page 76: Download Workshop Lecture

Web Development Workshop 76

Intro to HTML Forms

• Forms allow us to create interactive websites, by accepting input from users

• Types of input we can collect via forms:– Text via text boxes and text areas– Selections via radio buttons, check boxes,

pulldown menus, and select boxes

• Form actions do all of the work– Usually through button clicks

Page 77: Download Workshop Lecture

Web Development Workshop 77

Basic HTML Form

<form name="input" action="form_action.php" method="get">

<label for="user">Username</label>

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

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

</form>

Page 78: Download Workshop Lecture

Web Development Workshop 78

Method attribute

<form action="fileWithWhatToDo" method="post"> </form>

• Value tells how to send data from the form to the server

• GET / POST– GET is the default– GET

• Appends ? to the action URI and then lists the names and values of the form elements in pairs

• New URI is sent to the server– POST

• Name/value pairs are sent in the message body of an HTTP POST request

Page 79: Download Workshop Lecture

Web Development Workshop 79

Which Method to use?

• GET– You can see the data in the URL– Limit on how many characters can be sent– Can't send files– Can be bookmarked and revisited

• POST– You can't see the data in the URL– No limit on how much info can be sent– Can send files– Can't be bookmarked or revisited

Page 80: Download Workshop Lecture

Web Development Workshop 80

Forms contain controls

• Buttons– Regular, submit, reset

• Checkboxes• Radio buttons• Menus• Text input• Hidden• etc.

Page 81: Download Workshop Lecture

Web Development Workshop 81

INPUT controls

<form action="fred.php" method="post"> <input type="text" name="aName"> <input type="password" name="aName"> <input type="hidden" name="aName"> <input type="submit" name="submit" value="submit"> <input type="reset" name="reset" value="reset"></form>

Page 82: Download Workshop Lecture

Web Development Workshop 82

INPUT controls (checkbox)

<form action="fred.php" method="post"> <input type="checkbox" name="check1" value="c1">Checkbox1 text <input type="checkbox" name="check2" value="c2">Checkbox2 text

Checkbox3 text <input type="checkbox" name="check3" value="c3"></form>(Lets the user see meaningful values, but return the

primary key.)

Page 83: Download Workshop Lecture

Web Development Workshop 83

INPUT controls (radio buttons)

<form action="fred.php" method="post"> <input type="radio" name="group" value="r1">Radio1 text <input type="radio" name="group" value="r2">Radio2 text

Radio3 text <input type="radio" name="group" value="r3"></form>(all radio buttons in a group must have the same

name)

Page 84: Download Workshop Lecture

Web Development Workshop 84

TEXTAREA

<form action="fred.php" method="post">

<textarea name="aTextArea" rows="2" cols="20"> </textarea></form>

Page 85: Download Workshop Lecture

Web Development Workshop 85

SELECT control (drop down menu)

<form action="fred.php" method="post"> <select size="1" name="aName"> <option value="v1">Choice one</option> <option value="v2">Choice Two</option> <option value="v3" selected> Choice Three</option> </select></form>(Size = 1 and not multiple makes it display as

a drop down menu)

Page 86: Download Workshop Lecture

Web Development Workshop 86

SELECT (list box)

<form action="fred.php" method="post"> <select size="3" name="aName"> <option value="v1">Choice one</option> <option value="v2">Choice Two</option> <option value="v3" selected="true"> Choice Three</option> </select></form>(size > 1, so options are displayed in a list;size = number of options, so no scroll bar)

Page 87: Download Workshop Lecture

Web Development Workshop 87

SELECT (list with scroll bar)

<form action="fred.php" method="post"> <select size="2" name="aName"> <option value="v1">Choice one</option> <option value="v2">Choice Two</option> <option value="v3" selected="true"> Choice Three</option> </select></form>(size > 1, so options are displayed in a list;size < number of options, so scroll bar appears)

Page 88: Download Workshop Lecture

Web Development Workshop 88

SELECT (multi-line)

<form action="fred.php" method="post"> <select size="3" name="aName[]" multiple="t"> <option value="v1">Choice one</option> <option value="v2">Choice Two</option> <option value="v3" selected="true"> Choice Three</option> </select></form>(multiple, so options are displayed in a list.Name must be an array so it can return all the values.Hold down the shift key and click to select more than one

option)

Page 89: Download Workshop Lecture

Web Development Workshop 89

PHP Configuration

Language Options• short_open_tag (boolean )

– Tells whether the short form (<? ?>) of PHP's open tag should be allowed.

• asp_tags (boolean )– Enables the use of ASP-like <% %> tags in addition to the

usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>.

• precision (integer)– The number of significant digits displayed in floating point

numbers.

• y2k_compliance(boolean) – Enforce year 2000 compliance

Page 90: Download Workshop Lecture

Web Development Workshop 90

PHP Configuration (cont..)

Resource Limits• memory_limit integer

– This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

Page 91: Download Workshop Lecture

Web Development Workshop 91

PHP Configuration (cont..)

Data Handlingtrack_vars boolean

– If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and

$_SERVER.

register_globals boolean Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server)

variables as global variables. post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.

Page 92: Download Workshop Lecture

Web Development Workshop 92

PHP Configuration (cont..)

• Paths and Directories• include_path string

– Specifies a list of directories where the require(), include(), fopen(), file(), readfile() and file_get_contents() functions look for

files. • user_dir string

– The base name of the directory used on a user's home directory for PHP files, for example public_html .

• extension_dir string – In what directory PHP should look for dynamically loadable

extensions.

• extension string – Which dynamically loadable extensions to load when PHP starts up.

Page 93: Download Workshop Lecture

Web Development Workshop 93

PHP Configuration (cont..)

• File Uploads• file_uploads boolean

– Whether or not to allow HTTP file uploads.

• upload_tmp_dir string – The temporary directory used for storing files when doing

file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

• upload_max_filesize integer – The maximum size of an uploaded file.

Page 94: Download Workshop Lecture

Web Development Workshop 94

PHP Cookies and Sessions

Page 95: Download Workshop Lecture

Stateful & Stateless

• Stateful– Stateful means the computer or program

keeps track of the state of interaction, usually by setting values in a storage field designated for that purpose.

• Stateless– Stateless means there is no record of

previous interactions and each interaction request has to be handled based entirely on information that comes with it.

Page 96: Download Workshop Lecture

Web Development Workshop

HTTP is stateless

• The World Wide Web is intrinsically stateless

• Each request from a user for a Web page/ URL results in the requested pages being served

• The Web (HTTP) server never remembers the request later.

• There is no recorded continuity. • Each communication is discrete and

unrelated to those that precede or follow.

Page 97: Download Workshop Lecture

Web Development Workshop

Methods for maintaining state

• Cookies• Sessions• Passing [hidden] variables

Page 98: Download Workshop Lecture

What is a cookie?

• Cookies are simple text strings of the form of name=value

• Cookies are stored persistently on the client’s machine and not on the server.

• A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server.

Page 99: Download Workshop Lecture

How to Set a Cookie

• PHP provides setcookie() function to set a cookie.

• This function should be called before <html> tag.

• For each cookie this function has to be called

separately.• Format of the function is

setcookie(name, value, expire, path, domain, security);

Page 100: Download Workshop Lecture

Arguments of setcookie()

• Name - This sets the name of the cookie and is stored in an environment variable called

HTTP_COOKIE_VARS. This variable is used while accessing cookies. (Ex. “user”)

• Value -This sets the value of the named variable and is the content that you actually want

to store. (Eg. “Raju”)

• Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this

time cookie will become inaccessible. If this parameter is not set then cookie will

automatically expire when the Web Browser is closed. (Eg. time()+60*60*24*7)

• Path -This specifies the directories for which the cookie is valid. A single forward slash

character permits the cookie to be valid for all directories and files on the web server. If a

specific directory is named, this cookie is valid only for the pages within that directory (Eg.

“/”)

• Domain - This can be used to specify the domain name in very large domains and must

contain at least two periods to be valid. All cookies are only valid for the host and domain

which created them. (Eg. www.nic.in)

• Security - This can be set to 1 to specify that the cookie should only be sent by secure

transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular

HTTP. (Eg. 0 or 1)

Page 101: Download Workshop Lecture

Cookie Example

<?php

setcookie(“user”,”Raju”);

setcookie(“user", “nic", time()+3600);

setcookie(“user", “nic", time()+3600, "/","", 0);

?>

<html><head>

<title> Cookie Example </title></head>

<body>

<?php

echo “The cookie is set for variable ‘user’“;

?></body></html>

Page 102: Download Workshop Lecture

How to use a Cookie

<html><head>

<title>Using cookies in PHP</title>

</head>

<body>

<?php

//Display the value of ‘user’

echo $_COOKIE[“user"]. "<br />";

//This is another way

echo $HTTP_COOKIE_VARS[“user"]. "<br />";

?></body></html>

Page 103: Download Workshop Lecture

How to check whether a cookie is set - isset()

<html>

<head>

<title>Checking whether a cookie is set</title>

</head>

<body>

<?php

// Using isset() function

if( isset($_COOKIE[“user"]))

echo “Hello " . $_COOKIE[“user"] . "<br />";

else

echo “Unknown user" . "<br />";

?>

</body></html>

Page 104: Download Workshop Lecture

How to Erase a Cookie

• Set the cookie's expiration date to some time

in the past.<?php

setcookie( “user", "", time()- 3600, "/","", 0);

?>

<html><head>

<title>Erasing Cookies</title></head><body>

<?php

echo “The cookie is erased“;

echo “The user is :”. $_COOKIE[“user"] . "<br />";

?></body></html>

Page 105: Download Workshop Lecture

Limitations of Cookies

• Can’t call setCookie() after output has been sent to the browser

• Can’t have more than 20 cookies/server

• Cookies ONLY persist until the browser closes UNLESS you specify an expiry date

• Restrictions on use of cookies

Page 106: Download Workshop Lecture

Benefit of Cookies

• Cookies are used for authenticating, tracking, and maintaining specific information about users

• Personolised home pages• Electronic shopping carts.

Page 107: Download Workshop Lecture

Browser settings

• Most modern browsers support cookies.

• A user can choose whether cookies should be used or not. The following are common options:

– cookies are never accepted,– the browser asks the user whether to accept

every individual cookie or allows them to generate a white list of acceptable sites, or

– cookies are always accepted, or– cookies are accepted, except from sites specified

by the user, generating a black list for cookie

Page 108: Download Workshop Lecture

Why use sessions

• A normal HTML website will not pass data from one page to another

• All information is forgotten when a new page is loaded

• Many websites need to pass user data from one page to another • for tasks like a shopping cart, which requires

data(the user's selected product) to be remembered from one page to the next

• Using PHP sessions is one solution.

Page 109: Download Workshop Lecture

Web Development Workshop

PHP Sessions - Overview

• An alternative way to make data accessible across the

various pages of an entire website is to use a PHP Session.

• A series of related interactions between a single client and

the web server, over an extended period of time.

• A session creates a file in a temporary directory on the server

where registered session variables and their values are

stored. This data will be available to all pages on the site

during that visit.

• A session ends when the user loses the browser or after

leaving the site, the server will terminate the session after a

predetermined period of time, commonly 30 minutes

duration.

• Sessions are used to create multi page forms and store user

authentication information across pages and persistent user

preferences on a site.

Page 110: Download Workshop Lecture

Session IDs

• Sessions work by creating a unique identification(UID)

number for each visitor and storing variables based on

this ID.

• Session Identifier is known as Session Id (SID)

• It is a special variable for any particular session.

• It is a Unique ID.

Page 111: Download Workshop Lecture

Web Development Workshop

Starting a PHP Session

• Before storing user information in a PHP session, a session is to be started using session_start() function

• This must be at the very beginning of the code, before any HTML or text is sent.

• This function first checks if a session is already started and if none is started then it starts one

• Session variables are stored in an associative

array called $_SESSION[]. These variables can

be accessed during lifetime of a session.

Page 112: Download Workshop Lecture

Sample Session Start Code

<?phpsession_start(); // start up your PHP session!

?> • This tiny piece of code will register the

user's session with the server• Allow you to start saving user

information• Assign a session ID (SID) for that

user's session.

Page 113: Download Workshop Lecture

Web Development Workshop 113

Showing Session ID

• Whenever a session is created a unique session ID is created.

• The function session_id() displays the SID of the current session

<?php//showing session idsession_start();echo "Current Session ID = <b>".session_id()."</b>";?>

Page 114: Download Workshop Lecture

Store and Display Session Variable

• When you want to store user data in a session use the $_SESSION associative array.

• This is where you both store and retrieve session data.

<?phpsession_start(); $_SESSION['views'] = 1; // store session dataecho "Pageviews = ". $_SESSION['views']; //retrieve data?>

Display:Pageviews = 1

Page 115: Download Workshop Lecture

Web Development Workshop 115

Seeing the session variables on the Server

• The session variables are stored on the web server

• The Path is /var/lib/php/session• The file name is the session ID

Eg.

sess_076opqrstu56kldr670ndft0op

Page 116: Download Workshop Lecture

Using PHP's isset() Function

• Before using a session variable, check if it exists already

• isset is a function that takes any variable you want to use and checks to see if it has been set.

• That is, whether it has already been assigned a value.

Page 117: Download Workshop Lecture

Isset() ..Sample Code

<?phpsession_start(); if(isset($_SESSION['views']))

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

$_SESSION['views'] = 1; echo "views = ". $_SESSION['views'];

?> – we can create a very simple pageview counter – use isset to check if the pageview variable exists.

– If yes, increment the counter.If it doesn't exist create a pageview

counter and set it to one.

Page 118: Download Workshop Lecture

Web Development Workshop 118

Passing Session Variables

• Sessions are most useful to create multi page forms and store user authentication information across pages

• This require session ID to be passed across web pages.

• This can be done through the URL

Page 119: Download Workshop Lecture

Web Development Workshop 119

Clearing a Session Variable

• To destroy a single session variable, use unset()

function to unset a session variable.

<?php

unset($_SESSION[‘views']);

?>

Page 120: Download Workshop Lecture

Web Development Workshop 120

Destroying a Session

• A PHP session can be destroyed by session_destroy()

function. This function does not need any argument

and a single call can destroy all the session variables.

<?php

session_destroy();

?>

Page 121: Download Workshop Lecture

Web Development Workshop 121

String Manipulation

• String format:– Trimming: chop(), ltrim(), trim()– nl2br(), htmlspecialchars() – printf(): printf(“the price is %s.”,$total)– Case: strtoupper(), strtolower(), ucfirst(), ucwords()– Storage: AddSlashes(), StripSlashes()– Others: strlen();

• Join and Split– explode(), implode()/join(), strtok(), substr()

• Examples– $email_array = explode(‘@’,$email);– $new_email = implode(‘@’,$email_array); – $token = strtok($feedback,” “);//get one once a time– substr ( string astring, int start, [, int length]);

Page 122: Download Workshop Lecture

Web Development Workshop 122

String Manipulation (cont’)

• Match and Replace– Finding: strstr()/strchr(), stristr(), strrchar(),

• Examples: if(strstr($email, “unc.edu”)) { ..} //stristr() ignore cases, strrchar() reverse

– Position: strpos(),strrpos();• Examples:Echo strpos($email, “unc”);

– Replacing: str_replace(), substr_replace();• Examples: str_replace(“unc”, “ils.unc”,$email)

– Regular expressions:• \ ^ $ . | () * + {} • ereg(string pattern, string string, array [matches]) . eregi// if string contains pattern, the matched substring is stored in matches

array• ereg_replace(string pattern, string replacement, string string);• array split(string pattern, string string, int [max])

Page 123: Download Workshop Lecture

Web Development Workshop 123

Sending HTML email

<?php// multiple recipients$to  = '[email protected]' . ', '; // note the comma$to .= '[email protected]';

// subject$subject = 'Birthday Reminders for August';

// message$message = '<html><head>  <title>Birthday Reminders for August</title></head><body>  <p>Here are the birthdays upcoming in August!</p>  <table>    <tr>      ………    </tr>  </table></body></html>';

// To send HTML mail, the Content-type header must be set$headers  = 'MIME-Version: 1.0' . "\r\n";$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";$headers .= 'Cc: [email protected]' . "\r\n";$headers .= 'Bcc: [email protected]' . "\r\n";

// Mail itmail($to, $subject, $message, $headers);?>

Page 124: Download Workshop Lecture

Web Development Workshop 124

Reading file with PHP

Opening a file and reading it with fgets<?php

$file_handle = fopen("myfile", "r"); while (!feof($file_handle)) {$line = fgets($file_handle); echo $line;

} fclose($file_handle);

?>

Page 125: Download Workshop Lecture

Web Development Workshop 125

Simple Page Counter

<?php$COUNTER_FILE = “webcounter.txt";if (file_exists($COUNTER_FILE)) {

$fp = fopen("$COUNTER_FILE", "r+");flock($fp, 1);$hits = fgets($fp, 4096);$hits += 1; fseek($fp,0);fputs($fp, $hits);flock($fp, 3);fclose($fp);

} ?>

Page 126: Download Workshop Lecture

Web Development Workshop 126

Handling file uploads

• For uploading a file we need a form for the user to enter the file name or browse their computer and select a file. The input type="file" is used for that purpose.

<form method="post" enctype="multipart/form-data"><table width="350" border="0" cellpadding="1" cellspacing="1" class="box"><tr> <td width="246"><input type="hidden" name="MAX_FILE_SIZE" value="2000000"><input name="userfile" type="file" id="userfile"> </td><td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td></tr></table></form>

Page 127: Download Workshop Lecture

Web Development Workshop 127

Handling file uploads (Cont..)

• After the form is submitted the we need to read the autoglobal $_FILES. In the example above the input name for the file is userfile so the content of $_FILES are like this :– $_FILES['userfile']['name']

The original name of the file on the client machine. – $_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif".

– $_FILES['userfile']['size']The size, in bytes, of the uploaded file.

– $_FILES['userfile']['tmp_name']The temporary filename of the file in which the uploaded file was stored on the server.

– $_FILES['userfile']['error']The error code associated with this file upload. ['error'] was added in PHP 4.2.0

Page 128: Download Workshop Lecture

Web Development Workshop 128

Handling file uploads (Cont..)

• <?php// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead// of $_FILES.

$uploaddir = '/var/www/uploads/';$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {   echo "File is valid, and was successfully uploaded.\n";} else {   echo "Possible file upload attack!\n";}?>

Page 129: Download Workshop Lecture

Web Development Workshop 129

Introduction To Database

• Why Databases?– Databases are the preferred method of

storage for large multi-user applications.– Databases enhance applications, e.g. Web.– Databases introduce interesting ideas.

• A relational database – It splits the data into a series of tables, linked

by key elements that are common between tables.

– It provides storage efficiency because data do not need to be duplicated between records.

Page 130: Download Workshop Lecture

Web Development Workshop 130

DBMS

• A database management system (DBMS) is a system, usually automated and computerized, used to manage any collection of compatible, and ideally normalized data.

• The DBMS manages storage and access to the data, and provides a query language to specify actions associated with the data. The standard query language is SQL.

• A DBMS generally provides a client application that can be used to directly manipulate the data, as well as a programmable interface. MySQL provides a set of command line clients, as well as a program interface.

Page 131: Download Workshop Lecture

Web Development Workshop 131

Relational Databases

• Information is stored in tables– Tables store information about entities– Entities have characteristics called attributes– Each row in a table represents a single entity

• Each row is a set of attribute values• Every row must be unique, identified by a

key– Relationships -- associations among the data

values are stored Table structure = schema Table contents = instance

Page 132: Download Workshop Lecture

Web Development Workshop 132

Schema for Example table: ID number unique number(Key) Last text person’s last name First text person’s first name JobCode number current position Hire date first day on job ...

A Table in a Database

Tables have names, attributes {fields}, entities {rows}

instance

schema

Page 133: Download Workshop Lecture

Web Development Workshop 133

Relationships

Page 134: Download Workshop Lecture

Web Development Workshop 134

MySQL Introduction

• MySQL is a database management system

• SQL stands for the Structured Query Language. It defines how to insert, retrieve, modify and delete data

• Free from www.mysql.com• Reference sites

– NASA, Yahoo!, Compaq, Motorola

Page 135: Download Workshop Lecture

Web Development Workshop 135

Basic MySQL Operations

• Create table• Insert records• Load data• Retrieve records• Update records• Delete records• Modify table• Join table• Drop table• Optimize table• Count, Like, Order by, Group by• More advanced ones (sub-queries, stored procedures,

triggers, views …)

Page 136: Download Workshop Lecture

Web Development Workshop 136

How MySQL stores data (by default)

• A MySQL server can store several databases• Databases are stored as directories

– Default is at /usr/local/mysql/var/

• Tables are stored as files inside each database (directory)

• For each table, it has three files:– table.FRM file containing information about the

table structure– table.MYD file containing the row data– table.MYI containing any indexes belonging with

this table, as well as some statistics about the table.

Page 137: Download Workshop Lecture

Web Development Workshop 137

MySQL – Create Tables

• Table structure for following examples:

CREATE TABLE oscarpool ( uid int(4) auto_increment, username varchar(255), email varchar(255), bestpicture int(2), PRIMARY KEY (uid))

CREATE TABLE bestdirector ( bdid int(4) auto_increment, name varchar(255), PRIMARY KEY (bdid))

Page 138: Download Workshop Lecture

Web Development Workshop 138

MySQL – INSERT

• Common SQL Statement: INSERTINSERT INTO oscarpool(username,email,bestpicture)VALUES(‘dolsen',‘[email protected]',1)

• Creates a new record in the table ‘oscarpool’• Text fields need to have ‘s.• Tip: If you have an ‘ in your data you need to escape it before

inserting it. Can use the PHP function addslashes(). • Example: ‘John O\’Brien’

Page 139: Download Workshop Lecture

Web Development Workshop 139

MySQL – SELECT

• Common SQL Statement: SELECTSELECT uid,usernameFROM oscarpool

• Selects the attributes ‘uid’ and ‘username’ from every record in ‘oscarpool’

• SELECT is how you query the database. You can also:– limit the number of records returned with LIMIT, – limit retrieval to those records that match a condition with

WHERE,– sort the data after the query has been evaluated using

ORDER BY• Tip: To easily select every attribute replace ‘uid’ with ‘*’

Page 140: Download Workshop Lecture

Web Development Workshop 140

MySQL – UPDATE

• Common SQL Statement: UPDATE

UPDATE oscarpoolSET email = ‘[email protected]’WHERE uid = 1

• Updates the email address where ‘uid = 1’ in the table ‘oscarpool’

• In this case I know that uid 1 is what my record was. In many cases you’d pass a uid variable from a form.

Page 141: Download Workshop Lecture

Web Development Workshop 141

MySQL – DELETE

• Common SQL Statement: DELETE

DELETE FROM oscarpoolWHERE uid = 1

• Deletes the record where ‘uid = 1’ in the table ‘oscarpool’

• DELETE only removes the record from the table. To remove an entire table from the database you need to use the SQL statement DROP.

• Tip: To remove every record in a table but not remove the table just don’t include the WHERE clause.

Page 142: Download Workshop Lecture

Web Development Workshop 142

MySQL – JOIN

SELECT bd.nameFROM oscarpool op, bestdirector bdWHERE op.uid = 1 and op.bestdirector = bd.bdid

• Selects the name of the Best Director that the user with ‘uid = 1’ has chosen

• bestdirector is a Foreign Key of the Primary Key for the table BestDirector

Page 143: Download Workshop Lecture

Web Development Workshop 143

Database

Server-side Programming

Interchange Language

Client-side Programming

Web Browser

Client Hardware

Server Hardware (PC, Unix)

(MySQL)

(PHP)

(HTML, XML)

(JavaScript)

(IE, Firefox)

(PC)

Bus

ines

sru

les

Inte

ract

ion

Des

ign

Inte

rfac

eD

esig

n

Layered Architecture

Page 144: Download Workshop Lecture

Web Development Workshop 144

Accessing MySQL

• Steps in querying a MySQL database– Set up a connection

• @ $db=mysql_pconnect(‘pearl.ils.unc.edu’, ’webdb_24’ , ’webdb_24’ );

• if(!$db){..}– Choose a database

• mysql_select_db(‘webdb_24’);– Query the database

$query=“select * from accounts”;$result = mysql_query($query);

– Retrieve the query results$num_results=mysql_num_rows($result);$row = mysql_fetch_array($result);//return an associative array with the field name as the key and

record as value. – Free result and disconnect from the database

mysql_free_result($result);mysql_close($db);

Page 145: Download Workshop Lecture

Web Development Workshop 145

Retrieve the Query Results

• Return an array: $row=mysql_fetch_array($result);echo $row[‘name’];

• Return an enumerated array:$row= mysql_fetch_row($result);echo $row[0];

• Return an object : $row =mysql_fetch_object($result);echo $row->name;

Page 146: Download Workshop Lecture

Web Development Workshop 146

Image Functions

• PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser.

Page 147: Download Workshop Lecture

Web Development Workshop 147

Tricks and Tips

• Coding– Prototype your web pages first

• Separate the design of the site from the coding

– Turn repetitive code into functions• Makes for more maintainable and reusable

code

– Turn grunt code into functions• Database access, configuration file access

Page 148: Download Workshop Lecture

Web Development Workshop 148

Tricks and Tips

• Debugging– Feature: PHP is not a strongly typed

language• Variables can be created anywhere in your

code

– Undocumented Feature: PHP is not a strongly typed language• Typos in variable names will cause stuff to

happen

Page 149: Download Workshop Lecture

Web Development Workshop 149

Tricks and Tips

• Debugging– Use scripts to dump form and session

variables• Write scripts to dump data to discover bad or

missing data

Page 150: Download Workshop Lecture

Web Development Workshop 150

Debugging

• Removing the ‘bugs’ that prevent things from working

• Go through step-by-step by inserting echo statements– Test parts– See what works– See where it stops working

Page 151: Download Workshop Lecture

Web Development Workshop 151

Debugging techniques

• If something was working, look at what was changed – Keep multiple versions of your pages

• Show your team mates – Explain how it works– They will see things you can’t

Page 152: Download Workshop Lecture

Web Development Workshop 152

.php Debugging

• Include headers and footers on you pages

• Add echo statements to see where the error occurs

• Isolate the problem systematically• Test your SQL using phpMyAdmin • Is your PHP code displayed?

– Check for both <% and %>– Check your .htaccess file

Page 153: Download Workshop Lecture

Web Development Workshop 153

PHP Debugging checklist

• Check for undefined variable names– Must set variables before referencing

them

• Check use of "" { } and [ ]– Balanced and nested correctly?

• Use UltraEdit Match Brace ^B

– Appropriate grouping characters?

• Check the parameters for routines– Right number of parameters? Defined? $?

Page 154: Download Workshop Lecture

Web Development Workshop 154

SQL Debugging checklist

• Can't connect to the database? Check your account.inc.php file

• No ‘;’ at the end of your SQL within PHP

• Check for the correct characters for– Apostrophe ' – Quote "– Not Word SmartQuotes

Page 155: Download Workshop Lecture

Web Development Workshop 155

SQL Debugging techniques

• Use phpMyAdmin to test SQL statements• Test complicated SQL statements in parts• For example:

– Three way Join, test each pair of tables – Select with Order By, test the select first

• Check for Null values in columns• Check on the number of rows returned

– May be zero, one, or more

Page 156: Download Workshop Lecture

Web Development Workshop 156

Thank you

Page 157: Download Workshop Lecture

Web Development Workshop 157

• Any Question