0% found this document useful (0 votes)
916 views280 pages

PHP Final

PHP is most likely behind CGI / Perl in users, but its popularity is continually growing. PHP is a widely-used scripting language. It is used to create dynamic web sites that interface to databases or other data stores.

Uploaded by

Barkha Vijh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
916 views280 pages

PHP Final

PHP is most likely behind CGI / Perl in users, but its popularity is continually growing. PHP is a widely-used scripting language. It is used to create dynamic web sites that interface to databases or other data stores.

Uploaded by

Barkha Vijh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 280

PHP: The Basics

PHP Workshop

An Introduction to PHP Language

PHP Workshop

Website development tools Languages

PHP Workshop

Client-Side Definition
Scripts are run by the viewing web browser, usually in JavaScript. Do not have access to information located on the computer running the client-side script.

PHP Workshop

Server-Side Definition
Request is fulfilled by running a script (preprocessor) directly on the web server to generate dynamic HTML pages. Used to provide interactive web sites that interface to databases or other data stores. Advantage is the ability to highly customize the response based on the user's requirements, access rights, or queries into data stores.

PHP Workshop

Server-side v Client-side
Client-side Internet TCP IP DNS HTML VBScript Javascript CSS Java Applets ActiveX Flash ActionScript XML CGI ASP PHP JSP PERL .NET SQL Cold Fusion COM (VB, C#, C++) Java HTTP FTP Server-side

PHP Workshop

Server Side Uses


Session Control using Cookies Database Connections Counters Form Validation Emails Personalized Page Content Management Templates

Integration

PHP Workshop

PHP
Version Improvements 4.0.5 Largely performance-related, thanks to the Zend engine which can pre-compile scripts (verus run-time script interpretation of PHP 3.x). A number of features have also been added to the core API. You can read more about specific engine improvements at Zend's What's New site. Free PHP is fairly easy to get started with, and their superb support site provides lots of guidance and sample code to get you through complex issues. Even for large tasks, I would consider PHP to be only moderately complex to use. Take advantage of user support and discussions on USENET, accessible via Google Groups.

Cost

Complexity

Popularity

PHP is most likely behind CGI/Perl in users, but it is clear that PHP's popularity is continually growing. This is largely thanks to easy integration with Apache, a powerful language and an abundance of free/cheap hosting services with PHP abilities.
Cost, support sites, simplicity, powerful feature set, easy integration with Apache, excellent API to free databases such as MySQL and PostgreSQL. Missing enterprise features necessary for 24-by-7 sites, Web focus of language reduces its use outside of the Web (unlike Perl). Small to mid-sized Web sites. #

Strengths Weaknesses Best for...

PHP Workshop

PHP PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
PHP Workshop #

PHP Syntax (server side)


<html> <head> <title> Chicken Man Example </title> </head> <body> <p>My PHP code makes this page say:</p> <p> <?php // Comments here echo ("I am the CHICKEN MAN</p>"); ?> </body> </html>

PHP Workshop

PHP Syntax (client side)


<html> <head> <title> Chicken Man Example </title> </head> <body> <p>My PHP code makes this page say:</p> <p>I am the CHICKEN MAN</p> </body> </html>

PHP Workshop

Structure

PHP Workshop

What is PHP? Why PHP?

PHP Workshop

Review for the Previous Lectures


Static Webpage Webpage Dynamic Webpage: Server side PHP, Perl, JSP, ASP, HTML Documents Client side Javascript, Applet,

XML(eXtensible Markup Language)

HTML Documents

Client

HTTP (Hypertext Text Transfer Protocol) Using HTTP, Client/Server can talk with each others about how to transport HTML documents. ( HTML HyperText Markup Language)

Server

PHP Workshop

The Outline
PHP File Components: HTML, PHP Tag, PHP Statements, Whitespace, Comments

PHP Tag: <?php

. PHP Statements; .

?>

Syntax for PHP Statements: Variables: Submitted form variables, declaration, Operators: Arithmetic, String, Assignment, Reference, Control Structure: if, else, elseif, for, while
PHP Workshop #

What is PHP?
PHP is a server-side language designed specially for the web.
Conceived in 1994 by Rasmus Lerdorf PHP originally stands for Personal Home Page, now stands for PHP Hypertext Preprocessor Open source product

PHP code
Embed into an HTML page Be Interpreted by the web server to generate HTML or other output

The current major version: PHP 5


PHP Workshop #

What is PHP?
Server-side, scripting language Event based
Designed for use with HTML File Name .php Provide more flexibility than HTML alone Syntax is similar to C, Java, Perl
PHP Workshop #

PHP History
PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995. Personal Home Page/ Forms Interpreter - First Public release Version 3: 1997 PHP: Hypertext Preprocessor created by Andi Gutmans and Zeev Suraski Version 4: 2000 - Zend, full feature Actively supported by updates Version 4.4.6 on March 1, 2007 Version 5: 2004 New improved, Object Oriented & database connectivity The latest version Version 5.2.1 Stable

PHP Workshop

Why Use PHP?


Limits of HTML Open source & free ZEND is doing great! Job. Cross platform to develop, to deploy and to use: Window Macintosh Linux Powerful, Robust, scalable (Handle the traffic grow with you) Web development specific (Personal web site) Can be object oriented, especially in version 5 Great documentation in many languages

PHP Workshop

What is it?
PHP is a scripting language commonly used on web servers.
Stands for PHP: Hypertext Preprocessor Open source Embedded code Comparable with ASP Multiple operating systems/web servers

PHP Workshop

What is PHP?
PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. <? echo HI!; ?>
PHP Workshop #

What is PHP?
Compared to others like: Java Sun, compiled and interpreted (jsp) Perl Open Source, scripting .NET MS, opposite of Java ColdFusion Now Adobe, the original Javascript Netscape, client-side PHP Open Source, server-side
PHP Workshop #

Getting Started
1. How to escape from HTML and enter PHP mode
PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag.
HTML
PHP CODE

HTML

<?php echo Hello World; ?>

Starting tag
<?php <? <script language="php">

Ending tag Notes


?> ?> ?> Preferred method as it allows the use of PHP with XHTML Not recommended. Easier to type, but has to be enabled and may conflict with XML Always available, best if used when FrontPage is the HTML editor Not recommended. ASP tags support was added in 3.0.4
#

<%

%>

PHP Workshop

Getting Started
2. Simple HTML Page with PHP The following is a basic example to output text using PHP.
<html><head> <title>My First PHP Page</title> </head> <body> <?php echo "Hello World!"; ?> </body></html> Copy the code onto your web server and save it as test.php. You should see Hello World! displayed. Notice that the semicolon is used at the end of each line of PHP code to signify a line break. Like HTML, PHP ignores whitespace between lines of code. (An HTML equivalent is <BR>)
PHP Workshop #

Getting Started
3.

Using conditional statements


Conditional statements are very useful for displaying specific content to the user. The following example shows how to display content according to the day of the week.

<?php $today_dayofweek = date(w); if ($today_dayofweek == 4){ echo Today is Thursday!; } else{ echo Today is not Thursday.; } ?>

PHP Workshop

Getting Started
3.

Using conditional statements


The if statement checks the value of $today_dayofweek (which is the numerical day of the week, 0=Sunday 6=Saturday) If it is equal to 4 (the numeric representation of Thurs.) it will display everything within the first { } bracket after the if(). If it is not equal to 4, it will display everything in the second { } bracket after the else.
<?php $today_dayofweek = date(w); if ($today_dayofweek == 4){ echo Today is Thursday!; } else{ echo Today is not Thursday.; } ?>

PHP Workshop

Getting Started
3. Using conditional statements
If we run the script on a Thursday, we should see: Today is Thursday. On days other than Thursday, we will see: Today is not Thursday.
<?php $today_dayofweek = date(w); if ($today_dayofweek == 4){ echo Today is Thursday!; } else{ echo Today is not Thursday.; } ?>

PHP Workshop

Examples
PHP is a great way to implement templates on your website. How to implement a simple page counter

PHP Workshop

Examples

Step 1: Universal header and footer in a single file


Create a file called header.php. This file will have all of the header HTML code. You can use FrontPage/Dreamweaver to create the header, but remember to remove the closing </BODY> and </HTML> tags.

<html><head> <title>UCR Webmaster Support Group</title> <link rel="stylesheet" type="text/css" href=mycssfile.css"> </head> <body> <table width=80% height=30> <tr><td> <div align=center> Page Title </div> </td></tr></table>

PHP Workshop

Examples

Step 2: Universal header and footer in a single file


Next, create a file called footer.php. This file will have all of the footer HTML code.

<table width=80% height=30> <tr><td> <div align=center> UC Riverside Department<BR> <a href=mailto:[email protected]>[email protected]</a> </div> </td></tr></table> </body> </html>

PHP Workshop

Examples

Step 3: Universal header and footer in a single file


This is the basic template that you will use on all of the pages. Make sure you name the files with a .php extension so that the server will process the PHP code. In this example, we assume the header and footer files are located in the same directory.

<?php // header include(header.php); ?> Insert content here! <?php // footer include(footer.php); ?>
PHP Workshop #

Examples
Benefits: - Any changes to header or footer only require editing of a single file. This reduces the amount of work necessary for site maintenance and redesign. - Helps separate the content and design for easier maintenance
Header

Page 1 Content

Page 2 Content

Page 3 Content

Page 4 Content

Page 5 Content

Footer
PHP Workshop #

Examples
Step 1: Simple Page Counter
Download the counter file webcounter.txt onto your machine Upload the webcounter.txt file onto your web server (via FTP, WinSCP, etc) Change the file permissions of the webcounter.txt file to 777 to allow the counter file to be updated.

PHP Workshop

Examples
Step 2: Simple Page Counter
Copy this code into a page where you want a 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); } ?>
PHP Workshop #

