Powering Scripts with Functions David Lash Chapter 4 Using and writing your own functions.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Computer Programming w/ Eng. Applications
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Java Script Session1 INTRODUCTION.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Functions & Arrays. Functions Functions offer the ability for programmers to group together program code that performs specific task or function into.
1 PHP and MySQL David Lash Module 3 Powering scripts with functions.
Computer Science 1620 Loops.
Computer Science 103 Chapter 3 Introduction to JavaScript.
1 *Copyright © 2002 Pearson Education, Inc.. 2 Web Wizard’s Guide to CGI/Perl David Lash Chapter 3 Perl Basics.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
David Lash DePaul University SNL 262 Web Page Design Web Wizard’s Chapter 3 Instructor: David A. Lash Controlling the instruction flow.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming
1 PHP and MySQL David Lash Module 2 Working with forms, PHP conditionals and loops.
David Lash DePaul University SNL 262 Web Page Design Web Wizard’s Chapter 2 Instructor: David A. Lash Enhancing HTML With PHP.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
PHP == ‘ Hypertext Preprocessor ’ Open-source, server-side scripting language Used to generate dynamic web-pages PHP scripts reside between reserved PHP.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
PHP flow of control & functions
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Input, Output, and Processing
Flow of Control Part 1: Selection
ITBP 119 Algorithms and Problem Solving Section 2.1 Installing software Section 2.2 First Programs Section 2.3 Variables.
Slide 7-1 CHAPTER 7 Managing Multiple-Form Applications: Writing scripts with multiple screens.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
CSC 2720 Building Web Applications Server-side Scripting with PHP.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Introduction to Programming with RAPTOR
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Tutorial 11 1 JavaScript Operators and Expressions.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Copyright © 2003 Pearson Education, Inc. Slide 4-1 The Web Wizard’s Guide to PHP by David Lash.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizard’s Guide to PHP by David Lash.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Chapter 9: Value-Returning Functions
Intro to PHP & Variables
User-Defined Functions
Conditions and Ifs BIS1523 – Lecture 8.
The Web Wizard’s Guide to PHP
T. Jumana Abu Shmais – AOU - Riyadh
The Web Wizard’s Guide to PHP by David Lash
Presentation transcript:

Powering Scripts with Functions David Lash Chapter 4 Using and writing your own functions

David Lash Objectives zIntroduce this notion of a function  Some basic numeric PHP functions—E.g., sqrt(), round(), is_numeric(), and rand().  The print() function  The date() function. zSee what we can do for ourselves

David Lash 3 Using Some Basic PHP Functions zPHP has a bunch of built-in functions. yThey do things automatically for you: yFor example,  print (“Hello World”); xWe will look at other functions that do things for you Name of function Creates output with its one argument (or input variable).

David Lash 4 The sqrt() Function – Just to warm-up …  sqrt() - input a single numerical argument and returns its square root.  For example, the following y$x=sqrt(25); y$y=sqrt(24);  print "x=$x y=$y";  Will output yx=5 y= $y=144; $num = sqrt($y); Returned value Argument or parameter to function Function name

David Lash 5 The round() Function  round() - rounds number to nearest integer  For example, the following y$x=round(-5.456); y$y=round(3.7342);  print "x=$x y=$y";  Will output x=-5 y=4

David Lash 6 True/false Return values  So far functions have either returned nothing (e.g., print() ) or a number (e.g., round() ) zFunctions can also return a true or false value. yTrue is sometimes thought of 1 and false of 0 yThese are called boolean returned zWhy would you do this? …. yMakes testing something easy if ( got_a_number() ) { do stuff } yLets look at a true/false function …. This is just an example it is not a valid statement

David Lash 7 The is_numeric() Function  is_numeric() determines if a variable is a valid number or a numeric string. y It returns true or false.  Consider the following example... if (is_numeric($input)) { print "Got Valid Number=$input"; } else { print "Not Valid Number=$input"; }  If $input was “6” then would : Got Valid Number=6  If $input was “Happy” then would output : Not Valid Number=Happy Could use to test if input was string or numeric

David Lash 8 Remember this … Consider average example Survey Form Class Survey Pick A Number: Pick A Number 2: Pick A Number 3:

David Lash 9 PHP Code 1. Guess the Dice Your Averages Are: 4. 5.<?php 6. $num1 = $_POST[num1]; 7. $num2 = $_POST[num2]; 8. $num3 = $_POST[num3]; 9.if ( !is_numeric($_POST[num1]) || !is_numeric($_POST[num2]) || !is_numeric($_POST[num3]) ){ 10. print "Error please fill in numericaly values for all three inputs"; 11. print "num1=$num1 num2=$num2 num3=$num3"; 12. exit; 13.} 14. $aver = ($num1 + $num2 + $num3 ) / 3; 15. print " "; 16. print "num1 = $num1 "; 17. print "num2 = $num2 "; 18. print "num3 = $num3 "; 19. print " "; 20. print " aver = $aver"; 21. print " "; 22.?>

