Top Banner
1 PHP and MySQL David Lash Module 3 Powering scripts with functions
42

PHP and MySQL

Jan 30, 2016

Download

Documents

washi

PHP and MySQL. David Lash Module 3 Powering scripts with functions. Objectives. Some interesting PHP functions: print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). Creating your own functions General format Passing arguments - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PHP and MySQL

1

PHP and MySQL

David Lash

Module 3

Powering scripts with functions

Page 2: PHP and MySQL

2

Objectives Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Competency Alert:You need to

know this!

Common Problem Area!

People seem to forget this

Page 3: PHP and MySQL

3

Notes on print() You don’t need to use parenthesis with print() Double quotes means output the value of any variable:

» $x = 10;» print ("Mom, please send $x dollars");

Single quotes means output the actual variable name» $x = 10;» print ('Mom, please send $x dollars');

To output a single variable’s value or expression, omit the quotation marks.» $x=5;» print $x*3;

- Note: Single quotes with HTML tags: print '<font color="blue">';

- Can also escape with \»print "<font color=\"blue\">";

Page 4: PHP and MySQL

4

print() VS echo()

Use echo() when want to output a variable's value directly<?php

echo "hello";

echo "x=", rand(1, 6);

echo “2 + 2 =“, 2+2, “but 4 + 4=“, 4+4;

?>

Page 5: PHP and MySQL

5

Testing variable status

PHP supports a series of variable testing functions that return true or false.» is_numeric() tests if a variable is a valid

number or a numeric string.» is_set() – tests if a variable exists. » empty() – checks if a variable is empty

Page 6: PHP and MySQL

6

is_numeric()

<?phpecho '2 ', (is_numeric('2') ? "true" : "false") . "<br>";echo '2.4 ', (is_numeric('2.4') ? "true" : "false") . "<br>";echo '2.2b ', (is_numeric('2.2b') ? "true" : "false") . "<br>";echo '.5 ', (is_numeric('.5') ? "true" : "false") . "<br>";echo '1.2.5 ', (is_numeric('1.2.5') ? "true" : "false") . "<br>";echo 'A.5 ', (is_numeric('A.5') ? "true" : "false") . "<br>";?>

Page 7: PHP and MySQL

7

