PHP Workshop Notes

29
PHP PHP A scripting language design A scripting language design to produce HTML pages to produce HTML pages

description

Put on by USC's Upsilon Pi Epsilon as part of Wonderful World of Web2.0 Workshop Series. http://pollux.usc.edu/~upe/

Transcript of PHP Workshop Notes

Page 1: PHP Workshop Notes

PHPPHP

A scripting language design to A scripting language design to produce HTML pagesproduce HTML pages

Page 2: PHP Workshop Notes

PHP IntroductionPHP Introduction

PHP serves the same purpose as Java PHP serves the same purpose as Java Server Pages (JSP) and Active Server Server Pages (JSP) and Active Server Pages (ASP)Pages (ASP)

All are server-side languages “parsed” by All are server-side languages “parsed” by a web servera web server

Script execution results are sent to a Script execution results are sent to a browser as an HTML pagebrowser as an HTML page

PHP is a type-less languagePHP is a type-less language

Page 3: PHP Workshop Notes

PHP StructurePHP Structure

Tradition: Start with an HTML fileTradition: Start with an HTML file Add special tags to separate PHP code Add special tags to separate PHP code

from HTML statementsfrom HTML statements Web server parses the PHP file, Web server parses the PHP file,

producing HTMLproducing HTML Now can be used to output XML, image, Now can be used to output XML, image,

PDF, just by setting content-typePDF, just by setting content-type

Page 4: PHP Workshop Notes

Example: myfirst.phpExample: myfirst.php<html><html>

<body><body>

<?php<?php

//A comment//A comment

/*Or comment like this*//*Or comment like this*/

print("<b>Hello world</b>");print("<b>Hello world</b>");

$v = 5;$v = 5;

print("<p>Hello again " . $v );print("<p>Hello again " . $v );

print("<p>Hello a third time $v");print("<p>Hello a third time $v");

?>?>

</body></body>

</html></html>

Page 5: PHP Workshop Notes

VariablesVariables

All variables start with a dollar sign, $All variables start with a dollar sign, $$u = 5;$u = 5;

$v = “hello”;$v = “hello”;

$w = 1.22;$w = 1.22;

$x = $u + $v; $x = $u + $v; //arithmetic with + - ONLY//arithmetic with + - ONLY

$y = $v . $v; $y = $v . $v; //concatenation with period operator//concatenation with period operator

$x = $u . $u; //produces 55, not 10$x = $u . $u; //produces 55, not 10

Page 6: PHP Workshop Notes

PrintingPrinting

$u = 5;$u = 5;

print( “5 hello” ); //print anything in quotesprint( “5 hello” ); //print anything in quotes

print( $u . “hello” ); //prints 5helloprint( $u . “hello” ); //prints 5hello

print( “$u Hello” ); //prints 5 Helloprint( “$u Hello” ); //prints 5 Hello

Page 7: PHP Workshop Notes

String-Related FunctionsString-Related Functions

$v = “hello”;$v = “hello”;

strlen( $v); //returns 5strlen( $v); //returns 5

trim( $v); //trims any spaces on either side of a stringtrim( $v); //trims any spaces on either side of a string

$x = strtolower ($v); //$x has hello$x = strtolower ($v); //$x has hello

$x = strtoupper($v); //$x has HELLO$x = strtoupper($v); //$x has HELLO

$str = “abcdef”;$str = “abcdef”;

$a = substr( $str, 3, 3 );$a = substr( $str, 3, 3 );

# of characters to copy

Start position, zero indexed

Source string“def”

Can be negative to start fromright side

Page 8: PHP Workshop Notes

Getting HTML Form DataGetting HTML Form Data

There are 3 ways to get form data in PHPThere are 3 ways to get form data in PHP1.1. Global variables – this is a bad way because of Global variables – this is a bad way because of

security problems. PHP creates a variable with security problems. PHP creates a variable with a name matching the form field name in the a name matching the form field name in the source HTML.source HTML.

2.2. POST variable associative arrayPOST variable associative arrayPrior to version 4.1, Prior to version 4.1, $HTTP_POST_VARS$HTTP_POST_VARS4.1 and after, 4.1 and after, $_POST$_POST

3.3. GET variable associative arrayGET variable associative arraySame as POST, but use GETSame as POST, but use GET

Page 9: PHP Workshop Notes

ExamplesExamples

1.1. Global variablesGlobal variables (HTML has field with name ‘abc’)(HTML has field with name ‘abc’)

print ($abc);print ($abc);

2.2. POST POST