Examples
Step 3: Simple Page Counter
Next, output the counter value using PHP. Copy this line after the main block of code.

This page has been viewed <?php echo$hits; ?> times.


Thats it! The result should look something similar to:

PHP Workshop

Examples
Step 3: Simple Page Counter You can change the text around the <?php echo$hits; ?> tags to your liking.

<?php echo$hits; ?> visitors.

This example shows 1. How to escape from HTML and enter PHP mode 2. How to output variables onto the screen using PHP

PHP Workshop

Examples
2. How to output variables using PHP
Echo is the common method in outputting data. Since it is a language construct, echo doesnt require parenthesis like print(). Output Text Usage: <?php echo Hello World; ?> // prints out Hello World

Output the value of a PHP variable: <?php echo $hits; ?> // prints out the number of hits
Echo has a shortcut syntax, but it only works with the short open tag configuration enabled on the server. <?= $hits ?>

PHP Workshop

Examples
3. Other uses with echo()

Automatically generate the year on your pages. This will print out 2004 UC Riverside. <?php echo date(Y); ?> UC Riverside
You will need to escape any quotation marks with a backslash. <?php echo I said \She sells sea shells\ ; ?>

PHP Workshop

Hot, Hot, Hot,


PHP Advantages: free, ease of deployment, ease of use and huge body of support in the industry. (ASP controlled by one company; only on IIS platform. JSP controlled by one company; hard to learn, slow, not free,) Based on open source software, LAMP is widely used in industry to run web servers: L - Linux A - Apache M - MySQL P - PHP
PHP Workshop #

Example: One Online Order Form


<html> <body> <form action=http://www2.comp.polyu.edu.hk/~csdwang/processorder.php method="get"> <table border="0"> <tr bgcolor="#cccccc"> <td width="150">Item</td> <td width="15">Quantity</td> </tr> <tr> <td>Tires</td> <td align="center"><input type="text" name="tireqty" size="3 maxlength="3"></td> </tr> <tr> <td>Oil</td> <td align="center"><input type="text" name="oilqty" size="3" maxlength="3"></td> </tr> <tr> <td>Spark Plugs</td> <td align="center"><input type="text" name="sparkqty" size="3" maxlength="3"></td> </tr> <tr> <td>How did you find Bob's?</td> <td><select name="find"> <option value = "a">I'm a regular customer</option> <option value = "b">TV advertising</option> </select> </td></tr> <tr> <td colspan="2" align="center"><input type="submit" value="Submit Order"></td></tr> </table> </form> # PHP Workshop </body> </html>

PHP Processing Example 1

processorder.php <html> <head> <title>Bobs Auto Parts Order Results </title> </head> <body> <h1>Bobs Auto Parts </h1> <h2>Order Results </h2> <?php echo <p>Order proceed.</p>; ?> </body> Ex </html>
PHP Workshop #

The Types of Text in a PHP File


processorder.php <html> <head> <title> Bobs Auto Parts Order Results </title> </head>

Five types of text: 1. HTML

2. PHP Tags (XML Style): <?php . ?>


3. PHP Statements. echo <p> Order Processed.</p>; 4. White space: newline, tab, space 5. Comments: (1) C style: /* . */ (2) C++ style (single line): //
#

<body> <h1>Bobs Auto Parts </h1> <h2>Order Results </h2> <?php echo <p>Order proceed.</p>; ?> </body> </html>

PHP Workshop

The main reason for using server-side script is to be able to provide dynamic content to a sites users.
Content changes according to users needs or over time Attract visitors coming back

PHP Processing Example 2: Adding Dynamic Data

Call PHP built-in function date():


<?php echo <p>Order processed at ; echo date(H:i, jS F); echo </p>; ?>

PHP Workshop

How it works
PHP is installed on web server Our web server is Apache (just an FYI) Server parses files based on extensions Returns plain HTML, no code

PHP Workshop

What can it do?


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

PHP Workshop

Windows Installation
PHP requires: Windows 98/Me or Windows NT/2000/XP/2003 Apache: http://httpd.apache.org/ PHP: http://www.php.net MySQL: Dev.mysql.com

PHP Workshop

Windows Installation All-in-one Packages

WAMP:
www.wampserver.com/en/index.php

XAMPP:
www.apachefriends.org

PHP Workshop

Text Editor
Dreamweaver, Zend Studio, NotePad Word processors are not good for PHP editing PHP designer Best editors have:
Syntax coloring/highlights Syntax hinting PHP Workshop
#

Dreamweaver
Since we will be using Dreamweaver as our IDE, let us spend some time on its basics.
1)Creation of a new site 2)Syntax highlighting

PHP Workshop

Popular PHP software


Blog/ CMS: WordPress, PHP blog, Drupal, CMSimple, Joomla, PHP website, Drupal, PHP(Reactor) School System: Moodle Forum: Prado, phpBB, Vanilla, BBPress

PHP Workshop

Ill be using:
XAMPP 1.6.6a
Apache HTTPD 2.2.8 + Openssl 0.9.8g MySQL 5.0.51a PHP 5.2.5 PHP 4.4.8 phpMyAdmin 2.11.4

Text Editor Dreamweaver Web Browser (Firefox)


PHP Workshop #

Fundamentals
PHP is embedded within xhtml pages within the tags: <?php ?> The short version of these tags can also be used: <? ?> Each line of PHP is terminated, like MySQL, with a semi-colon.

PHP Workshop

How To The Basics


Need to name files is a .php extension Example: index.php, mypage.php

Open and close tags: <? ?> Was: <?php ?>


Save file to server, view in a browser
PHP Workshop #

PHP Programming
<?php ?>

Short syntax

<?php phpinfo(); ?>

Note: create first first.php firstphp.swf

PHP Workshop

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

PHP Workshop

Preparing to code with PHP

PHP Workshop

Literals..
All strings must be enclosed in single of double quotes: Hello or Hello. Numbers are not in enclosed in quotes: 1 or 45 or 34.564 Booleans (true/flase) can be written directly as true or false.

PHP Workshop

Comments
// This is a comment # This is also a comment /* This is a comment that is spread over multiple lines */ Do not nest multi-line comments // recommended over #
PHP Workshop #

Comments
It is good practice to enter comments
//single-line comments are like this #or like this /* Multiple line comments*/

PHP Workshop

Comments
<?php // this is a comment echo Hello World!; /* another multi-line comment */ ?>
PHP Workshop #

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

PHP Workshop

Displaying data
<?php echo Hello World!<br />; echo(Hello World!<br />); print Hello World!<br />; print(Hello World!<br />); ?>
PHP Workshop #

Escaping Characters
Some characters are considered special Escape these with a backslash \ Special characters will be flagged when they arise, for example a double or single quote belong in this group

PHP Workshop

Escaping Characters
<?php
// Claire OReilly said Hello.

echo Claire O\Reilly ; echo said \Hello\.; ?>

PHP Workshop

PHP Variables
1. 2. 3. 4. 5. 6. 7. <?php $utterance = "I love you!"; echo ("I want to say: . $utterance); echo ("<p>"); $utterance = "I will smite you!"; echo ("I want to say: . $utterance); ?>

Line 1 tells the browser: "Start PHP code here". Line 2 creates the variable $utterance and sets it to "I love you!". Line 3 prints a phrase that draws on the variable $utterance. Line 4 creates a <p> tag in HTML Line 5 RE-SETS the variable $utterance to "I will smite you!". Line 6 prints a new phrase with the rest variable $utterance. Line 7 tells browser : PHP code ends here.

