introduction to php & mysql laboratory setup. php - mysql commercial sites: apache http server...

95
Introduction to PHP & MySQL Laboratory Setup

Upload: nickolas-burns

Post on 04-Jan-2016

242 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Introduction to PHP & MySQL

Laboratory Setup

Page 2: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

PHP - MySQL

• Commercial Sites:• Apache http server• MySQL• PHP

– XAMP (WAMP – MAMP)

• Required Tools– Text Editor or a Program like Dreamweaver

Page 3: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Installing XAMP

• If you are working from your laptop, it is time to download and install XAMP:– Windows: Download and install WAMP Server – MAC: Download and install MAMP– Leave all the settings as default except the browser

(change to your preferred browser: I recommend Chrome, Firefox or Safari)

– Once Installed, your files for this module need to be stored in the following folder (also applies to the lab machines: c:/wamp/www

– Task: Create a folder with your name inside this folder

Page 4: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Stopping IIS

• Next step (only if you are working in the lab or have started IIS on your own machine) – you need to stop IIS – go to:– CONTROL PANEL ADMINISTRATIVE TOOLS

Internet Information Service (IIS) Manager

Page 5: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Stopping IIS

– At the top right hand side of the screen click STOP

Page 6: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Configuring XAMP

• Now it is time to start WAMP Server:– On the desktop click start wampserver; a red “w”

icon should appear in your taskbar, it should go from red, to orange to green – once it is green we are ready to go

Page 7: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Starting WAMP

Start WampServer TaskBar – Red “W”

Page 8: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Starting WAMP

• Click on the icon and select: localhost (this should open your browser with the WAMP welcome page)

Page 9: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

WAMP in Browser

Page 10: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Configuring Dreamweaver

• If you are working with your laptop, and don’t have Dreamweaver, then use any available text editor; just remember to save the files with the correct extension and NOT as TEXT

• In Dreamweaver, you will need to create a site to store your WAMP files:

Page 11: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Dreamweaver

– On the Dreamweaver MENU BAR, click:

• SITE New Site

Page 12: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Setting the Site

• On the Site Section name the site, e.g. john

• Select the local folder (C:\wamp\www\ or browse to find it)

• Then click on “Servers” (second menu item down on the left)

Page 13: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Setting the Server

• Click on the “+” sign under the window

• Change the Connect using setting to Local/ Network

• Use the settings shown in the figure

Page 14: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Your Files

• Click on the “Testing” box and Save

Page 15: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

First XHTML

Page 16: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">

<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>YOUR DOCUMENT TITLE</title></head>

<body>…YOUR CODE…</body></html>

XHTML CODE – PAGE STRUCTURE

Page 17: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

HTML & XHTML

• HTML– All Web pages are made up using HTML

(Hypertext Markup Language)– Every Web Browser turns HTML code into the

stylized web page seen by the user• XHTML

– The World Wide Web Consortium (W3C) – which is the group responsible for defining HTML and other protocols created XHTML as a transition between HTML and XML

Page 18: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

XHTML

• XHTML is almost exactly like HTML, with the following differences:– All tags are written in lowercase– Nested tags must be well formed:

• i.e. you can’t write: <div><p>text</div></p> instead you should write:

• <div><p>text</p></div>– All tag attributes must be quoted:

• HTML: <table border=2>• XHTML: <table border=“2”>

Page 19: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

XHTML

– All tags must be closed:• Many HTML tags have an open and close tag, i.e. <div

class=“class1”>text</div>, but a few don’t have implicit closing tags: i.e. <hr>, <br>, <img> and <input>

• To make these valid XHTML tags, you need to close them by adding a space and a slash at the end, like this:

– <br />– <hr />– <img src=“file.png” width=“100” height=“50” />– <input type=“text” name=“age” size=“3” />

Page 20: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

First XHTML PageFill in the Title of the page (inside the <header></header> tags)

<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Welcome to This page!</title></head>

Fill in the Body of the Page:

<body><h1>This is a Basic XHTML page</h1><br /><p>Even with <span style="font-size:150%;">some</span> decoration, it's still not very exciting.</p></body></html>

Page 21: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Open the Page on the Browser

The URL for your page is: http://localhost/yourfoldername/welcome.html

Page 22: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Styling

• Styling of XHTML is done using CSS (Cascading Style Sheets)

• This is covered in detail in COM621 Advanced Interactive Web Development, available at:

http://scisweb.ulster.ac.uk/~jose/com621/

Page 23: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Introduction to PHP

Page 24: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Initial PHP

• To create a PHP script you should start exactly as you would if you were creating an XHTML document from scratch

• In Dreamweaver: – File New PHP Document – This will create a PHP document that looks

EXACTLY like the Blank XHTML document• Understanding the reason for this is vitally

important

Page 25: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

How PHP Works

• PHP is a server-side language; the code that you write in PHP resides on a host computer that serves Web pages to Web Browsers

• When you go to a website (www.google.com for example), your Internet Service Provider (ISP) directs your request to the server that hosts the www.google.com information

• The server reads the PHP code and processes it according to its scripted directions

Page 26: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

How PHP Works

PHP creates an HTML page on the fly based on parameters of your choosing

Page 27: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Conceptual Summary PHP

• PHP is a server-side technology– It does not run on the client (which is what the

web browsers are)– However, the browsers understand HTML (and

JavaScript and CSS), so – PHP will be used to generate the HTML that runs

in a Web Browser– PHP is free, open-source code

Page 28: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

PHP

• There are 3 main differences between a standard HTML document and a PHP document:

1. PHP scripts should be saved with the .php file extension2. The PHP code is placed within the following tags:

• Start tag: <?php• End tag: ?>

3. PHP Scripts must run on a PHP-enabled Web server• HTML pages can be viewed on any computer• PHP must always be run through a URL (i.e.

http://something/page.php)

Page 29: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

PHP

• In the lab and on your laptop, WAMP will do the job of a web server. WAMP/MAMP stands for:

• Windows/Mac (Operating System)• Apache (web server technology)• MySQL (database technology)• Php (PHP:Hypertext Processor/HTML embedded scripting

language) Invented by Rasmus Lerdorf in 1994

Page 30: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

First PHP Script• The following script will be useful to determine if the

server being used supports PHP• Code:

– On the Head section of your new PHP:<title>First PHP Script</title>

– On the Body Section of your new PHP: <body> <?php phpinfo() ?> </body>

• Save the Script as: phpinfo.php

Page 31: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Testing the Script

• Once the file is saved in the WWW directory (htdocs for a MAC) inside your folder, open your favourite web browser and open the following URL

http://localhost/yourfolder/phpinfo.php

Page 32: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Programming PHP• Comments and White Space

– PHP comments are added by placing two slashes // in front of the text to be commented, or by enclosing multiple lines of text between /* and */

– A commented line will not be processed by the PHP server

Page 33: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Comments

<?php

// comment lines are indicated by the // symbol

/* Multiple line comments can be enclosed within these marks. Usually used to describe the functionality of a part of your code */

statements here;

// note: all PHP statements end with a semicolon ‘;’

?>

All PHP script must be enclosed between these tags

Page 34: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

White Space

• It is good practice to use white space (blank lines, tabs, and other extra space) to make your code easier to write, read and maintain

Page 35: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Programming PHP

• Well written scripts:– Place blank lines between sections of code– Nest elements one tab-stop in from their parent

element– Generally space out the page nicely

• These techniques are the trademark of professionally written code

Page 36: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Variables

• A variable is best thought of as a container for data

• Once a variable has been assigned a value, that variable can be altered, printed to the browser, saved to a database, emailed, etc.

• Variables in PHP are flexible: you can put data into a variable, retrieve it (without affecting the value of the variable), put new data in and continue the cycle as necessary

Page 37: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Variables

• Variables in PHP are also temporary:

– They only exist (have value) for the duration of a script

– Once the user clicks a link or submits a form, the variables cease to exist unless you take special measures to extend their longevity

Page 38: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Variables

• There are some variables that are predefined in PHP (you don’t need to create them again).– i.e: $_SERVER, $_SESSION, $_COOKIE, etc.

• The print_r() function can be used to view the value stored in a variable

• Create a new PHP file named: variables.php and place the following code:

Page 39: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Displaying Variable Content

Page 40: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Variables - Syntax

• All variable names must be preceded by a dollar ($) sign

• Following the dollar sign, the variable name must begin with either a letter (A-Z, a-z) or an underscore (_). It can’t begin with a number

• The rest of the variable name can contain any combination and quantity of letters, underscores, and numbers

Page 41: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Variables - Syntax

• You may not use spaces within the name of a variable (underscore is normally used to separate words)

• Variable names are CASE-SENSITIVE! Consequently, $variable and $Variable are two different constructs

Page 42: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Types of Variables

• There are 3 basic types of variables: numbers, strings and arrays

• In PHP, numbers can be either– Integers (positive or negative) i.e. 1, 1972, -1– Floating point (positive or negative) 1.0, 19.72, -1.0

Page 43: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Types of Variables

• A string is any number of characters enclosed within a pair of either single (') or double (") quotation marks. They can contain any combination of letters, numbers, symbols and spaces. Strings can contain variables:

"Hello World!”"Hello, $first_name!”"1 1/4”"24.12.2011”"1995”' '

Page 44: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Strings:Operators

String Manipulation Description Example

Concatenation(.) Merges 2 or more strings together

$st1 = hello;$st2 = world;$fst = $st1.$st2

Equal (==) and Identical (===)

Check that two strings are equal or identical – when comparing, strings that do not begin with a number are seen as 0 by the language

$st1=“hello”$st2=“hello”$st3=0

$st1==$st2 True$st2==$st3 True (0=0)$st2===$st3 False

Page 45: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

StringFunctions

Function Description

printf() Displays (prints) a formatted string

sprintf() Saves a formatted string in a variable

fprintf() Prints a formatted string to a file

number_format() Formats numbers as strings

Page 46: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Common StringFunctions

Function Description Example

strlen() Finds the length of a string echo strlen("Hello World"); 11

strtoupper() Converts the string to uppercase

strtolower() Converts the string to lowercase

ucfirst() Converts the first letter in a string to uppercase

ucwords() Converts the first letter in each word of a string to uppercase

Page 47: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Common StringFunctions

Function Description Example

strcmp() Compares two strings (case sensitive)

strcmp(‘Dan’,’Daniel’) -3returns 0 if equal, <0 if st1 smaller and >0 if st1 bigger

strcasecmp() Compares two strings (not case sensitive)

new york is equal to New York

str_repeat() Repeats the string str_repeat(input,multiplier)print str_repeat(“-”,30) print 30 dashes

Page 48: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Common StringFunctions

Function Description Example

strchr() Finds the first occurrence of a character in a string and returns it and all characters to end of the string

strchr(string, character)

strchr(“[email protected]”,”.”) .ac

strichr() Case insensitive form of strchr()

strrchr() Finds last occurrence of a character on a string and returns it and all characters to end of the string

strchr(“[email protected]”,”a”) ac

substr() returns parts of a string specified by start position and length

substr (string,start,[length])

start and length are integers

Page 49: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Add SlashesSpecial Characters

• When a form sends a word like O’Neil to a php script, the script will interpret the apostrophe as either an opening or closing of single quotes and that will not allow the script to work. In order for it to work, the apostrophe needs to be send preceded by an slash, i.e. O\’Neil.

• These are called “escaped” characters

• The addcslashes() and addslashes() functions are used to “escape” backslash character when inserted into a database.

• The escaped characters are:– Single and Double Quotes– The Backslash itself (\)– NULL

Page 50: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Add SlashesSpecial Characters

• The PHP directive magic_quotes_gpc() is on by default and it runs addslashes() on all $_GET, $_POST and $_COOKIE data.

• DO NOT USE addslashes() ON STRINGS THAT HAVE ALREADY BEEN ESCAPED

• You can use the get_magic_quotes_gpc() function to see if magic_quotes is on:

if (get_magic_quotes_gpc()==1) {echo "on";} else {echo "off";}

Page 51: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

• If instead of adding the escaped data into the database, you only need to print it, then you will need to use the stripcslashes() function to print it

• The stripcslashes() functions removes backslashes that precede quotation marks and if there are double slashes, they become a single slash.

Page 52: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Example<?php$passstring = $_GET['field'];$strippedstring = stripcslashes($passstring);echo $passstring."<br />";echo $strippedstring;

$link = mysql_connect('localhost','student','student');mysql_select_db('sandra',$link);$query1 = "INSERT into input VALUES (NULL,'$passstring')";$result = mysql_query($query1,$link) or die(mysql_error());$query2 = "INSERT into input VALUES (NULL,'$strippedstring')";$result = mysql_query($query2,$link) or die(mysql_error());?>

<body><form action="teststring.php" method="get"><input type="text" name="field" /><input type="submit" /></form>

</body>

HTML FORM

teststring.php FILE

This Query will give an error when aninput like o’neil or o’connor is used inform

Page 53: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Types of Variables

• Whereas a string or a number contains a single value (they are called “scalars”), an array can have more than one value assigned to it

• Arrays use “keys” to create and retrieve the values they store. The resulting structure looks similar to a two column spreadsheet

• The array structure in PHP is so flexible that it can use either numbers or strings for both the keys and the values

Page 54: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Types of ArraysIndexed: uses numbers as the keys

Key Value

0 Don

1 Jordan

2 James

3 Jenny

Associative: uses arrays as the keys

Key Value

VT Vermont

FL Florida

NY New York

TX Texas

PHP has two types of arrays:

Note: The Arrays key is also called the index and both terms are used interchangeably in the literature

Page 55: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Example: Indexed Array<?php

$products=array('floral talc','body mist', 'perfumed powder','bath gel'); echo "<b>\$products is $products.<br>\n"; echo "\$products[0] is $products[0].<br>\n"; echo "\$products[1] is $products[1].<br>\n"; echo "\$products[2] is $products[2].<br>\n"; echo "\$products[3] is $products[3].<br>\n";

?><br><em>Let's add another element to the array.</em><br>

<?php $products[]='gentle soap'; echo "\$products[4] is $products[4].<br>\n";?>

Page 56: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Example:Associative Array<?php

$book=array('Title' => 'War and Peace', 'Author' => 'Tolstoy', 'Publisher' => "Oxford University Press" ); $book['ISBN'] = "0192833987"; // Add a new element echo "<b>\$book is $book.<br>"; echo "\$book['Title'] ". $book['Title'] .".<br>"; echo "\$book['Author'] is ". $book['Author'] .".<br>"; echo "\$book['Publisher'] is ". $book['Publisher'] .".<br>"; echo "\$book['Pages'] is ". $book['ISBN'] .".<br>";

?>

Page 57: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Programming PHP

• Sending text to the browser:– There are 3 main functions that are used to send

text to the browser:• print()• printf()• echo()

• Note that PHP is case insensitive• We will be using primarily echo() and printf()

during the module

Page 58: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

echo()

Page 59: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Examples

Use of echo with strings<?php$str = "Who's Anshe Chung?";echo $str;echo "<br />";echo $str."<br />I don't know!";?>

Echo with multiple lines<?phpecho "This textspans multipleLines but will print in a single line.";?>

//Note to make the test appear in multiple lines <pre> must be used in the html

Page 60: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Examples• Multiple Parameters

<?phpecho 'This ‘.'string ‘.'was ‘.'made ‘.'with multiple parameters';?>

• Difference of single and double quotes – items within single marks are treated literally, items within double quotes are extrapolated (variable name is replaced with its value)

• So in the following example single quotes will print the variable name, not the value:

<?php$color = "red";echo "Roses are $color";echo "<br />";echo 'Roses are $color';?>

Page 61: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

printf()

• The printf() function outputs a formatted string

• The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string

• This function works "step-by-step"• At the first % sign, arg1 is inserted, at the

second % sign, arg2 is inserted, etc.

Page 62: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Examples

Formatted Multiple Strings<?php$str = "Hello";$number = 123;printf("%s world. Day number %u",$str,$number);?>

Single String<?php$number = 123;printf("%f",$number);?>

Page 63: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

printf()

Page 64: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Printing variables within XHTML

<?phpprint "<HTML><HEAD><TITLE> String Example</TITLE>

</HEAD>";print "<BODY>";$first = “Sandra ";$last = “Moffett";$name = $first . $last; // string concatenationprint "<BR> name= $name";print "</BODY></HTML>"; ?>

name=Sandra Moffett

Page 65: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Conditional Statements• if statement

if ( test condition ) statement to execute if condition is true;

• else clauseif ( test condition )

statement to execute if condition is true;else

statement to execute if condition is false;

• elseif clauseif ( test condition1 )

statement to execute if condition1 is true;elseif (test condition2)

statement to execute if condition2 is true;

Page 66: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Conditional Statements• if statement

if ( test condition ) { one or more statements}

• else clauseif ( test condition ) { one or more statements} else { one or more statements}

• elseif clauseif ( test condition ) { one or more statements} elseif (test condition) { one or more statements}

Note the difference between standard and curly brackets

Page 67: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

67

The if statement

if ( $aver > 40 ) { $Grade="Pass"; print "Grade=$Grade";}print "Your average was $aver";

Statement(s) to executeregardless of test condition.

Execute these statementswhen $aver is greater than 40.

• no semicolon appears at the end of the if statement itself. Instead, curly brackets indicate a statement block, which may contain semicolons as required.

Page 68: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

68

The elseif clause• specifies an additional test condition to check

$found = 0; if ( $name == “John" ) {

print "Found - John";$found = 1;

} elseif ( $name == "Jane" ) {

print "Found - Jane";$found = 1;

} print "Name=$name and found=$found";

Execute these whenif condition is true .

Execute these whenthis condition is true

but previous is false .

Executeregardless of theprevioustest conditions.

Page 69: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

69

The else clause• used to specify a set of statements that execute

when all other test conditions in an if block are false

if ( $name == “Mark" ) {print “Found - Mark";

} elseif ( $name == "Jane" ) {

print “Found - Jane"; } else {

print "Could not validate Name=$name"; }

One or more statements to executewhen test condition is true.

One or more statements to executewhen this test condition is truebut the previous test condition is false.

One or more statements to executewhen the previous test condition(s) are false.

Page 70: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

70

if statement - example<?php$mark = 92; if ( $mark > 100 ) { print “Invalid mark > 100”;}elseif ( $mark < 0 ) { print “Invalid mark < 0”; } elseif ( $mark > 89 ){ print “Grade A”; } else { print “Not A standard”;} ?>

Page 71: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

71

Switch Statements• if-elseif statements are good when we need to choose an action from a small

number of options but they become difficult to read/manage when the number of options gets larger

• Sometimes we may want the same action to occur for a number of options and a different action for another set of options

• For these cases, PHP has a control structure called “switch”. The switch statement is not limited to numbers, strings can also be used

<?phpif ($i == 0) {    echo "i equals 0";} elseif ($i == 1) {    echo "i equals 1";} elseif ($i == 2) {    echo "i equals 2";} ?>

Page 72: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Switch Statements Example

<?phpswitch ($i) {    case "apple":        echo "i is apple";        break;    case "bar":        echo "i is bar";        break;    case "cake":        echo "i is cake";        break;}?>

72

Page 73: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Switch Statements• The switch statement executes statement by

statement. In the beginning, no code is executed • When a case statement is found with a value that

matches the value of the switch expression PHP begins to execute the statements

• PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement

• If you don't write a break statement at the end of a case’s statement list, PHP will go on executing the statements of the following case

73

Page 74: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Switch Statements<?phpswitch ($i) {    case 0:        echo "i equals 0 ";    case 1:        echo "i equals 1 ";    case 2:        echo "i equals 2 ";}?>

• If $i=0 the output will be:– i equals 0 i equals 1 i equals 2

74

Page 75: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Switch Statements• In order for the script to work, we need to add BREAKS:

<?phpswitch ($i) {    case 0:        echo "i equals 0 ";

break;    case 1:        echo "i equals 1 ";

break;    case 2:        echo "i equals 2 ";

break;}?>

• If $i=1 the output will be:– i equals 1

75

Page 76: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Switch Statements

• In a switch statement, the condition is evaluated only once and the result is compared to each case statement– In an elseif statement, the condition is evaluated

again– If your condition is more complicated than a

simple compare and/or is in a tight loop, a switch may be faster

76

Page 77: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

77

Looping statements• PHP supports four types of looping (or iteration)

statement:

– The for loop– The foreach loop

– The while loop– The do-while loop

• Used to repeat sections of code while certain conditions exist

bounded iteration

unbounded iteration

Page 78: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

78

The for loop

• Typically used when you know how many times the code should be repeated

for ( $i = 0; $i < $max; $i++ ) {

Set of statements to repeat}

Initializationexpression. Sets theinitial value of "$i"

Loop end condition

Iteration expressionIncrement $i each

loop iteration

note: use of semicolons

Page 79: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

79

The foreach loop

• Typically used to repeat a set of statements for every element in an array

• e.g.$items_array = (“A”, “B”, “C”);$value becomes “A” then “B” then “C”

foreach ($items_array as $value ) {

Set of statements to repeat}

An array value

Repeat the loop once forevery element in the list

Page 80: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

80

The foreach loop

• A variation can use both key and value from the array

• e.g.$items_array = (“A” => “Blue”, “B” => “Red”, “C” =>

“Green”);$key becomes “A” then “B” then “C”$value becomes “Blue” then “Red” then “Green”

foreach ($items_array as $key => $value ) {

Set of statements to repeat}

An array value.Repeat the loop once forevery pair in the list

Page 81: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

81

The while loop

• You use a while loop to repeat a section of code as long as a test condition remains true

while ( $ctr < $max ) {

Set of statements to repeat}

true

Repeat as longas the conditionaltest is

Conditionenclosedin parenthesis

Page 82: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

82

The do-while loop

• Operates just like the while loop except that it guarantees the statements inside the loop with execute at least once

do { Set of statements to repeat

} while ( $x < 100 )

Repeat while thiscondition is true

The "do"word startsthe loop

Page 83: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Notes on infinite loops• Always make sure your conditional statement is

appropriate in your for loops– Using relativity comparisons is safer than using

absolute ones• If you need to repeat a loop 6 times starting at 1, have your

comparison be $x<7 rather than $x==6• Unlike for loops where the control variable is

managed by the language, while and do-while loops require manual management of a control variable to avoid entering an infinite loop – while ($x<6){…} will enter an infinite loop if $x is never

modified inside the while loop

83

Page 84: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

84

Which loop to use?

• There is no rule that dictates which type of loop to use

• Often the same problems can be solved using different types of loop

• Use the construct which is the easiest for the task at hand

Page 85: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

85

Compound conditionals

• Logical conditional operators can test more than one test condition at once when used with if statements, while loops, and do-while loops

• For example, while ( $x < $max && $found != ‘TRUE’ )

• For clarity, it may be useful to group test conditions in parenthesiswhile ( ($x < $max) && ($found != ‘TRUE’) )

Page 86: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

The include() statement

• The include statement includes and evaluates the specified file

• Files are included based on the file path given or, if none is given, the include_path specified in php.ini. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing

• The include() construct will emit a warning if it cannot find a file

86

Page 87: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

When to use include()?

• Reuse of code• Setting up environmental variables• Reusable functions• Libraries

87

Page 88: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

88

PHP operatorsOPERATOR USAGE TYPE

+ Addition Arithmetic

- Subtraction Arithmetic

* Multiplication Arithmetic

/ Division Arithmetic

% Modulus (remainder after division)

Arithmetic

++ Increment Arithmetic

-- Decrement Arithmetic

= Assigns a value to a variable

Assignment

== Equality Comparison

!= Inequality Comparison

Page 89: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

89

OPERATOR USAGE TYPE

< Less than Comparison

> Greater than Comparison

<= Less than or equal to Comparison

>= Greater than or equal to Comparison

! Negation Logical

AND && And Logical

OR || Or Logical

_ Concatenation String

XOR Or not Logical

.= Concatenation to the value of a variable

Combined concatenation and assignment

+= Adds to the value of a variable

Combined concatenation and assignment

-= Subtracts from the value of a variable

Combined concatenation and assignment

Page 90: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

Catching errors

• PHP provides a feature that is very useful for catching errors:– or die(‘error message’)

• Usageinclude(‘myfile.php’) or die (‘“myfile.php” not found’);

– Will attempt to load and evaluate myfile.php, and output an error “myfile.php” not found if not successful.

• Execution of the script will exit on die90

Page 91: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

91

PHP Superglobals

• PHP provides a set of predefined variables accessible from anywhere within the executing script and provides us with substantial environmental information

• A script may require some variables be passed to it in order to do something

• One way to “share” data between scripts is by means of the $_GET superglobal

• The arguments to the script then get passed in the URL that calls the script

• These are called CGI variables, or parameters

Note CGI stands for COMPUTER GATEWAY INTERFACE

Page 92: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

92

Sending arguments (CGI variables) from a browser

• can be sent as a name-value pair after the CGI program URL, signalled by ‘?’

http://localhost/example/module.php?mymark=96

The argument name ismymark.

Its value is 96.

URL of the CGIprogram to start.

The "?" signals argument to follow.

multiple name-value pairs can be sent, separated by ampersands ‘&’

http://localhost/example/module.php?mygrd=56&myname=Ian

Query String

Page 93: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

How do we read them?

• The $_GET variable is in reality an associative array

• The index or “key” of the array is the name of the variable

• The value of the array at the “key” is the value of the variable.

http://localhost/example/module.php?mark=96

$a=$_GET[“mark”]); // a=96

93

Page 94: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

94

The Undefined value

• Before variables are first assigned, they have the undef value– behaves as a zero when used as a number– behaves as a zero-length string when used as a

string

• Many operators return undef when the arguments are out of range or are not sensible

Page 95: Introduction to PHP & MySQL Laboratory Setup. PHP - MySQL Commercial Sites: Apache http server MySQL PHP – XAMP (WAMP – MAMP) Required Tools – Text Editor

95

Testing for null values

• When receiving data from a browser, it is useful to test whether a CGI variable has a value at all$name = $_GET[“uname”]; if ($name) { statement(s) to execute when $name has a value} else { statement(s) to execute when $name has no value }

• The first if condition evaluates to true if $name has any value, otherwise the else clause will execute