Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 PHP and MySQL David Lash Module 3 Powering scripts with functions.

Similar presentations


Presentation on theme: "1 PHP and MySQL David Lash Module 3 Powering scripts with functions."— Presentation transcript:

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

2 2 Objectives l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

3 3 Notes on print() You don’t need to use parenthesis with print() l Double quotes means output the value of any variable: »$x = 10; »print ("Mom, please send $x dollars"); l Single quotes means output the actual variable name »$x = 10; »print ('Mom, please send $x dollars'); l 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 ' '; - Can also escape with \ »print " ";

4 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; ?>

5 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

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

7 7 is_set() l Checks if variable exists. l 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 " : "FALSE "; //TRUE $b = "0"; print isset($b) ? "TRUE " : "FALSE "; //TRUE $c = ""; print isset($c) ? "TRUE " : "FALSE "; //TRUE $d = 1; print isset($d) ? "TRUE " : "FALSE "; //TRUE print isset($e) ? "TRUE " : "FALSE "; //FALSE $f= TRUE; print isset($f) ? "TRUE " : "FALSE "; //TRUE $g= FALSE; print isset($g) ? "TRUE " : "FALSE "; //TRUE $h=array();print isset($h) ? "TRUE " : "FALSE "; //TRUE ?>

8 8 empty() l 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

9 9 The rand() Function l Generate a random number. »simulate a dice roll or a coin toss or » to randomly show advertisement banner. l 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";

10 10 A rand() application Favorite Character My favorite cartoon character is <?php $r = rand(1, 6); print " "; ?> that guy Banner ads can be randomly displayed: 1. Store image as toon1.gif, toon2.gif, etc. 2. Assemble file image to use on the fly

11 11 Objectives l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

12 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 <, & to & 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 bold 'quote' < and & fun. specchars(str)=A <b>bold</b> 'quote' < and & fun. specchars(str, ENTQUOTE)=A <b>bold</b> 'quote' < and & fun. addslashes(str)=A bold \'quote\' < and & fun <?php $str = "A bold '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"; ?>

13 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. l Note: Can also combine multiple character formats »For example, $today = date( 'l, F d, Y'); print "Today=$today"; l On April 27, 2005, would output Today=Wednesday, December 27, 2005

14 14 Selected date() character formats

15 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

16 16 Days to Christmas Code 1 days to Christmas 2 3 <? 4 $today = time(); 5 $day = date( 'l, F d, Y'); 6 print "Today=$day "; 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 ?> Get the current time since UNIX epoch. Get the current day Get the current epoch Seconds for 00:00:00 Dec 25, 2004;

17 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 32 nd day Converts date in past Converts extra 13 th month Converts 2 digit year

18 18 Objectives l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

19 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

20 20 l 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 l Consider the following: function OutputTableRow() { print ' One Two '; } l You can run the function by executing OutputTableRow();

21 21 As a full example … 1. 2. Simple Table Function 3. Here Is a Simple Table 4. <?php 5. function OutputTableRow() { 6. print ' One Two '; 7. } 8. OutputTableRow(); 9. OutputTableRow(); 10. OutputTableRow(); 11. ?> 12. OutputTableRow() function definition. Three consecutive calls to the OutputTableRow() function Note: Function definition can be before or after function call

22 22 Passing Arguments to Functions l Input variables to functions are called arguments to the function l For example, the following sends 2 arguments »OutputTableRow("A First Cell", "A Second Cell"); l Within function definition can access values function OutputTableRow($col1, $col2) { print " $col1 $col2 "; }

23 23 Consider the following code … 1. 2. Simple Table Function 3. Revised Simple Table 4. <?php 5. function OutputTableRow( $col1, $col2 ) { 6. print " $col1 $col2 "; 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. OutputTableRow() Function definition. Four calls to OuputTableRow()

24 24 Objectives l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

25 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 numbers 3. // ARGUMENTS: $num1 -- 1st number, $num2 -- 2nd number 4. if ($num1 > $num2) { 5. return($num1); 6. } else { 7. return($num2); 8. } 9. } For example $largest = Simple_calc(15, -22);

26 26 Example 2 – Function checks if its been 24 hours since last post Last Post was: Apr-15-2005 05:04:00 am Time 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; }