PHP Workshop

Variables Names
In PHP variable starts with a $ Followed by letter or underscore Can contain letters, numbers, underscores, or dashes No spaces Case-sensitive and $Student are different as it is case sensitive

$student

Global variable global $student Superglobals Automatically available throughout all program $_GET $_POST $_Request $_COOKIES $_SESSION

PHP Workshop

Examples of Variable Names:


$employee $Employee $NicEmployee (camel case) $Nic_Employee $Nic-Employee (Not a good practice) $Employee3 $_employee (Not a good practice) $__employee (Not a good practice)

PHP Workshop

Storing strings and numbers in variables

PHP Workshop

Note: variable1.php and variable2.php

Variables: What are they?


When we work in PHP, we often need a labelled place to store a value (be it a string, number, whatever) so we can use it in multiple places in our script. These labelled places are called VARIABLES

PHP Workshop

User-Declared Variables
No need to declare variables before using them. A variable is created when we first assign a value to it. Variable Types: Integer, Float, String, Boolean, Array, Object, NULL(for unassigned variable) and resource (for database)
PHP is a very weakly typed language.
The type of a variable is determined by the value assigned to it. Strangely, the variable type will changed according to what is stored in it at any given time. For example, $total = 0; //Integer $total = 0.00; //Float $total = Hello; //String # PHP Workshop

Testing and Setting Variable Types


Get & Set variable type functions: string gettype(mixed var); int settype( mixed var, string type); e.g. $a = 56; echo gettype($a).<br />; settype ($a, double); Reinterpret variable types: int intval(mixed val); float floatval(mixed var), string strval(mixed var) Test variable types: is_array(), is_double(), is_float(), is_real() is_long(), is_int(), is_integer() is_string(), is_object(), is_resource(), is_null() is_scalar(): if the variable is integer, boolean, string or float is_callable(): if the variable is a valid function is_numeric(): if the variable is any kind of number or a numeric string
#

PHP Workshop

Testing variable Status and Convert


Test status (setting or not): boolean isset(mixed var); Remove the setting:
void unset(mixed var);

Test if a variable exists and has nonempty, nonzero value: boolean empty(mixed var);
PHP Workshop #

Identifiers: the Names of Variables


Valid Identifier:
Identifier can be any length and can consist of letters, numbers and under-stores. Identifier can not begin with a digit. Identifier is case-sensitive. $tireqty is not the same as $Tireqty A variable can have the same name as a function. However, this usage could cause confusion and should be avoided.
PHP Workshop #

Variables in PHP
Assign value to a variable using =, e.g. $total = 0; $total_amount = 0.00; $total_amount = $total; Type Casting: $total_amount = (float) $total; Variable Variables: $varname = total; $$varname = 5; is equivalent to $total = 5; Useful to operate a list of variables in loops.
PHP Workshop #

Variable & Constant Scope


Built-in superglobals are visible everywhere (e.g., $_GET) Constants are visible globally Global variables declared in a script are visible throughout that script, but not inside functions. Variables used inside functions that are declared as global refer to the global variables of the same name. Variables inside functions declared as static are invisible from outside but its value is kept between one of the execution and the next one. Variables created inside functions are local to the function and are not visible from outside
PHP Workshop #

Built-in Superglobal Variables


GLOBALS An array of all global variables. Can access using $GLOBALS[myvar]. $_SERVER An array of server environment variables $_POST An array of variables passed via POST $_GET An array of variables passed via GET $_COOKIE An array of cookie variables $_FILES An Array of variables related to file uploads $_ENV An array of environment variables $_REQUEST An array of all user input including $_GET, $_POST, and $_COOKIE $_SESSION An array of session variables
PHP Workshop #

PHP Processing Example 3: Variables


<?php // create short variable names $tireqty = $_POST['tireqty']; ?> . <?php define('TIREPRICE', 100);
echo Tire ordered:. $tireqty. <br />; Echo Unit Price: .TIREPRICE .'<br />';

$totalamount = 0.00; $totalamount = $tireqty * TIREPRICE;


echo 'Subtotal for tire: $ . number_format($totalamount,2). '<br />'; ?>
PHP Workshop #

Variables
Variables are like a cup The same cup can hold lots of different things Same with variables

PHP Workshop

Variables
In PHP, you create a variable with a dollar sign and some text. Usually the text will be something descriptive of what it is going to hold. $name = Patrick Laverty; $dept = CIS; $campus_addr = Box 1885;
PHP Workshop #

Variables
There are many different kinds of variables in PHP Scalar Array Object

PHP Workshop

Scalar Variables
Hold single values String/text Numbers $name = Josiah; $dob = 1/1/23; $age = 84; $waist_size = 36;
PHP Workshop #

Array Variables
Hold multiple values All in one step example: $kids = Array(Tom,Dick,Harry); Multiple steps example: $kids = Array(); $kids[0] = Tom; $kids[1] = Dick; $kids[2] = Harry; Individual array values are just a scalar
PHP Workshop #

Array Variables
Associative Arrays may be easier to find stuff $teams = Array(bos=>Red Sox, nyy=>Yankees, bal=>Orioles); The two-step way works the same: $teams = Array(); $teams[bos] = Red Sox;
PHP Workshop #

Array

Note: arrays.php
PHP Workshop #

Object Variables
Well talk about these later.

Were in no rush
PHP Workshop #

Boolean and Null

Note: boolean.php
PHP Workshop #

Variables: Naming
$ followed by variable name

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

Name must started with a letter or an underscore


Followed by any number of letters, numbers and underscores
PHP Workshop #

Variables: example
<?php $name = Phil; $age = 23; echo $name; echo is ; echo $age; // Phil is 23 ?>
PHP Workshop #

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

PHP Workshop

Declare and Use Constants


Use the function: define() to define a constant: define(Constant_Name, value) For example, define(TIREPRICE,100); Convention: Use uppercase letter for constant so easy to distinguish between a variable and a constant. When refer a constant, dont put $ in front of it. e.g. echo TIREPRICE;

PHP Workshop

Constants
<?php define(NAME,Phil); define(AGE,23); echo NAME; echo is ; echo AGE; // Phil is 23 ?>
PHP Workshop #

Constants

Note: constant.php
PHP Workshop #

or ?
There is a difference between strings written in single and double quotes. In a double-quoted string any variable names are expanded to their values. In a single-quoted string, no variable expansion takes place.

PHP Workshop

or ? <?php $name = Phil; $age = 23; echo $name is $age; // Phil is 23 ?>
PHP Workshop #

or ? <?php $name = Phil; $age = 23; echo $name is $age; // $name is $age ?>
PHP Workshop #

Hello World
helloworld.php <html> <body> <? echo Hello World!; ?> </body> </html>
PHP Workshop #

Strings:

PHP Workshop

Strings concatenate:

Note: strings.php
PHP Workshop #

Strings function:

Note: strings2.php
PHP Workshop #

Calling Functions in PHP


The general form to call a function in PHP is like: echo date(H:i, jS F);
In the function: date(H:i, jS F), we use a string H:i, jS F to pass parameter. H: 24-hour format i: the minutes with a leading zero if required j: the day of the month without a leading zero S: represent the ordinal suffix ( e.g. 23th) F: full name for month
PHP Workshop #

Operators - Arithmetic Operators


Arithmetic Operators Operator Name Example + Addition $a + $b Subtraction $a - $b * Multiplication $a * $b / Division $a / $b % Modulus $a % $b For example: $a=27; $b=-21; $result = $a + $b;
Pre- and Post-Increment/Decrement: ++ -$a=4; echo ++$a; $a=4; echo $a++;

PHP Workshop

Operators - String Operators


. Concatenate two strings into one $a= Bobs ; $b= Alice ; $c=$a . $b; String Concatenation: echo $tireqty . tires<br />; echo $tireqty tires<br />; Note: Within double quotation marks, the variable name is replaced with its value. Within single quotation marks, the variables or any other text is sent unaltered. # PHP Workshop

Assignment Operators
= means set to. $tireqty = 1; //$tireqty is set to 1 Combination Assignment Operators
Operators Use Equivalent To

+= -= *= /= %= .=
PHP Workshop

$a +=$b $a -=$b $a *=$b $a /= $b $a %=$b $a .=$b

$a = $a + $b $a = $a -$b $a = $a * $b $a = $a / $b $a = $a % $b $a = $a . $b
#

Reference (&, an Ampersand)


Use reference operator, we can create an alias for another variable, e.g., $a = 5; $b = $a; $c = &$a; $a = 7; // At this point, $b=5 but $c=7
$a and $c point to the same piece of memory. To break this relation, we can use unset ():
unset($a) or unset($c). No change for the values of $a and $c, but remove the link between $a and $c.
PHP Workshop #

