420 likes | 674 Views
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
E N D
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 • Passing Arguments to Functions • Returning values • Passing by Reference • Using Default Argument Values • Using External Script Files • Variable Scope Common Problem Area! People seem to forget this Competency Alert: You need to know this!
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\">";
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; ?>
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
is_numeric() <?php echo '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>"; ?>
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 ?>
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
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";
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
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
A couple HTML support Functions Find html special characters, and convert (e.g., < to <, & to & $str = htmlspecialchars($str1); $str = htmlspecialchars($str1, ENT_QUOTES); $str = addslashes($str1); Translates quotes too. Find characters that need back slashes and add them. (‘,”, \ and null) (e.g., ‘ to \’, and “ to \”. <?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"; ?> Original string=A <b>bold</b> '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 <b>bold</b> \'quote\' < and & fun 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)
The date()Function One or more characters that define output. • Use date() for date and time info • The format string defines output format: • $day = date('d'); • print "day=$day"; $str = date(‘format string'); Request date() to return the numerical day of the month. Note: If executed on December 27, 2005, would output “day=27”. • 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
Working with UNIX timestamps Returns number of seconds since Unix Epoch (January 1 1970 00:00:00 GMT) $stamp = time (); $var1= date ('l, F d, Y', $stamp ); Convert optional UNIX time stamp to format $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
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 epoch Seconds for 00:00:00 Dec 25, 2004;
A little more on mktime() and date() Converts 32nd day <?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"; ?> Converts extra 13th month Converts date in past Converts 2 digit year Jan-01-2011 Jan-01-2003 Jan-01-1998 Dec-01-2006
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
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
Writing Your Own Functions • Use the following general format function function_name() { set of statements } Include parentheses at the end of the function name The function runs these statements when called Enclose in curly brackets. • Consider the following: function OutputTableRow() { print '<tr><td>One</td><td>Two</td></tr>'; } • You can run the function by executing OutputTableRow();
As a full example … Note: Function definition can be before or after function call 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. <?php 5. 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
Passing Arguments to Functions • Input variables to functions are calledarguments to the function • For example, the following sends 2 arguments • OutputTableRow("A First Cell", "A Second Cell"); • Within function definition can access values function OutputTableRow($col1, $col2) { print "<tr><td>$col1</td><td>$col2</td></tr>"; }
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. <?php 5. 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()
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
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);
Example 2 – Function checks if its been 24 hours since last 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; } } Last Post was: Apr-15-2005 05:04:00 am Time is: Apr-19-2005 07:04:09 am It is OK to Post
Passing by Reference The ‘&’ indicates pass 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 default is pass value
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> Call three different ways Set default values for $size and $color
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
Using External Script Files Search for the file named within the double quotation marks and insert its PHP, HTML, or JavaScript code into the current file. 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. 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.)
Consider the following example The script will output these lines when the file is included. 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 value of $time will be set when the file is included. This function will be available for use when the file is included.
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> Include the file header.php Calc_perc() is defined in header.php
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"); ?>
config.php More Typical Use of External Code Files <?php $HOME = ‘/home/dlash’; $email = ‘dlash01@yahoo.com’; $color = ‘red’; $size = 122; function output_val( $text, $size = 3, $color = 'blue' ) { print "<font size=$size color=$color>"; print "$text </font>"; } ?>
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
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> $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.
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>
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 ?>
Hands-on Lab 2 Ask 2 survey questions Common footer Must answer both questions
Front end-Survey survey.php <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> <?php include 'footer.php' ?> </body> </html> footer.php <hr> <center> David Lash <br> 13 13 Mockingbird Lane <br> dlash@yahoo.com
One possible solution <html> <head> <title>Schedules</title> </head> <body bgcolor="#ffffff"> <h1> Survey Results </h1> <?php if ( !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>
Which Can Be Modified To . . . <html> <head> <title>Schedules</title> </head> <body bgcolor="#ffffff"> <h1> Survey Results </h1> <?php if ( !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 = 'dlash@condor.depaul.edu'; $subj = 'Survey Results' ; $msg = "Q1=$prog \n Q2=$php "; mail( "$addr", "Indelible Survey Results", $msg); } include 'footer.php'; ?> </body> </html>