David Lash 10 The rand() Function – can be fun  Use rand() to generate a random number.  You can use random numbers to simulate a dice roll or a coin toss or to randomly select an advertisement banner to display.  rand() gen a number from 1 to max number.  E.g., $num = rand(); print ”num=$num” xMight output … num = 12

David Lash 11 The rand() Function - Part II  Use the rand() to generate a number 1-6 y$numb = rand(); y$rnumb = ($numb % 6) + 1; yprint "Your random dice toss is $rnumb";  The random number generated in this case can be a 1, 2, 3, 4, 5, or 6. Think a second … Asks for remainder of $numb / 6 which is always 0,1,2,3,4, or 5 so you add 1 to force it to be 1,2,3,4,5, or 6

David Lash 12 A Full Example... zConsider the following application:  Uses an HTML form to ask the end-user to guess the results of dice roll : y 1 y 2 y 3 y 4 y 5 y 6 

David Lash 13 Consider the following... Guess the Dice <?php $guess = $_POST["guess"]; if ( $guess >= 1 && $guess <=6 ) { $numb = rand() % 6 + 1; print "numb=$numb "; $dice="dice$numb.gif"; print "The Random Dice Generated Is..."; print " "; print " Your Dice=$dice "; if ( $guess == $numb ) { print " You got it right "; print " Your Guess is $guess "; } else { print " You got it WRONG ? "; print " Your Guess is $guess "; } } else { print "Illegal Value For Guess=$guess"; } ?> Generate random number 1-6 Set which image to display Display either dice1.gif, dice2,gif, dice3.gif, dice4.gif, dice5.gif, or dice6.gif Check to see if got it right or wrong

David Lash Objectives zTo learn to use several PHP functions useful for Web application development  Some basic numeric PHP functions—E.g., sqrt(), round(), is_numeric(), and rand().  The print() function  The date() function. zTo learn to write and use your own functions

David Lash 15 More information on the print() Function  You don’t need to use parenthesis with print()  Double quotes means output the value of any variable: y$x = 10; yprint ("Mom, please send $x dollars"); zSingle quotes means output the actual variable name y$x = 10; yprint ('Mom, please send $x dollars');  To output a single variable’s value or expression, omit the quotation marks. y$x=5; yprint $x*3; Double quotes “ Single quotes ‘

David Lash 16 Generating HTMLTags with print()  Using single or double quotation statements can be useful when generating HTML tags  print ' ';  This above is easier to understand and actually runs slightly faster than using all double quotation marks and the backslash (\) character : yprint " "; using \ allows “ to be output

David Lash Objectives zTo learn to use several PHP functions useful for Web application development  Some basic numeric PHP functions—E.g., sqrt(), round(), is_numeric(), and rand().  The print() function  The date() function. zTo learn to write and use your own functions

David Lash 18 The date() Function  The date() function is a useful function for determining the current date and time  The format string defines the format of the date() function’s output : x$day = date('d'); xprint "day=$day";  If executed on December 27, 2001, then it would output “ day =27”. Request date() to return the numerical day of the month.

David Lash 19 Selected character formats for date()

David Lash 20 More About date()  You can combine multiple character formats return more than one format from the date()  For example, y$today = date( 'l, F d, Y'); yprint "Today=$today";  On MQY 11, 2004, would output y“Today=Tuesday, May 11, 2004”.

David Lash 21 A Full Example...  Consider the following Web application that uses date() to determine the current date and the number of days remaining in a store’s sale event. ySale runs from 12/1 until 1/10/02

David Lash 22 Receiving Code 1. Our Shop <?php 4. $today = date( 'l, F d, Y'); 5. print "Welcome on $today to our huge blowout sale! "; 6. $month = date('m'); 7. $year = date('Y'); 8. $dayofyear = date('z'); 9. if ($month == 12 && $year == 2001) { 10. $daysleft = (365 - $dayofyear + 10); 11. print " There are $daysleft sales days left"; 12.} elseif ($month == 01 && $year == 2002) { 13. if ($dayofyear <= 10) { 14. $daysleft = (10 - $dayofyear); 15. print " There are $daysleft sales days left"; 16. } else { 19. print " Sorry, our sale is over."; 20. } 21. } else { 22. print " Sorry, our sale is over."; 23. } 24. print " Our Sale Ends January 10, 2002"; 25. ?> Get a date in format day of week, month, day and year Get month number 1-12,, 4 digit year and day of year Check if its Dec Then figure out days left in year and add 10. If if 1/2002 already, how many days left before 1/10? Otherwise sale is ove.

David Lash 23 The Output... The previous code can be executed at

David Lash Create your own functions... zWrite your own function to y group a set of statements, set them aside, and turn them into mini-scripts within a larger script. zThe advantages are yScripts that are easier to understand and change. yReusable script sections.  Smaller program size

David Lash 25  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 Use the keyword function here

David Lash 26 For example …  Consider the following : function OutputTableRow() { print ' One Two '; } zYou can run the function by including … OutputTableRow();

David Lash 27 As a full example … 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

David Lash 28 Would have the following output …