Comparison Operators
Comparison operators are use to compare two values, and it will return true/false,e.g. $a==$b will test if $a and $b have the same values. $a=5; $b=1; if( $a==$b ) and if ($a=$b) Operator Name Use == Equal $a==$b e.g. 0==0 true === Identical $a===$b e.g. 0===0 false != Not equal $a != $b !== Not identical $a !== $b <> Not equal $a <> $b < Less than $a < $b > Greater than $a > $b <= Less than or equal to $a <= $b >= Greater than or equal to $a >= $b
PHP Workshop #

Logical Operator
Operator ! && || and or Name Use Results NOT !$b Return true if $b is false and vice versa AND $a&&$b Return true if both $a and $b are true, otherwise false OR $a || $b Return true if either $a or $b are true, otherwise false. AND $a and $b Same with && but with lower precedence OR $a or $b Same with || , but with lower precedence

PHP Workshop

Bitwise Operator

Operator & | ~ ^ << >>

Name Bitwise AND Bitwise OR Bitwise NOT Bitwise XOR Left shift Right shift

Use $a & $b $a | $b ~$a $a ^ $b $a << $b $a >> $b

For shift operation, it is Shift $a left/right $b sits

PHP Workshop

Array Operator
Operators Name Use + Union $a+$b == === != <> !==
PHP Workshop

Result Return an array containing everything in $a and $b Equal $a== $b Return true if $a and $b have the same elements Identical $a===$b Return true if $a and $b have the same elements with the same order Inequal $a != $b Return true if $a and $b are not equal Inequal $a <> $b Return true if $a and $b are not equal Non-indentity $a != = $b Return true if $a and $b are not identical
#

Other Operators
Object: new, ->, instanceof Ternary Operator: ?:
condition ? Value_if_ture : Value_if_false $grade >=50 ? Passed : Failed

Error suppression operator: $a = @(57/0) // Suppress error warning Without @, generate divide-by-zero warning Execution Operator: a pair of backticks (`xxx`)
$out = `ls l`; //The content in the backticks is executed as //a command at the servers command line.
PHP Workshop #

Control Structure
if statement else statement elseif statement switch statement Repeating actions through iteration
while Loops for and foreach Loops do .. while Loops

Breaking out of a control structure & Script


Use break to jump out of loop Use continue to jump to next loop iteration Use exit to finish executing the entire PHP script

PHP Workshop

if, else, elseif statements


Examples:
if ($totalqty == 0) { echo You did not order anything<br />; } else if ($totalqty <50 ) { echo The num less than 50 <br />; } else { echo The num >= 50 <br />; }
PHP Workshop #

switch statements
Example: switch($find) { case a: echo <p>Regular Customer.</p>; break; case b: echo <p> Referred by TV. </p>; break; default: echo <p> Dont know how the customer found</p>; break; } PHP Workshop

while loops
Example: $num = 1; while ( $num < 5) { echo $num.<br />; $num ++; }
PHP Workshop #

for loops
Example:
for ($i= 1; $i <= 250; $i++) { $temp = i; echo $$temp.<br />; }
#

PHP Workshop

do .. while loops
Example:
$num = 100; do { echo $num.<br />; }while ($num > 100);

PHP Workshop

IF statement
If (expression)
Statement;

If($a>$b) {
Note: ifstatement.php
PHP Workshop

Echo a is larger than b; }


#

While Loop:
While (expression)
Statement;

While ($count<=10) {
Echo $count; $count++; Note: while.php }
#

PHP Workshop

Same example with for Loop:


For (Initial; expression; end)

Note: for.php
PHP Workshop #

Foreach Loop:
Foreach ($array as $value) Statement;

Note: foreach.php
PHP Workshop #

Continue and Break:

Note: continue.php
PHP Workshop #

Functions
Getting PHP to do some action for you echo() or print() phpinfo() (phpinfo.php)

PHP Workshop

User defined Function


// Value passes before the code executes is called arguments Function name ($arguments) Statement;

Note: function.php
PHP Workshop #

Function arguments

PHP Workshop

Predefined Function

Note: prefunction.php
PHP Workshop #

Echo/ Print function


echo

or & concatenation Note: hello.php hello2.php

PHP Workshop

Functions
Be lazy. Its a good thing. If youre going to do the same action more than once, write a function. sayhello.php function sayHello($toWhom) { echo Hello $toWhom; }

PHP Workshop

Functions
Lots have already been written for you: http://php.net/manual/en If you know the function: http://php.net/echo
PHP Workshop #

PHP GET
Built-in functions to get data from pages $_GET function collects values from a form sent with method = get HTML Page: <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> PHP Response: Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
PHP Workshop #

PHP POST
Get is limited to 100 characters
Not awesome

Post has 8Mb maximum


Awesome

PHP Workshop