is_set() Checks if variable exists. Most useful for checking array elements: if (!is_set($_POST[‘name’] && !is_set($_POST[‘score’] )

{

print (“Error you must specify name and score”);

}

Note: from php.net contrib notes: <?php$a = 0; print isset($a) ? "TRUE<br>" : "FALSE<br>"; //TRUE$b = "0"; print isset($b) ? "TRUE<br>" : "FALSE<br>"; //TRUE$c = ""; print isset($c) ? "TRUE<br>" : "FALSE<br>"; //TRUE$d = 1; print isset($d) ? "TRUE<br>" : "FALSE<br>"; //TRUE print isset($e) ? "TRUE<br>" : "FALSE<br>"; //FALSE$f= TRUE; print isset($f) ? "TRUE <br>" : "FALSE<br>"; //TRUE$g= FALSE; print isset($g) ? "TRUE<br>" : "FALSE<br>"; //TRUE$h=array();print isset($h) ? "TRUE<br>" : "FALSE<br>"; //TRUE?>

Page 8: PHP and MySQL

8

empty() Check if a variable is empty. Am empty string is:

» "" (an empty string)

» 0 (integert) or "0" (string)

» NULL, or FALSE

» array() (an empt)

» var $var; (a variable declared, but without a value in a class

if (empty($_POST[‘name’] && empty($_POST[‘score’] ) {

print (“Error you must specify name and score”);

}

Note: from php.net contrib notes:

$a = 0  ; print empty($a) ? "TRUE" : "FALSE"; //TRUE $b = "0" ; print empty($b) ? "TRUE" : "FALSE"; //TRUE $c = ""  ; print empty($c) ? "TRUE" : "FALSE"; //TRUE $d = 1  ; print empty($d) ? "TRUE" : "FALSE"; //FALSE            print empty($e) ? "TRUE" : "FALSE"; //TRUE $f= TRUE ; print empty($f) ? "TRUE" : "FALSE"; //FALSE $g= FALSE; print empty($g) ? "TRUE" : "FALSE"; //TRUE

$h=array();print empty($h) ? "TRUE" : "FALSE"; //TRUE

Page 9: PHP and MySQL

9

The rand() Function Generate a random number.

» simulate a dice roll or a coin toss or» to randomly show advertisement banner.

E.g., return a number 1 - 15 – $num = rand(1, 15);

Since PHP 4.2.0 do not need to seed with srand(). A random seed value if omitted.

srand ((double) microtime() * 10000000);$dice = rand(1, 6);print "Your random dice toss is $dice";

Page 10: PHP and MySQL

10

A rand() application<html><head><title> Favorite Character </title> </head><body>My favorite cartoon character is <?php $r = rand(1, 6); print "<img src=toon{$r}.gif>";?>that guy</body></html>

Banner ads can be randomly displayed:1. Store image as toon1.gif, toon2.gif, etc. 2. Assemble file image to use on the fly

Page 11: PHP and MySQL

11

Objectives Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Page 12: PHP and MySQL

12

A couple HTML support Functions

$str = htmlspecialchars($str1); $str = htmlspecialchars($str1, ENT_QUOTES);

$str = addslashes($str1);

Find html special characters, and convert (e.g., < to &lt;, & to &amp;

Find characters that need back slashes and add them. (‘,”, \ and null) (e.g., ‘ to \’, and “ to \”.

Note, sites can also run with magic_quotes_gpc set to ‘on’ within php.ini, this essentially, addslashes() to each string input from all get, post and cookie (gpc)

Translates quotes too.

Original string=A <b>bold</b> 'quote' < and & fun . specchars(str)=A &lt;b&gt;bold&lt;/b&gt; 'quote' &lt; and &amp; fun .specchars(str, ENTQUOTE)=A &lt;b&gt;bold&lt;/b&gt; &#039;quote&#039; &lt; and &amp; fun .addslashes(str)=A <b>bold</b> \'quote\' < and & fun

<?php$str = "A <b>bold</b> 'quote' < and & fun .";print "Original string=$str \n";echo "specchars(str)=", htmlspecialchars($str), "\n";echo "specchars(str, ENTQUOTE)=", htmlspecialchars($str, ENT_QUOTES), "\n";echo "addslashes(str)=", addslashes($str), "\n";?>

Page 13: PHP and MySQL

13

The date()Function Use date() for date and time info

The format string defines output format:– $day = date('d');– print "day=$day";

Request date() to return the

numerical day of the month.

Note: If executed on December 27, 2005, would output “day=27”.

$str = date(‘format string');

One or more characters that define output.

Note: Can also combine multiple character formats

» For example,

$today = date( 'l, F d, Y');

print "Today=$today"; On April 27, 2005, would output

Today=Wednesday, December 27, 2005

Page 14: PHP and MySQL

14

Selected date() character formats

Format String

Meaning Format String

Meaning

D Three-letter indication of day of week (for example, Mon, Tue)

M Current month of year in short three-letter format (for example, Jan, Feb)

d Numerical day of month returned as two digits (for example, 01, 02)

s Seconds in current minute from 00 to 59 (for example, 07, 50)

F Current month in long format (for example, January, February)

t Number of days in current month (28, 29, 30, or 31)

h Current hour in day from 01 to 12 (for example, 02, 11)

U Number of seconds since the epoch (usually since January 1, 1970)

H Current hour in day from 00 to 23 (for example, 01, 18).

w Current day of week from 0 to 6 (where 0 is Sunday, 1 is Monday, and so on)

i Current minute from 00 to 59 (for example, 05, 46)

y Current year returned in two digits (for example, 01, 02)

l Current day of week in long format (for example, Sunday, Monday)

Y Current year returned in four digits (for example, 2001, 2002)

L Returns 1 if it is a leap year or 0 otherwise

z Day number of the year from 0 to 365 (where January 1 is day 0, January 2 is day 1, and so on)

m Current month of year from 01 to 12

Page 15: PHP and MySQL

15

Working with UNIX timestamps

$var1= date ('l, F d, Y', $stamp );

Convert optional UNIX time stamp to format

$stamp = time (); Returns number of seconds since Unix Epoch (January 1 1970 00:00:00 GMT)

$stamp2 = mktime ( $hr, $min, $src, $mon, $day, $year );

Convert time and date into UNIX timestamp<?

$today=date('Y-m-d');

$nextWeek = time() + (7 * 24 * 60 * 60);

$next_week = date('Y-m-d', $nextWeek);

print "today is $today \n" ;

print "please comeback nextweek = $next_week \n";

?>

today is 2005-04-18

please comeback nextweek = 2005-04-25

Page 16: PHP and MySQL

16

Days to Christmas Code

1 <html> <head> <title> days to Christmas </title> </head> 2 <body> 3 <? 4 $today = time(); 5 $day = date( 'l, F d, Y'); 6 print "Today=$day <br>"; 7 8 $christmas = mktime(00,00,00,12,25,2004); 9 10 $secs_to_christmas = $christmas - $today; 11 12 $days_to_christmas = floor( $secs_to_christmas / 86400); 14 15 16 print "There are $days_to_christmas shopping days to Christmas!"; 17 ?></body> </html>

Get the current time since UNIX epoch.

Get the current day

Get the current epochSeconds for 00:00:00 Dec 25, 2004;

Page 17: PHP and MySQL

17

A little more on mktime() and date()

<?php

echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 2010)), "\n";

echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 2002)), "\n";

echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998)), "\n";

echo date("M-d-Y", mktime(0, 0, 0, 24, 1, 05)), "\n";

?>

Jan-01-2011

Jan-01-2003

Jan-01-1998

Dec-01-2006

Converts 32nd day

Converts date in past

Converts extra 13th month

Converts 2 digit year

Page 18: PHP and MySQL

18

Objectives Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Page 19: PHP and MySQL

19

Defining Your Own Functions

Programmer-defined functions provide a way to group a set of statements, set them aside, and turn them into mini-scripts within a larger script.» Scripts that are easier to understand and change.» Reusable script sections.» Smaller program size

Page 20: PHP and MySQL

20

Use the following general format function function_name() {

set of statements

}

Writing Your Own Functions

Enclose in curly brackets.

Include parentheses at the end of the function name

The function runs these statements when called

Consider the following: function OutputTableRow() {

print '<tr><td>One</td><td>Two</td></tr>';

}

You can run the function by executingOutputTableRow();

Page 21: PHP and MySQL

21

As a full example …1. <html>2. <head><title> Simple Table Function </title> </head> <body>3. <font color="blue" size="4"> Here Is a Simple Table <table border=1>4. <?php5. function OutputTableRow() {6. print '<tr><td>One</td><td>Two</td></tr>';7. }8. OutputTableRow();9. OutputTableRow();10. OutputTableRow();11. ?>12. </table></body></html>

OutputTableRow() function definition.

Three consecutive calls to the OutputTableRow() function

Note: Function definition can be before or after function call

Page 22: PHP and MySQL

22

Passing Arguments to Functions

Input variables to functions are called arguments to the function

For example, the following sends 2 arguments» OutputTableRow("A First Cell", "A Second Cell");

Within function definition can access valuesfunction OutputTableRow($col1, $col2) {

print "<tr><td>$col1</td><td>$col2</td></tr>";

}

Page 23: PHP and MySQL

23

Consider the following code …

1. <html>2. <head><title> Simple Table Function </title> </head> <body>3. <font color="blue" size=4> Revised Simple Table <table border=1>4. <?php5. function OutputTableRow( $col1, $col2 ) {6. print "<tr><td>$col1</td><td>$col2</td></tr>";7. }8. for ( $i=1; $i<=4; $i++ ) {9. $message1="Row $i Col 1";10. $message2="Row $i Col 2";11. OutputTableRow( $message1, $message2 );12. }13. ?>14. </table></body></html>

OutputTableRow()

Function definition.

Four calls to OuputTableRow()

Page 24: PHP and MySQL

24

Objectives Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Page 25: PHP and MySQL

25

Returning Values Use the following to immediately return a

value to the calling script: return $result;

Can return, a string, a value, array, or TRUE, FALSE

1. function Simple_calc( $num1, $num2 ) {2. // PURPOSE: returns largest of 2 numbers3. // ARGUMENTS: $num1 -- 1st number, $num2 -- 2nd number4. if ($num1 > $num2) {5. return($num1);6. } else {7. return($num2);8. }9. } For example

$largest = Simple_calc(15, -22);

Page 26: PHP and MySQL

26

Example 2 – Function checks if its been 24 hours since

last post

Last Post was: Apr-15-2005 05:04:00 amTime is: Apr-19-2005 07:04:09 am It is OK to Post

<?php

$lastpost = mktime(5,15,0,04,15,2005);echo 'Last Post was: ', date("M-d-Y H:m:s a", $lastpost), "\n";

$now = date("M-d-Y H:m:s a", time());print "Time is: $now \n"; if (canPost($lastpost, 24)) { print "It is OK to Post\n";} else { echo 'next post time is ', date("M-d-Y H:m:s a", $lastpost+(3600*24));}

function canPost($lastpost, $diff) {

$diff = $diff*3600; # convert hourse into seconds

$nextpost = $lastpost+$diff; $timenow = time();

if ($timenow > $nextpost) { return true; } else { return false; }}

Page 27: PHP and MySQL

27

Passing by Reference When want to change an argument must pass reference. 1 <html> <head><title> Pass by Reference </title> </head> 2 <body> 3 <?php 4 $fname = 'John'; 5 $lname = 'Adams'; 6 print "<font color=blue> Pre call "; 7 print "fname=$fname lname=$lname </font><br>"; 8 output_val( $fname, $lname ); 9 10 print "<br><font color=red> Post call "; 11 print "fname=$fname lname=$lname </font>"; 12 function output_val( &$first, $last ) { 13 $first = 'George'; 14 $last = 'Washington'; 15 } 16 ?> </body></html>

The ‘&’ indicates pass by reference

The default is pass value

Page 28: PHP and MySQL

28

Using Default Argument Values

When want to change an argument must pass reference.

1 <html> <head><title> Pass by Reference</title> </head> 2 <body> 3 <?php 4 5 output_val( 'Yankee Doodle' ); 6 output_val( 'went to town', 4, 'red' ); 7 output_val( 'riding on a pony', 6 ); 8 9 function output_val( $text, $size = 3, $color = 'blue' ) { 10 print "<font size=$size color=$color>"; 11 print "$text </font>"; 12 } 13 ?> </body></html>

Set default values for $size and $color

Call three different ways

Page 29: PHP and MySQL

29

Objectives Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Page 30: PHP and MySQL

30

Using External Script Files

require ("header.php");

require_once(“header.php”);

include ("trailer.php");

include_once(“trailer.php”);

produce a fatalerror if it can’t insert the specified file.

Produce a warningif it can’t insert the specified file.

Search for the file named within the double quotation marks and insert its PHP, HTML, or JavaScript code into the current file.

Use require_one() and include_once() when want to ensure functions are included only once (E.g., when using libraries that may also include code.)

Page 31: PHP and MySQL

31

Consider the following example

1. <font size=4 color="blue">

2. Welcome to Harry’s Hardware Heaven!

3. </font><br> We sell it all for you!<br>

4. <?php

5. $time = date('H:i');

6. function Calc_perc($buy, $sell) {

7. $per = (($sell - $buy ) / $buy) * 100;

8. return($per);

9. }

10. ?>

The script will outputthese lines when thefile is included.

The value of $time will be set when the file is included.

This function willbe available foruse when the fileis included.

Page 32: PHP and MySQL

32

header.php If the previous script is placed into a file called header.php … 1. <html><head><title> Hardware Heaven </title></head> <body>2. <?php

3. include("header.php");

4. $buy = 2.50;

5. $sell = 10.00;

6. print "<br>It is $time.";

7. print "We have hammers on special for \$$sell!";

8. $markup = Calc_perc($buy, $sell);

9. print "<br>Our markup is only $markup%!!";

10. ?>

11. </body></html>

Calc_perc() is defined in header.php

Include the file header.php

Page 33: PHP and MySQL

33

More Typical Use of External Code Files

Might use one or more files with only functions and other files that contain HTML

For example, <hr>

Hardware Harry's is located in beautiful downtown Hardwareville.

<br>We are open every day from 9 A.M. to midnight, 365 days a year.

<br>Call 476-123-4325. Just ask for Harry.

</body></html>

Can include using: <?php include("footer.php"); ?>

Page 34: PHP and MySQL

34

config.php

<?php

$HOME = ‘/home/dlash’;

$email = ‘[email protected]’;

$color = ‘red’;

$size = 122;

function output_val( $text, $size = 3, $color = 'blue' ) {

print "<font size=$size color=$color>";

print "$text </font>";

}

?>

More Typical Use of External Code Files

Page 35: PHP and MySQL

35

Summary Some interesting PHP functions:

» print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date().

Creating your own functions» General format» Passing arguments» Passing Arguments to Functions» Returning values» Passing by Reference» Using Default Argument Values» Using External Script Files » Variable Scope

Page 36: PHP and MySQL

36

Module 3 Hands on Assignment

Create a PHP a set of PHP functions that create HTML form elements: oradio( $name, $label1, $value1, $lebel2, $name2 )

– Would output<input type=radio name=$name value=$value1> $label1<input type=radio name=$name value=$value2> $lable2

otextbox( $name, $label, $size );Would output<input type=text name=$name size=$size> $labelUse default value of 40 for size but output an error if label has no value.

oform( $action );• Would putput:

• Output an error is action is null.

• Place these functions in an external file called htmlhelpers.php and include it into your script.

Page 37: PHP and MySQL

37

One possible solution 1 <html> <head> <title> form test </title> </head> 2 <body> 3 <?php 4 include('lab3.php'); 5 oform( 'lab3_handle.php'); 6 otextbox( "name", 'What is your name?', 20 ); 7 print "<br>Did you enjoy the course?"; 8 oradio( 'enjoy', 'yes', 1, 'no', 0); 9 ?> 10 <br><input type=submit> 11 </form> </body> </html>

Page 38: PHP and MySQL

38

The file lab3.php 1 <?php 2 function oradio( $name, $label1, $value1, $label2, $name2 ) { 3 print "<input type=radio name=$name value=$value1> $label1"; 4 print "<input type=radio name=$name value=$value2> $label2"; 5 } 6 function otextbox( $name, $label, $size = 40 ) { 7 print "$label <input type=text name=$name size=$size> "; 8 } 9 function oform ( $action ) { 10 if ( empty($action) ) { 11 print "Error action=$action cannot be empty <br>"; 12 exit; 13 } 14 print "<form action=$action method=post>"; 15 } 16 ?>

Page 39: PHP and MySQL

39

Hands-on Lab 2

Ask 2 survey questions

Common footer

Must answer both questions

Page 40: PHP and MySQL

40

Front end-Survey<html><head><title>Schedules</title></head> <body bgcolor="#ffffff"><h1> Precourse Survey for Building Web Applications with PHP and Mysql </h1><table cellpadding="6" cellspacing="0" border="0" ><form action='results.php' method=post><tr> <td> 1. What is your experience using any programming language? </td><td><input type=radio name=programming value=0> none<input type=radio name=programming value=1> some<input type=radio name=programming value=2> lots</td> </tr><tr> <td> 2. What is your experience using any php/mysql ? </td><td><input type=radio name=php value=0> none<input type=radio name=php value=1> some<input type=radio name=php value=2> lots</td> </tr><tr> <td> <input type=submit> </td></form></table><?phpinclude 'footer.php' ?></body></html> <hr>

<center>David Lash<br>13 13 Mockingbird Lane<br>[email protected]

footer.php

survey.php

Page 41: PHP and MySQL

41

One possible solution

<html><head><title>Schedules</title></head> <body bgcolor="#ffffff"><h1> Survey Results </h1><?phpif ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) { print "Error you must specify a value for Q1 and Q2 <br>"; include 'footer.php'; exit;} else { $prog = $_POST['programming']; print "Received Q1 = $prog <br>"; print "Received Q2 = {$_POST['php']} <br>";}include 'footer.php';?> </body> </html>

Page 42: PHP and MySQL

42

Which Can Be Modified To . . .

<html><head><title>Schedules</title></head> <body bgcolor="#ffffff"><h1> Survey Results </h1><?phpif ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) { print "Error you must specify a value for Q1 and Q2 <br>"; include 'footer.php'; exit;} else { $prog = $_POST['programming']; print "Received Q1 = $prog <br>"; print "Received Q2 = {$_POST['php']} <br>"; $addr = '[email protected]'; $subj = 'Survey Results' ; $msg = "Q1=$prog \n Q2=$php "; mail( "$addr", "Indelible Survey Results", $msg);

}include 'footer.php';?> </body> </html>