27 27 Passing by Reference l When want to change an argument must pass reference. 1 Pass by Reference 2 3 <?php 4 $fname = 'John'; 5 $lname = 'Adams'; 6 print " Pre call "; 7 print "fname=$fname lname=$lname "; 8 output_val( $fname, $lname ); 9 10 print " Post call "; 11 print "fname=$fname lname=$lname "; 12 function output_val( &$first, $last ) { 13 $first = 'George'; 14 $last = 'Washington'; 15 } 16 ?> The ‘&’ indicates pass by reference The default is pass value

28 28 Using Default Argument Values l When want to change an argument must pass reference. 1 Pass by Reference 2 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 " "; 11 print "$text "; 12 } 13 ?> Set default values for $size and $color Call three different ways

29 29 Objectives l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

30 30 Using External Script Files require ("header.php"); require_once(“header.php”); include ("trailer.php"); include_once(“trailer.php”); produce a fatal error if it can’t insert the specified file. Produce a warning if 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.)

31 31 Consider the following example 1. 2. Welcome to Harry’s Hardware Heaven! 3. We sell it all for you! 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 output these lines when the file is included. The value of $time will be set when the file is included. This function will be available for use when the file is included.

32 32 header.php l If the previous script is placed into a file called header.php … 1. Hardware Heaven 2. <?php 3. include("header.php"); 4. $buy = 2.50; 5. $sell = 10.00; 6. print " It is $time."; 7. print "We have hammers on special for \$$sell!"; 8. $markup = Calc_perc($buy, $sell); 9. print " Our markup is only $markup%!!"; 10. ?> 11. Calc_perc() is defined in header.php Include the file header.php

33 33 More Typical Use of External Code Files l Might use one or more files with only functions and other files that contain HTML l For example, Hardware Harry's is located in beautiful downtown Hardwareville. We are open every day from 9 A.M. to midnight, 365 days a year. Call 476-123-4325. Just ask for Harry. l Can include using:

34 34 config.php <?php $HOME = ‘/home/dlash’; $email = ‘dlash01@yahoo.com’; $color = ‘red’; $size = 122; function output_val( $text, $size = 3, $color = 'blue' ) { print " "; print "$text "; } ?> More Typical Use of External Code Files

35 35 Summary l Some interesting PHP functions: »print() & echo(), rand(), is_numeric, is_set, empty(), htmlspecialchars(), addslashes(), and date(). l 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

36 36 Module 3 Hands on Assignment l Create a PHP a set of PHP functions that create HTML form elements: oradio( $name, $label1, $value1, $lebel2, $name2 ) –Would output $label1 $lable2 otextbox( $name, $label, $size ); Would output $label Use 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.

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

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

39 39 Hands-on Lab 2 Ask 2 survey questions Common footer Must answer both questions

40 40 Front end-Survey Schedules Precourse Survey for Building Web Applications with PHP and Mysql 1. What is your experience using any programming language? none some lots 2. What is your experience using any php/mysql ? none some lots <?php include 'footer.php' ?> David Lash 13 13 Mockingbird Lane dlash@yahoo.com footer.php survey.php

41 41 One possible solution Schedules Survey Results <?php if ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) { print "Error you must specify a value for Q1 and Q2 "; include 'footer.php'; exit; } else { $prog = $_POST['programming']; print "Received Q1 = $prog "; print "Received Q2 = {$_POST['php']} "; } include 'footer.php'; ?>

42 42 Which Can Be Modified To... Schedules Survey Results <?php if ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) { print "Error you must specify a value for Q1 and Q2 "; include 'footer.php'; exit; } else { $prog = $_POST['programming']; print "Received Q1 = $prog "; print "Received Q2 = {$_POST['php']} "; $addr = 'dlash@condor.depaul.edu'; $subj = 'Survey Results' ; $msg = "Q1=$prog \n Q2=$php "; mail( "$addr", "Indelible Survey Results", $msg); } include 'footer.php'; ?>


Download ppt "1 PHP and MySQL David Lash Module 3 Powering scripts with functions."

Similar presentations


Ads by Google