PHP Post
HTML Page: <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> PHP Response: Welcome <?php echo $_POST["fname"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!
PHP Workshop #

Outline
This Lecture
File: Open, Read, Write, Lock, Array: Define, Access, Operate, Sort, String: Trim, Join, Split, Compare, Function: Include, Name, Parameter, Scope,

PHP Basics: History, Current Trend, File structure, PHP Tag, Syntax (variables, operators, Control structure)
PHP Workshop

Last Lecture

Part I: Data Storing and Retrieving with Files

PHP Workshop

Files
Files can be used to store/retrieve data Basic steps for read/write a file (similar to C)
1. Open the file 2. Read/write data from/to the file 3. Close the file
PHP Workshop #

Using fopen( ) to open a file


Usage: $fp = fopen( file_name, mode) file_name: file_path/file_name
Make sure that others have at least wx permission for the directory file_path
You can use a relative path based on the document root:
$DOCUMENT_ROOT = $_SERVER[DOCUMENT_ROOT] $fp = fopen( $DOCUMENT_ROOT/orders/order.txt, w);

(In our server (www2.comp.polyu.edu.hk), we do not have enough permission to create a file on the # PHP Workshop directory pointed by

How to get superglobal variables


We can use the following php file
Test if a server supports php Get all superglobal variables if it is supported.

<?php phpinfo(); ?>


PHP Workshop #

File Modes
Make three choices using mode when opening a file: 1. Open a file for reading only, writing only, or for reading+writing 2. If writing to a file, overwrite existing contents of a file or append new data to the end of the file. 3. If a file system differentiates binary and text files (like windows), you need to specify it.

PHP Workshop

File Modes for fopen( )


Mode
r r+ w w+ x x+ a

Name
Read Read write

Meaning

a+
b

t
PHP Workshop

Open for reading, beginning from the start of the file. Open for reading/writing, beginning from the start of the file. Open for writing, beginning from the start of the file. If the file already exists, delete its contents; otherwise, create it. write Open for reading/writing, beginning from the start of the file. If the file already exists, delete its contents; otherwise, create it. Cautious write Open for writing, beginning from the start of the file. If the file already exists, do not open it and return false Cautious write Open for reading/writing, beginning from the start of the file. If the file already exists, do not open it and return false Append Open for appending (writing) only, starting from the end of the existing contents. If it does not exist, try to create it Append Open for appending (writing) only, starting from the end of the existing contents. If it does not exist, try to create it Binary Used in conjunction with one of other modes. Default mode. Under unix file system, no difference for binary/text files; windows has. Text Used in conjunction with one of other modes. An option only for # windows.

Return from fopen( )


If a file is successfully opened, a resource handle will be returned; otherwise, false will be returned.

Gracefully terminate:
@ $fp = fopen("../phpfile/orders.txt", 'ab'); if (!$fp) { echo '<p><strong> Your order could not be processed at this time. .'Please try again later. </strong> </p> </body> </html>'; exit; }
PHP Workshop #

Optional Parameters for fopen( )


fopen( file_name, mode, true/false, parameters ); file_name: file path and name mode: open mode true/false: search/not search include_path parameters: when file name is prefixed with a protocol (e.g. http://, ftp://), extra parameters can # PHP Workshop be put here.

Write to a file
After a file is successfully opened, we can use fwrite() to write contents to it: fwrite($fp, $out_put_string) or fputs($fp, $out_put_string)
Another file write function without need to open a file:
int file_put_contents (string file_name, string data [, int flags [, resource context ] ] )

PHP Workshop

String Format
When putting delimiters such as tab, new line, , use \t, \n, An example: $out_put_string = $date.\t. $tireqty . tires \t. $address.\n;

PHP Workshop

Read from a file


string fread(resource $fp, int length); Read up to length bytes, to the end of the file or network pocket. string fgets(resource $fp, int length); Read one line from a file (it reads until it encounters \n, EOF or has read length bytes.) string fgetss(resource $fp, int len, string [allow_tag]); Similar to fgets except stripping out any HTML/PHP tags. array fgetcsv($fp, len [,string delimiter [,string enclosure]] ); Read one line and break it up whenever a delimiter is encountered where enclosure specifies what each field in a line is surrounded by (default ) char fgetc(resouce $fp);
PHP Workshop #

Read the whole file


int readfile(string file_name ) Read the whole contents to the standard output array file(string file_name) Read the whole contents to an array, each element of the array corresponds to a line in the file with \n int fpassthru(resource $fp); Read the whole contents to the standard output

PHP Workshop

Other Useful File Functions


fclose(resouce $fp) feof (resource $fp): Return true if the file pointer is at the end of the file. file_exists(string file_name) file_size(string file_name) unlink(string file_name): Delete a file rewind(resource $fp): reset the pointer fseek(resourc $fp, int offset): move the pointer ftell(resource $fp): how far into a file the file pointer is (bytes) bool flock(resource $fp, int operation): Lock file Check http://www.php.net/filesystem # PHP Workshop

Example
<?

. // open file for appending @ $fp = fopen("../phpfile/orders.txt", 'ab');


if (!$fp) { echo '<p><strong> Your order could not be processed at this time. ' .'Please try again later.</strong></p></body></html>'; exit; } fwrite($fp, $outputstring, strlen($outputstring)); fclose($fp); echo '<p>Order written.</p>';
PHP Workshop

?>

Problem using flat files


Processing is slow when a file is large Searching a particular record/group of records is difficult Concurrent access is problematic. Random access (e.g. find/insert/delete a record) is difficult No access control besides file permission.
To solve these problems, RDBMS is widely PHP Workshop used. We will study how to use Oracle through

Part II: Arrays

PHP Workshop

Arrays
In the previous lecture, we learn the scalar variable, a named location in which to store a value. An array is a named place to store a set of value, allowing you to group scalars. Element & Key (Index) The value stored in an array are called array elements; Each array element is associated with an index (also called key) in order to access the element. key value

For example, a[1]=6;


PHP Workshop #

Arrays
Numerically indexed Associatively indexed (maps) Multidimensional (combination of one or any of the above) Create an array with $var_name = array(); Index with $var_name[0] = assignment; or $var_name[$other_var] = assignment;
PHP Workshop #

Numerically Indexed Arrays


Initialize: use array or range
$product = array ( Tire, Oil, Spark Plugs); $numbers = range ( 1, 10); $even_num = range( 0, 10, 2); $letters = range(a, z);

Access: use key


$product[0], $product[1], $product[2] $number[0], , $number[9] $even_num[0], $letters[0],

PHP Workshop

Print Arrays
Use echo, e.g.: echo $product[0].' '.$product[1].' '.$product[2]; Use for with echo, e.g.:
for ($i=0; $i<3; $i++) echo $product[i]. ;

Use foreach with echo, e.g.:


foreach ($product as $current) echo $current. ;

PHP Workshop

Arrays with different Indices


PHP supports arrays in which you can associate any key (index) with each value. Initialize: $price = array ( Tire=>100, Oil=>10, Spark Plug => 4); Access: $price[Tire] $price[Oil] $price[Spark Plug]
PHP Workshop #

Print Arrays
Use echo: echo $price[Tire]. .$price[Oil]; Use foreach: foreach( $price as $key => $value ) echo $key.=>.$value.<br />; Use each: while ( $element = each ($price) ) echo $element[ key]..$element[value].<br />;
PHP Workshop #

Array Operator
Operators Name Use + Union $a+$b Result The array $b is appended to $a, but any key clashed are not added. == Equal $a== $b Return true if $a and $b have the same elements === Identical $a===$b Return true if $a and $b have the same elements with the same order != Unequal $a != $b Return true if $a and $b are not equal <> Unequal $a <> $b Return true if $a and $b are not equal !== Non-identical $a != = $b Return true if $a and $b are not identical
PHP Workshop #

Multi-dimensional Arrays
Initialize: $product = array (array ( T, Tire, 100), array (O, Oil, 10), array (S, Spark Plug, 4) ); Access & Display: echo $product[0][1].-. $product[0][2].<br />;

PHP Workshop

Sorting Arrays
sort( ): $product = array(Tire, Oil, Spark Plug); sort($product); Now the order in $product is Oil, Spark Plug, Tire.
For an array with descriptive keys, use asort() Sort it according to the value of each element ksort() Sort it according to the key of each element Reverse Sort: sort(), asort(), ksort() sort an array into ascending order rsort(), rasort(), rksort() sort an array into descending order
PHP Workshop

User-Defined Sorts
Use usort() you can define your own sorting Write your own compare function to tell PHP how to compare: function compare ($x, $y) { } usort( $product, compare);

PHP Workshop

Load Arrays from Files


Example: $order=file(../phpfile/order.txt); $num_order= count ($order); if ($num_order == 0) echo <p>No orders pending</p>; for($i=0; $i<$num_order; $i++) echo $order[$i].<br />;
PHP Workshop #

Other Useful Function


Count number of elements of an array: count(), sizeof(), array_count_values(); Reordering arrays: shuffle( ): Randomly reorder elements of an array array_reverse( ): Create a new array with reverse order. Navigating arrays: each( ), current( ), Check http://www.php.net/array for more information.

PHP Workshop

Part III: String Manipulation and Regular Expression

PHP Workshop

Format Strings
trim( ), ltrim( ), rtrim( ): trim( ): Strip whitespace from the start and end of a string ltrim( )/rtrim( ): strip whitespace from the start / from the end. printf( ): printf(Total amount %.2f, $total);
PHP Workshop #

nl2br( ): newline <br /> tag


$feedback = \n name:Jason \n email:[email protected]\n; <?php echo $feedback; ?> name: Jason email:[email protected] <?php echo nl2br($feedback); ?> name: Jason email:[email protected] PHP Workshop

Change the Case of a String


strtoupper( ) Turn string to uppercase strtolower( ) Turn string to lowercase

ucfirst( )
ucwords( )

Upper case first character


Upper case first character of each word

PHP Workshop

Add/Strip slashes for database storage


addslashes( ): add backslash to special characters such as quotation marks, backslashes and NULL character. stripslashes( ): remove backslash. The system can automatically add backslashes if magic_quotes_gpc is set on. Using get_magic_quote_gpc( ) to check if it is on (return true if it is on). If it is on, need to call stripslashes( ) before displaying user data.

PHP Workshop

Join and Split Strings


array explode( string separator, string input [, int limit]) $email= [email protected]; $email_array = explode(@, $email); $email_array[0] csdwang $email_array[1] comp.polyu.edu.hk string implode( string separator, array input [, int limit]) string strtok( string input, string separator): String to token
$token = strtok ($feedback, ); echo $token.<br \>; while( $token != ) { $token = strtok( ); echo $token.<br />; PHP Workshop }

Return a substring by substr( )


string substr( string str1, int start [, in length] ) Example: $test=Your customer service is excellent; substr($test, 1) : from the beginning, offset 1 return our customer service is excellent substr($test, -9): from the end, offset -9 (reverse) return excellent substr($test, 0, 4): from the beginning, offset 0, length 4 return Your

PHP Workshop

Comparing Strings
int strcmp( string str1, string str2) equal return 0 greater (lexicographic order) a number > 0 less (lexicographic order) a number < 0 int strcasecmp( ): not case sensitive

PHP Workshop

Matching & Replacing Strings


string strstr( string haystack, string needle) Look for the needle from the haystack: if found, return the haystack from the needle onward; otherwise, return false. stristr( ): not case sensitive

PHP Workshop

Replace Substrings
mixed str_replace(mixed needle, mixed new_needle, mixed haystack [,int &count] ) ); Replace all instances of needle in haystack with new_needle.

string substr_replace( string str, string replacement, int start [, int length]); Replace the part of the string with replacement

PHP Workshop

Finding Substrings with Regular Expression


Find substring with Regular Expression int ereg( string pattern, string input, array $match); If a pattern is found in input, it will be stored in array $match. int eregi( ): not case sensitive.
The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format: <?php if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) { echo "$regs[3].$regs[2].$regs[1]"; } else { echo "Invalid date format: $date"; } # PHP ?> Workshop

Replacing/Splitting Substrings with Regular Expression


Replace substring with Regular Expression int ereg_replace ( string pattern, string replacement, string input_string); Split strings with regular expression array split( string pattern, string input [, int max]); Spit the input string into substrings based on the pattern and return the substrings in an array. Example: $addr = [email protected]; $arr = split(\. | @, $add); while ( list($key, $value) = each ($arr) ) PHP Workshop echo <br />.$value;

Part IV: Functions

PHP Workshop

require( ) and include( )


Using require( ) and include( ), we can include any type code. For example: reuse.php <?php echo Reuse code<br />; ?> main.php <?php echo Main file<br />; require( reuse.php ); ?> include() is almost identical with require() except that after failure, include() gives a warning while require() gives a fatal error.

PHP Workshop

A Basic Form
How we do things now: eform.cgi <form method=POST action=http://www.brown.edu/cgilocal/eform.cgi> <input type=text name=name> <input type=text name=age> <input type=submit> </form>

PHP Workshop

Accessing Form Variables


In order.htm: <html><body><form .. method=post> <table> <tr> <td>Tires</td> <td align="center"><input type="text" name="tireqty" size="3 maxlength="3"></td> </tr>

In PHP, all variables start with $. We can access each form fields as a PHP variable related to the name of the form field. Three ways: $tireqty //short style $_POST[tirety] //medium style. Recommend!!! $HTTP_POST_VARS[tireqty] //long style
PHP Workshop #

Accessing Form Variables in PHP


If a form is submitted using
The POST method: access data using
$_POST[field_name] , e.g., $_POST[tireqty]

The GET method, access data using $_GET[field_name] ,e.g., $_GET[tireqty] In both cases, we can use $_REQUEST[field_name]. e.g. $_REQUEST[tireqty]
PHP Workshop #

A Basic Form
How we do things with PHP: basicform.html <form method=POST action=output.php> <input type=text name=name> <input type=text name=age> <input type=submit> </form>
PHP Workshop #

A Basic Form
Capturing the data in output.php Variables:
$_POST[name] $_POST[age]

Use phpinfo() to see variables


PHP Workshop #

A Basic Form
Weave HTML and PHP output.php
<html><body> <? $name = $_POST[name]; $age = $_POST[age]; echo My name is $name and I am $age years old; ?> </body></html> # PHP Workshop

Data Validation

Well talk more about validating user input later.

PHP Workshop

A Basic Form
Outputting to the screen is nice, but boring We could email the results Lets store data in a database

PHP Workshop

Layers of a Database
Server Database Tables Fields/Columns Records Data

PHP Workshop

How to Get a Database


Use Microsoft Access Use Filemaker Request a MySQL Database (http://brown.edu/db)

PHP Workshop

Request a MySQL Database


You will receive:
Server name (its not localhost) Database name Username Password Link to phpMyAdmin

PHP Workshop

phpMyAdmin
phpMyAdmin is a graphical view of your database Very easy Lets take a look (http://brown.edu/phpMyAdmin)

PHP Workshop

Connecting to DB from PHP


Create one connection script: dbconn.php <?
$conn = mysql_connect($server,$user,$pw); mysql_select_db($db,$conn);

?>
PHP Workshop #

Connecting to DB from PHP


Remember, Be Lazy! At the top of each file that needs the DB: <? require(dbconn.php); ?>

PHP Workshop

Database Table
Table named info has two fields, name and age Use a SQL INSERT statement:

$sql = INSERT INTO info (name,age) values ($name, $age);

PHP Workshop

Database Table
Send it to the Database: mysql_query($sql,$conn);

PHP Workshop

The Whole Picture


dbinsert.php <? require(dbconn.php); $name = $_POST[name]; $age = $_POST[age]; $sql = INSERT into info (name,age) values($name, $age); mysql_query($sql,$conn);

?> <html><body> Thank you, your name and age were received. </body></html>

PHP Workshop

The Whole Picture - Fancier


fancydbinsert.php <? require(dbconn.php); $name = $_POST[name]; $age = $_POST[age]; $sql = INSERT into info (name,age) values($name, $age); $success = mysql_query($sql,$conn); ?> <html><body> <? if($success) { echo Thank you, your name and age were received.; } else { echo Sorry, your info wasnt received, please contact ; } ?> # PHP Workshop </body></html>

Getting the Info Back


Read it in phpMyAdmin Create an output page
(Just like that little survey you filled out)

PHP Workshop

Create an Output Page


Connect to the Server Do a query of the data Programmatically write the data to a page View the page in a browser Lets see how to do it

PHP Workshop

Connect to the Server


First, include our connection script: <? require(dbconn.php); ?>

PHP Workshop

Do a Query of the Data


This time we use SELECT $sql = SELECT name, age FROM info;

Or if you have many fields and want to be LAZY!


$sql = SELECT * from info;

PHP Workshop

Programmatically Write the Data


Heres the only hard part: <table border=1> <? $result = mysql_query($sql, $conn); while($table = mysql_fetch_object($result)) { echo <tr><td>; echo $table->name; echo </td><td>; echo $table->age; echo </td></tr>; } ?> PHP Workshop </table>

Putting it All Together


statuspage.php <? require(dbconn.php); $sql = SELECT * FROM info; $result = mysql_query($sql, $conn); ?> <html><body> <table border=1> <? while($table = mysql_fetch_object($result)) { echo <tr><td>; echo $table->name; echo </td><td>; echo $table->age; echo </td></tr>; } ?> <table> PHP Workshop </body></html>

I Hate Objects!
If you dont like using mysql_fetch_object:
mysql_fetch_array($result) mysql_fetch_assoc($result)

PHP Workshop

mysql_fetch_array()
Access the columns by numbers: while($array = mysql_fetch_array($result)) { echo $array[0]; echo $array[1]; }
PHP Workshop #

mysql_fetch_assoc()
Access the columns by column names: while($array = mysql_fetch_assoc($result)) { echo $array[name]; echo $array[age]; }
PHP Workshop #

One Helpful Function


nl2br() Line breaks in a form are not respected This function will turn a newline (nl) character into (2) an html <br> (br) tag.

PHP Workshop

Data Validation
Very Important! Without it, your site and all others can be hacked! PHP makes it easier

PHP Workshop

Data Validation
Cut down on XSS with htmlentities() Cut down on SQL-injection with mysql_real_escape_string() Check that youre getting what you expect Check that youre getting the length you expect Dont trust JavaScript
PHP Workshop #

Data Validation
Cross site scripting vulnerability
Allows a user to input scripts Allows a user to input links to malicious sites Allows a user to steal a session/cookie/password

The htmlentities() function turns entities into its harmless entity number. A is turned into &#39;
#

PHP Workshop

Data Validation
SQL-injection vulnerability
Allows a user to directly access your database Allows a user to get access to other accounts Allows a user to read data you dont want read

Prevention can be as simple as escaping quotes with mysql_real_escape_string to all user input $clean_user = mysql_real_escape_string($_POST[username]) # PHP Workshop ;

Data Validation
Get what you expect to get Dont change it, give error message
Example: (validinsert.php) Age, should be less than 110, and numeric. Reject anything else if(strlen($age)>3){ //error message } if(!is_int($age)){ //error message } if($age>110 || $age<18){ //error message }
PHP Workshop #

Data Validation
Get the length you expect
<input type=text name=username maxlength=8>

Make sure the username is no longer than 8


if(strlen($username)>8)){ //error message }

PHP Workshop

Data Validation
Dont trust JavaScript Do client side AND server side validation

PHP Workshop

Overview of phpMyAdmin

Creation of a new DB Insertion of a record


PHP Workshop #

CRUD Create, Read, Update, Delete

Note: mysql1.php
PHP Workshop #

Insert

PHP Workshop

Update

PHP Workshop

Delete

PHP Workshop

PHP and Databases: Overview


Open a connection to the database - PHP returns a "connection resource" Run a query - PHP returns a query "result resource" Do something with the result - display output to user or do some other actions Close the connection resource - tell database and PHP we don't need it any more
PHP Workshop

Connecting to a Database
PHP Postgresql Functions: http://www.php.net/manual/en/ref.pgsql.php pg_connect() returns a connection resource that is needed by other PostgreSQL functions. <?php $username = cs386"; $password = "introdb"; $databasename = cs386"; $hostname = "db.cecs.pdx.edu";
$connection = pg_connect("host=$hostname dbname=$databasename user=$username password=$password") or die ("Could not connect"); // do stuff pg_close($connection); ?>
PHP Workshop #

Connection Errors
<?php $username = cs386"; $password = "foobar"; // wrong password $databasename = cs386"; $hostname = "db.cecs.pdx.edu";
$connection = pg_connect("host=$hostname dbname=$databasename user=$username password=$password") or die ("Could not connect"); // do stuff pg_close($connection);?>

Error Message
Warning: pg_connect(): Unable to connect to PostgreSQL server: FATAL: Password authentication failed for user cs386" in ./display.php(433) : eval()'d code on line 7 # PHP Workshop Could not connect

Executing a Query on a Connection: pg_query

<?php // assuming we already connected with code from previous slide... $query = " SELECT DISTINCT N.candname, N.party FROM candcl N; "; $result = pg_query($connection, $query)

PHP Workshop

Query Result Errors


If we had said SELECT DISTINCT foobar

We would have seen the error message Warning: pg_query(): Query failed: ERROR: column "foobar" does not exist in ./display.php(433) : eval()'d code on line 20 Query error: ERROR: column "foobar" does not exist
PHP Workshop

Note: Postgresql automatically folds all

Retrieving tuples: pg_fetch_row pg_fetch_row returns each row as an


enumerated array
<?php echo pg_num_rows($result) . " rows returned\n"; $row = 0; while ($row = pg_fetch_row($result)) { echo "Name: $row[0]<br>\n"; echo Party: $row[1]<br>\n"; } ?>

Output
4 rows returned Name: MCCAIN, JOHN S. Party: REP PHP Workshop

Fetching rows as objects <?php


$num = pg_numrows($result); echo '<table border="1">'; for($count=0; $count < $num && $data=pg_fetch_object($result,$count); $count++){ printf("<tr>\n"); printf(" <td>%s</td>\n",$data->candname); printf(" <td>%s</td>\n",$data->party); printf("</tr>\n"); } echo "</table>\n"; ?> Output: MCAIN JOHN S. OBAMA, BARACK SMITH, GORDON MERKLEY, JEFFREY REP DEM REP DEM
#

PHP Workshop

Calling pg_fetch_array() will return an enumerated and an associative array <?php $array = pg_fetch_array($result); echo "Name: $array[candname"]<br/>\n"; echo Party: $array[party"]<br/>\n";
PHP Workshop

Fetching rows as arrays

echo "Name: $array[0]<br/>\n";

<?php $username = "akimbo_ro"; $password = "readme"; $databasename = "akimbo"; $hostname = "db.cecs.pdx.edu"; $connection = mysql_connect($hostname, $username, $password) or die ("Could not connect");
mysql_select_db($databasename) or die("Database select error: " . mysql_error()); $query = " SELECT DISTINCT N.candname, N.party FROM candcl ); "; $result = mysql_query($query, $connection) or die("Query error: " . mysql_error()); echo mysql_num_rows($result) . " rows returned\n"; while ($row = mysql_fetch_row($result)) { echo "Name: $row[0]<br/>\n"; echo Party: $row[1]<br/>\n"; } mysql_close($connection); ?>
PHP Workshop #

Example for MySQL

PHP + MySQL = Sweet


MySQL is an open source database software solution Enables rich web applications when combined with PHP

PHP Workshop

Image Source: http://www.mysql.com/

Rainfall Application
Read the contents of a database Get the rainfall data Parse the results Display it

PHP Workshop

Connecting to a Database
PHP Has a set of functions that can be used with MySQL First step is to setup a link to the desired database

PHP Workshop

Making a Query
Once a link is established, querying is easy Errors for any given function are returned by mysql_error()

PHP Workshop

MySQL Result Set


The value returned by mysql_query() is a reference to an internal data structure It can be parsed by various functions

PHP Workshop

Associative Arrays
An array that can be indexed by a string A set of key->value pairs Very similar to a hash in Perl

PHP Workshop

PHP foreach
Similar to the Perl equivalent Allows iterating through each element of an array

PHP Workshop

Put it All Together

PHP Workshop

PHP Workshop

The Results

PHP Workshop

http://128.174.242.224/PHPExamples/rainfall.php

A Slight Improvement
This was not the exact code we came up with I added some titles and a neat trick
Highlight every other row in the table This makes information more readable

PHP Workshop

PHP Workshop

SQL | PHP

Tutorial
at 8am. god, its early.

PHP Workshop

SQL intro
There are many different versions of SQL available for usage. Oracle MySQL SQLite DB2 Mimer The popular ones are Oracle and MySQL with MySQL quickly gaining ground. Ill be showing you MySQL. The syntax between SQL domains varies little and with google skills you can adjust this knowledge for SQLite, which Ive # PHP Workshop never used.

Databases _ creation
CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(name) ); Types of attributes: char, varchar, int, smallint, decimal, date, float, etc. *varchar is a string with varying # of characters. In our example, 55 is the characters longest possible string allowed. *decimal(10,2) indicated 2 places after the decimal point and 10 total digits (including the decimal numbers)

PHP Workshop

Databases _ creation 2
CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1) NOT NULL, age INT(3), birthdate DATE, salary DECIMAL(10,2) DEFAULT 0.00, primary key(name) ); Primary key: primary key is a UNIQUE value. For every entry in your database this must be unique and not null and every DB must have one. NOT NULL: column must have a value DEFAULT: you can set a default value if no other value is inputted for # PHP Workshop that column.

Databases _ indexed primary keys specifying a column as a primary key you can have the Instead of
database create a column of numbers that will automatically increment with each entry inserted into the DB. Example: CREATE TABLE tableName ( id INT AUTO_INCREMENT, name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(id) );
PHP Workshop #

Entry 1 will have 1 as a key. Entry 2 will have 2 and so forth.

Databases _ deletion
DROP TABLE tableName;

PHP Workshop

Databases _ insertion
Inserting data in the database: INSERT INTO tableName(name,sex,age) VALUES(Mr. Freeze,M,42); Also valid: INSERT INTO tableName(sex,name,age) VALUES(F,Mr. Freeze,42); Order doesnt matter.

PHP Workshop

Databases _ the meat


Always in the form of: SELECT . FROM . WHERE . So select a column from your database. From a database Where x meets y condition. * Except in the case of modification

PHP Workshop

Databases _ updating
Suppose we want to change Mr. Freezes age to 52.

UPDATE tableName SET age = 52 WHERE name LIKE Mr. Freeze And so forth.

PHP Workshop

Databases _ aggregates
This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, Ill show a quick example with each. The only way to really know this stuff is practice. Group by Count Sum Avg Min/Max Order by

PHP Workshop

Databases _ group by
This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, Ill show a quick example with each. The only way to really know this stuff is practice. Group by lumps all the common attributes into one row. SELECT employee_id, MAX(salary) FROM Works_In GROUP BY dept_id; * MAX selects the maximum value in its () likewise for MIN

PHP Workshop

Databases _ count
Count counts the number of columns with the specified attribute.

SELECT term, COUNT(course_id) FROM teaches GROUP BY term; We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.

PHP Workshop

PHP Workshop

PHP _ connecting to the db


This is the basic connect script for accessing your db:

<?php mysql_connect(localhost,username,password) or die(mysql_error()); ?>


Localhost indicates the current machine. So youre asking the machine to connect to itself. The die(mysql_error) part says if theres an error halt everything and display this error. If it errors on this part, it means either your host, username, or password are wrong.

PHP Workshop

PHP _ error checking w/ echo


Consider the connection script again with this modification:

<?php mysql_connect(localhost,username,password) or die(mysql_error()); echo Connected to database. ?>


Later on you may be unable to differentiate where the error occurred. So while developing your code throw in some echo statements, they just print stuff to the screen. When PHP is done connecting to our database it tell us.

PHP Workshop

PHP _ select the database.


<?php mysql_connect(localhost,username,password) or die(mysql_error()); echo Connected MySQL!; mysql_select_db(ljlayou_comp353 or die(mysql_error()); echo Connected to database 353; ?>

PHP Workshop

PHP _ create/drop table


<?php mysql_connect(localhost,username,pw) or die(mysql_error()); mysql_select_db(ljlayou_comp353 or die(mysql_error()); mysql_query(CREATE TABLE Works_In()) or die(mysql_error()); ?> Were querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this. Again we tell php to stop everything if an error occurs.

PHP Workshop

PHP _ insertion
<?php mysql_connect(localhost,username,pw) or die(mysql_error()); mysql_select_db(ljlayou_comp353 or die(mysql_error()); mysql_query(INSERT INTO Works_In(company,position) VALUES(McDonalds,fry cook)); ?> Were querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this.

PHP Workshop

PHP _ selecting a table


In order to manipulate, fetch, etc data from your database you must have PHP remember the result. So we store it in an array (?) to preserve columns. PHP variables unlike Java do not need a type declaration. From now on Ill be omitting the connect stuff. <?php [] $result = mysql_query(SELECT * FROM Works_In) or die(mysql_error()); $row = mysql_fetch_array($result); echo company: .$row[company]; echo position: .$row[position]; ?> From these lines we see that each cell in the area is labeled under the column name. Using this method we can output or even compare data.

PHP Workshop

PHP _ selecting a table


In order to manipulate, fetch, etc data from your database you must have PHP remember the result. So we store it in an array (?) to preserve columns. PHP variables unlike Java do not need a type declaration. From now on Ill be omitting the connect stuff. <?php [] $result = mysql_query(SELECT * FROM Works_In) or die(mysql_error()); $row = mysql_fetch_array($result); echo company: .$row[company]; echo position: .$row[position]; ?> From these lines we see that each cell in the area is labeled under the column name. Using this method we can output or even compare data. The * symbol in the SELECT statement just means that we select all the columns in the table. The above statement however results in the first row only being shown.
#

PHP Workshop

PHP _ selecting a table 2


To solve this problem, we loop continuously until there are no more rows to choose from.

<?php []
while ($row = mysql_fetch_array($result)) { echo company: .$row[company]. | position: .$row[position]; echo <br/>;} ?> If you have noticed the . symbol signifies a concatenation.

PHP Workshop

PHP _ the formula


We looked over it all. Heres the general formula:

<?php

mysql_connect(localhost,username,pw) or die(mysql_error()); mysql_select_db(databaseName or die(mysql_error());


$result = mysql_query(yourQuery) or die(mysql_error()); $row = mysql_fetch_array($result); while ($row = mysql_fetch_array($result)) { }; ?> (Show 255 final)

PHP Workshop

PHP Workshop

PHP _ form processing


Topic job but its all good. Im assuming you know how to create forms in HTML. Else, well, google it. Its pretty straight forward. So lets take this form as our example, this is a snippet of the form code: <form name=animas action=processform.php" method="post> [] <b>FUN</b>: <input type="radio" name="extra" value="horns">Horns <input type="radio" name="extra" value="wings">Wings <input type="radio" name="extra" value="mane">Mane <input type="radio" name="extra" value="giraffe">Giraffe Neck <input type="submit" name="submit" value="imagine it" class="submit" /> </form>
PHP Workshop #

PHP _ form processing 2


Our form action tells the form what to do with the data. POST is a method that sends an array of variables, our data. Only when the submit button is pressed is the data sent. <form name=animals action=processform.php" method="post> [] <input type="submit" name="submit" value="imagine it" class="submit" /> </form> It is common practice to create a separate file for form processing.

PHP Workshop

PHP _ form processing 3


Our data is now winding through the PHP tubes. Lets look how its processed.

$_POST[submit] if( $dbc = @mysql_connect(localhost,username,pw)) { if(!@mysql_select_db(database)) { die(mysql_error());} } else { die(mysql_error());}


$query = INSERT INTO animals(id,data,appendages, tail, sound,extra) VALUES(0,{$_POST[body]},{$_POST[appendages]}, [] ) if(@mysql_query($query) { else { print you lose;} mysql_close(); print success;}

PHP Workshop

PHP _ form processing 4


Some notes on the previous slide: - @ symbol means success or halt script. - mysql_close(); its very important to close your connection when youre done

PHP Workshop

Basic MySQL Syntax


SHOW DATABASES; USE database_name; SHOW TABLES; DROP TABLE table_name;
PHP Workshop #

Create MySQL Table


CREATE TABLE user (name varchar(9) NOT NULL, id int(6) NOT NULL, PRIMARY KEY (id), UNIQUE (id) );

PHP Workshop

Add/Delete/Update Table
INSERT INTO user VALUES (bond, 007); DELETE FROM user WHERE id=007; UPDATE user SET name=BOND WHERE id=007;
PHP Workshop #

Query Database
SELECT * FROM user; SELECT * FROM user WHERE name=BOND; SELECT DISTINCT name FROM user; SELECT name, id FROM user ORDER BY name;

PHP Workshop

PHP User Front-End


<html> <body> <?php $variable=271004"; echo $variable; ?> </body> </html> Script is executed server side and presented to user via a browser. PHP code is rendered as plain HTML.
PHP Workshop #

PHP Configuration File


Use a securely positioned config file to store variables.
<? // configuration parameters // database configuration $host = "macneill.cs.tcd.ie"; $user = username"; $pass = password"; $db = username_db"; // default contact person $def_contact = Karl"; ?>
#

Other PHP pages can link to it and use the variables as their own.
PHP Workshop

PHP Add to DB Code 1


<table cellspacing="5" cellpadding="5"> <form action="addUpdate.php" method="POST"> <tr> <td valign="top"><b><font size="1">Title</font></b></td> <td><textarea name="title" cols="40" rows="2"></textarea></td> </tr> <tr> <td valign="top"><b><font size="1">Authors</font></b></td> <td><textarea name="authors" cols="40" rows="2"></textarea></td> </tr>

<inut type="Submit" name="submit" value="Add"></td></tr> </form> </table>

PHP Workshop

PHP Add to DB Code 2


<?

include("conf.php");
// form submitted so start processing it

$title = $_POST["title"];
$authors = $_POST["authors"]; // set up error list array & validate text input fields $errorList = array(); $count = 0; if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } // set default value for contact person if (!$contact) { $contact = $def_contact; } // check for errors & if none found... if (sizeof($errorList) == 0) {

$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");


mysql_select_db($db) or die ("Unable to select database!");

$query = "INSERT INTO papers (title, authors, description, comment, super, bibtex, url, genre) VALUES ('$title', '$authors', '$description', '$comment', '$super','$bibtex','$url','$genre')"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
echo "<font size=-1>Addition successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</font>"; // close database connection

mysql_close($connection);
} else {// errors occurred} ?> PHP Workshop

PHP Query Code


include("conf.php");

$connection = mysql_connect($host, $user, $pass) or die (); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT * FROM papers"; $result = mysql_query($query) or die ("Error in query);
?> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt="" height="2"></td></tr> <? // if records present

if (mysql_num_rows($result) > 0)
{ // iterate through resultset & print title with links to edit and delete scripts

while($row = mysql_fetch_object($result))
{ ?> <font size="-2"><a href="edit.php?id=<? echo $row->id; ?>">edit/view</a> | <a href="delete.php?id=<? echo $row->id; ?>">delete</a></font><p>

<font size="-1"><b><? echo $row->title; ?></b><br> <font size="-1"><b>-<? echo $row->authors; ?></b>
<br><a href="<? echo $row->url; ?>" target="_blank"> pdf</a> <br><br><br> </font> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt=" height="2"></td></tr> <? } } // if no records present else{}

mysql_close($connection);
?>

PHP Workshop

PHP Delete Code


include("conf.php"); // form not yet submitted, display initial form with values pre-filled $id=$_GET['id']; { // open database connection $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); // select database mysql_select_db($db) or die ("Unable to select database!"); // generate and execute query $query = "DELETE FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // close database connection mysql_close($connection); // print result echo "<font size=-1>Deletion successful. <br><br><a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</font>"; }

PHP Workshop

PHP Update Code 1


$id=$_GET['id']; if (!$submit) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT title, authors, description, comment, super, bibtex, url, genre FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()) if (mysql_num_rows($result) > 0) { $row = mysql_fetch_object($result); // print form with values pre-filled ?> <table cellspacing="5" cellpadding="5">

<form action="Update.php" method="POST">


<input type="hidden" name="id" value="<? echo $id; ?>"> <tr> <td valign="top"><b><font size="-1">Title</font></b></td> <td><textarea name="title" cols="40" rows="2"><? echo $row->title; ?></textarea></td> </tr> <tr> <td valign="top"><b><font size="-1">Authors</font></b></td> <td><textarea name="authors" cols="40" rows="2"><? echo $row >authors; ?></textarea></td> </tr> <tr> <td colspan=2>

<input type="Submit" name="submit" value="Update"></td></tr>

PHP Workshop

</form> </table>

PHP Update Code 2


include("conf.php"); // form submitted so start processing it $title = $_POST["title"]; $authors = $_POST["authors"]; $id = $_POST["id"]; // set up error list array $errorList = array(); $count = 0; // validate text input fields if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } if (!$contact) { $contact = $def_contact; } // check for errors, if none found... if (sizeof($errorList) == 0) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!");

$query = "UPDATE papers SET title = '$title', authors = '$authors', description = '$description', comment = '$comment', super = '$super', bibtex = '$bibtex', url = '$url', genre = '$genre' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // print result echo "<font size=-1>Update successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</a></font>";
// close database connection mysql_close($connection); } else{} ?>

PHP Workshop

Create Form

Note: form.html

PHP Workshop

Slide #50
I think thats enough [email protected] Next topic to be announced for early May

PHP Workshop

The PHP Resource

www.php.net

PHP Workshop

Review
Weve started PHP..
Escaping XHTML Comments Basic Syntax Variables Constants

PHP Workshop

Basic Math:

Note: basic.php
PHP Workshop #

Float

PHP Workshop

Float

Note: float.php
PHP Workshop #

You might also like