David Lash 29 TIP Use Comments at the Start of a Function zIt is good practice to place comments at the start of a function  For example, function OutputTableRow() { // Simple function that outputs 2 table cells print ' One Two '; }

David Lash 30 Passing Arguments to Functions zInput variables to functions are called arguments to the function zFor example, the following sends 2 arguments yOutputTableRow("A First Cell", "A Second Cell"); zWithin function definition can access values function OutputTableRow($col1, $col2) { print " $col1 $col2 "; }

David Lash 31 Consider the following code … Simple Table Function 3. Revised Simple Table 4. <?php 5. function OutputTableRow( $col1, $col2 ) { 6. print " $col1 $col2 "; 7. } 8.OutputTableRow( ‘Row 1 Col 1’, ‘Row 1 Col 2’ ); 9.OutputTableRow( ‘Row 2 Col 1’, ‘Row 2 Col 2’ ); 10.OutputTableRow( ‘Row 3 Col 1’, ‘Row 3 Col 2’ ); 11.OutputTableRow( ‘Row 4 Col 1’, ‘Row 4 Col 2’ ); 12. ?> 13. OutputTableRow() Function definition. Four calls to OuputTableRow()

David Lash 32 Returning Values zYour functions can return data to the calling script. yFor example, your functions can return the results of a computation. zYou can use the PHP return statement to return a value to the calling script statement: return $result; This variable’s value will be returned to the calling script.

David Lash 33 Example function 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. } What is output if called as follows: $largest = Simple_calc(15, -22); Return $num1 when it is the larger value. Return $num2 when it is the larger value.

David Lash 34 Consider an application that … Main form element: Starting Value: Ending Value:

David Lash 35 A Full Example... zConsider a script that calculates the percentage change from starting to an ending value  Uses the following front-end form: Starting Value: <input type="text" size="15” maxlength="20" name="start"> Ending Value: <input type="text" size="15” maxlength="20" name="end">

David Lash 36 The Source Code Your Percentage Calculation 3. Percentage Calculator 4. <?php 5. function Calc_perc($buy, $sell) { 6. $per = (($sell - $buy) / $buy) *100; 7. return($per); 8. } 9. $start = $_POST[“start”]; $end = $_POST[“end”]; 10. print " Your starting value was $start."; 11. print " Your ending value was $end."; 12. if (is_numeric($start) && is_numeric($end) ) { 13. if ($start != 0) { 14. $per = Calc_perc($start, $end); 15. print " Your percentage change was $per %."; 16. } else { print " Error! Starting values cannot be zero "; } 17. } else { 18. print " Error! You must have valid numbers for start and end "; 19. } 20. ?> Calculate the percentage change from the starting value to the ending value. The call to Calc_perc() returns the percentage change into $per.

David Lash 37 Using External Script Files zSometime you will want to use scripts from external files. yReuse code from 1 situation to another yCreate header and footer sections for code zPHP supports 2 related functions: require ("header.php"); include ("trailer.php"); zBoth search for the file named within the double quotation marks and insert its PHP, HTML, or JavaScript code into the current file. The require() function produces a fatal error if it can’t insert the specified file. The include() function produces a warning if it can’t insert the specified file.

David Lash 38 Consider the following example 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.

David Lash 39 header.php  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

David Lash 40 Would output the following...

David Lash 41 More Typical Use of External Code Files zMore typically might use one or more files with only functions and other files that contain HTML  For example, might use the following as footer.php. 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 Just ask for Harry.  Can include using:

David Lash 42 Even More Practical Example zCheck out the following link zOriginal found at perl-pgm.comperl-pgm.com zCould hard code header in each file that needs it or … ySeparate the header info into a different file (Say header.php.) yInclude it everywhere needed. yE.g., Indellible Technologies <body text="#000000" bgcolor="#ffffff" link="#000099" vlink="#990099" alink="#000099">

David Lash 43 Here is contents of header.php <img src="INdelliblecolor3.gif" alt="" width="792" height="102"> <a href="requestinfo.html">Request Information | <a href="preregister.html">Pre-register | CourseCatalog | Testimonials

David Lash Summary zTo learn to use several PHP functions useful for Web application development  Some basic numeric PHP functions—E.g., abs(), sqrt(), round(), is_numeric(), and rand().  The print() function  The date() function. zTo learn to write and use your own functions yWriting own functions yreturning values yPassing arguments

David Lash 45 Here is the receiving code... Receiving Script <?php $passwd= $_POST["pass"]; $fname= $_POST["fname"]; if ($passwd == "password" ) { print "Thank you $fname welcome "; print "Here is my site's content"; } else { print "Hit the road jack you entered password=$passwd "; print "Contact someone to get the passwd"; } ?>

David Lash 46 Summary zLooked at using conditional statements yif statement yelsif statement yelse statement zconditional statements have different format if ( $x < 100 ) { $x = $y + 1; $z = $y + 2; } zCan do multiple tests at once: if ( $x < 100 && $name = “george” ) { $x = $y + 1; $z = $y + 2; }  Can test if variable(s) set from form zif ( !$_POST[‘var1’] || !$_POST[‘var1’] ) {