print($_POST(‘abc’)); //4.1 and afterprint($_POST(‘abc’)); //4.1 and after

3.3. GETGET

print($_GET(‘abc’)); //4.1 and afterprint($_GET(‘abc’)); //4.1 and after

Page 10: PHP Workshop Notes

Comparing StringsComparing Strings

strcmp( $a, $b ); //works like C functionstrcmp( $a, $b ); //works like C function

Returns:Returns:

– –1 if first string less than second string1 if first string less than second string

0 if the same0 if the same

1 if first string greater than second string1 if first string greater than second string It is case sensitiveIt is case sensitive

Page 11: PHP Workshop Notes

PHP Syntax SimilaritiesPHP Syntax Similarities

Has a switch statementHas a switch statement forfor loop is the same, but uses PHP loop is the same, but uses PHP

variable syntaxvariable syntaxfor ($i=0; $i < 10; $i++ ){ …. }for ($i=0; $i < 10; $i++ ){ …. }

whilewhile and and ifif are also what you’d expect are also what you’d expect Standard logical operators: ==, &&, <, > Standard logical operators: ==, &&, <, >

……

Page 12: PHP Workshop Notes

Other Useful FunctionsOther Useful Functions

round ($a); //rounds a numberround ($a); //rounds a number is_numeric($v); //returns true/falseis_numeric($v); //returns true/false rand($start, $end); //Produces int randrand($start, $end); //Produces int rand

Page 13: PHP Workshop Notes

Current Date/TimeCurrent Date/Time

Use date function to get the current date.Use date function to get the current date. Takes a format string to provide the date Takes a format string to provide the date

in a format you want. See in a format you want. See http://php.net/datehttp://php.net/date..

Use time function to get the current time.Use time function to get the current time. Returns the current time measured in the Returns the current time measured in the

number of seconds since the Unix Epoch number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).(January 1 1970 00:00:00 GMT).

Page 14: PHP Workshop Notes

Creating FunctionsCreating Functions

function myfunc( $a, $b, $c ) {function myfunc( $a, $b, $c ) {

//this is my code//this is my code

return $x;return $x;

}}

Page 15: PHP Workshop Notes

External PHP FilesExternal PHP Files

Can use Can use requirerequire or or includeinclude Require will produce a fatal error if the file Require will produce a fatal error if the file

cannot be foundcannot be found Include will just ignore a missing script fileInclude will just ignore a missing script file

require(‘my.php’);require(‘my.php’);

include(‘my.php’);include(‘my.php’);

The files can contain PHP and/or HTMLThe files can contain PHP and/or HTML

Page 16: PHP Workshop Notes

ArraysArrays

Creating an arrayCreating an array$a = array(1,2,3,4,5);$a = array(1,2,3,4,5);

Accessing array elementsAccessing array elements$v = $a[2];$v = $a[2];

$a[2] = 5;$a[2] = 5;

$a[] = 1; $a[] = 2; $a[] = 3; //appends to array$a[] = 1; $a[] = 2; $a[] = 3; //appends to array

Page 17: PHP Workshop Notes

Iterating Over ArraysIterating Over Arrays

for ($i=0; $i<count($a); $i++ ) {for ($i=0; $i<count($a); $i++ ) {

print ($a[i]);print ($a[i]);

}}

foreach( $a as $item ) {foreach( $a as $item ) {

print( “<p>$item”);print( “<p>$item”);

}}

Array variable

Local variable. Set tonext array element eachiteration.

Page 18: PHP Workshop Notes

Other Array FunctionsOther Array Functions

$m = max($a); //returns max value in array$m = max($a); //returns max value in array

$m = min($a); //returns min value in array$m = min($a); //returns min value in array

$s = array_sum($a); //returns sum or array $s = array_sum($a); //returns sum or array valuesvalues

sort($a); //sorts the items in the array. Changessort($a); //sorts the items in the array. Changes

//the array itself//the array itself

Optional second argument is “sort flags” to Optional second argument is “sort flags” to control the sort.control the sort.

Page 19: PHP Workshop Notes

Associative ArraysAssociative Arrays

Arrays containing key/value pairsArrays containing key/value pairs$s = array( ‘a’=>’alpha’, ‘b’=>’beta’, … );$s = array( ‘a’=>’alpha’, ‘b’=>’beta’, … );

print ( $s[‘b’] );print ( $s[‘b’] );

The parameter to the left of => is the key.The parameter to the left of => is the key. The right parameter is the value.The right parameter is the value.

Page 20: PHP Workshop Notes

SQL – Structured Query SQL – Structured Query LanguageLanguage

A language for accessing relational A language for accessing relational databasesdatabases

Relational databases have tablesRelational databases have tables Tables have fields and contain rows of Tables have fields and contain rows of

datadata

Page 21: PHP Workshop Notes

SQL Syntax – SELECTSQL Syntax – SELECT

Used for retrieving data from a databaseUsed for retrieving data from a databaseSELECT [fields] FROM [tables] WHERE [expr]SELECT [fields] FROM [tables] WHERE [expr]

ExamplesExamples

select * from usersselect * from users

select abc, def from mytable where ghi=5select abc, def from mytable where ghi=5

Page 22: PHP Workshop Notes

SQL Syntax – INSERTSQL Syntax – INSERT

Used to insert new data in a tableUsed to insert new data in a tableINSERT INTO [table] [field names] VALUES INSERT INTO [table] [field names] VALUES

[values][values]

ExamplesExamples

insert into users (abc,def,ghi) values (‘111’,22,’cc)insert into users (abc,def,ghi) values (‘111’,22,’cc)

insert into xyz values (1,2,3,4,5)insert into xyz values (1,2,3,4,5)

Page 23: PHP Workshop Notes

SQL Syntax – UPDATESQL Syntax – UPDATE

Updating one or more values in existing Updating one or more values in existing rows in a tablerows in a tableUPDATE [table] SET [name=value pairs] UPDATE [table] SET [name=value pairs]

WHERE [expression]WHERE [expression]

ExamplesExamples

update mytable set a=‘aaa’, b=55 where c=11update mytable set a=‘aaa’, b=55 where c=11

Page 24: PHP Workshop Notes

PHP and Mysql DatabasePHP and Mysql Database

5 steps5 steps1.1. Connect to the Mysql DBMSConnect to the Mysql DBMS

2.2. Pick a databasePick a database

3.3. Execute an SQL statementExecute an SQL statement

4.4. If the SQL was a ‘select’, retrieve the dataIf the SQL was a ‘select’, retrieve the data

5.5. Close the connectionClose the connection

Page 25: PHP Workshop Notes

Connecting to Mysql Connecting to Mysql DBMSDBMS

$con = mysql_connect( /* 3 arguments */ );$con = mysql_connect( /* 3 arguments */ );

1.1. Your Mysql DBMS server process network Your Mysql DBMS server process network locationlocation

2.2. Your Mysql user IDYour Mysql user ID

3.3. Your Mysql user passwordYour Mysql user password

For tonight only,For tonight only,mysql_connect(‘www.freesql.org’,’upeworkshop’,’upeworkshop’);mysql_connect(‘www.freesql.org’,’upeworkshop’,’upeworkshop’);

Page 26: PHP Workshop Notes

Selecting a DatabaseSelecting a Database

mysql_select_db( ‘upeworkshop’ );mysql_select_db( ‘upeworkshop’ );

Page 27: PHP Workshop Notes

Executing an SQL Executing an SQL StatementStatement

mysql_query( /*SQL statement*/ );mysql_query( /*SQL statement*/ );

Proper form for any SQL not a SelectProper form for any SQL not a Select

if ( !mysql_query ( “update a ….” ); ) {if ( !mysql_query ( “update a ….” ); ) {

echo mysql_error(); //for easy debugging, echo mysql_error(); //for easy debugging, not for final user-oriented websitenot for final user-oriented website

} //returns true/false if it worked, or not} //returns true/false if it worked, or not

Page 28: PHP Workshop Notes

For Select SQL For Select SQL StatementsStatements

$r = mysql_query( ‘select * from abc’ );$r = mysql_query( ‘select * from abc’ );

while ( $row = mysql_fetch_row( $r ) ) { … }while ( $row = mysql_fetch_row( $r ) ) { … }$row contains a row of data$row contains a row of datareturns false when no more rows availablereturns false when no more rows available

Iterating through the fields in the rowIterating through the fields in the rowforeach ( $row as $item ) { … }foreach ( $row as $item ) { … }

OR access the fields using index position (zero indexed)OR access the fields using index position (zero indexed)

OR put results in an associative array – less error proneOR put results in an associative array – less error pronewhile ($row = mysql_fetch_assoc($r)){while ($row = mysql_fetch_assoc($r)){

echo $row[‘firstname’];echo $row[‘firstname’];}}

Page 29: PHP Workshop Notes

Closing a ConnectionClosing a Connection

mysql_close( $con );mysql_close( $con );