Title: PHP and MySQL
1PHP and MySQL
- David Lash
- Module 3
- Powering scripts with functions
2Objectives
- 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!
3Notes on print()
- You dont 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 variables value or
expression, omit the quotation marks. - x5
- print x3
- - Note Single quotes with HTML tags print
'ltfont color"blue"gt' - - Can also escape with \
- print "ltfont color\"blue\"gt"
4print() VS echo()
- Use echo() when want to output a variable's value
directly
lt?php echo "hello" echo "x", rand(1, 6)
echo 2 2 , 22, but 4 4, 44 ?gt
5Testing 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
6is_numeric()
lt?php echo '2 ', (is_numeric('2') ? "true"
"false") . "ltbrgt" echo '2.4 ',
(is_numeric('2.4') ? "true" "false") .
"ltbrgt" echo '2.2b ', (is_numeric('2.2b') ?
"true" "false") . "ltbrgt" echo '.5 ',
(is_numeric('.5') ? "true" "false") .
"ltbrgt" echo '1.2.5 ', (is_numeric('1.2.5') ?
"true" "false") . "ltbrgt" echo 'A.5 ',
(is_numeric('A.5') ? "true" "false") .
"ltbrgt" ?gt
7is_set()
- Checks if variable exists.
- Most useful for checking array elements
- if (!is_set(_POSTname !is_set(_POSTscor
e ) - print (Error you must specify name and score)
Note from php.net contrib notes lt?php a 0
print isset(a) ? "TRUEltbrgt" "FALSEltbrgt"
//TRUE b "0" print isset(b) ? "TRUEltbrgt"
"FALSEltbrgt" //TRUE c "" print isset(c) ?
"TRUEltbrgt" "FALSEltbrgt" //TRUE d 1 print
isset(d) ? "TRUEltbrgt" "FALSEltbrgt" //TRUE
print isset(e) ? "TRUEltbrgt" "FALSEltbrgt"
//FALSE f TRUE print isset(f) ? "TRUE ltbrgt"
"FALSEltbrgt" //TRUE g FALSE print isset(g)
? "TRUEltbrgt" "FALSEltbrgt" //TRUE harray()prin
t isset(h) ? "TRUEltbrgt" "FALSEltbrgt" //TRUE ?gt
8empty()
- 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(_POSTname empty(_POSTscore
) - 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
harray()print empty(h) ? "TRUE" "FALSE"
//TRUE
9The 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"
10A rand() application
lthtmlgtltheadgtlttitlegt Favorite Character lt/titlegt
lt/headgtltbodygt My favorite cartoon character is
lt?php r rand(1, 6) print "ltimg
srctoonr.gifgt" ?gt that guy lt/bodygtlt/htmlgt
Banner ads can be randomly displayed 1. Store
image as toon1.gif, toon2.gif, etc. 2. Assemble
file image to use on the fly
11Objectives
- 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
12A couple HTML support Functions
Find html special characters, and convert (e.g.,
lt to lt, to amp
- 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 \.
lt?php str "A ltbgtboldlt/bgt 'quote' lt and fun
." print "Original stringstr \n" echo
"specchars(str)", htmlspecialchars(str),
"\n" echo "specchars(str, ENTQUOTE)",
htmlspecialchars(str, ENT_QUOTES), "\n" echo
"addslashes(str)", addslashes(str), "\n" ?gt
Original stringA ltbgtboldlt/bgt 'quote' lt and fun
. specchars(str)A ltbgtboldlt/bgt
'quote' lt and amp fun . specchars(str,
ENTQUOTE)A ltbgtboldlt/bgt
039quote039 lt and amp fun
. addslashes(str)A ltbgtboldlt/bgt \'quote\' lt 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)
13The date()Function
- Use date() for date and time info
- The format string defines output format
- day date('d')
- print "dayday"
One or more characters that define output.
str date(format string')
Request date() to return the numerical day of the
month.
Note If executed on December 27, 2005, would
output day27.
- Note Can also combine multiple character formats
- For example,
- today date( 'l, F d, Y')
- print "Todaytoday"
- On April 27, 2005, would output
- TodayWednesday, December 27, 2005
14Selected date() character formats
15Working with UNIX timestamps
Returns number of seconds since Unix Epoch
(January 1 1970 000000 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
lt? todaydate('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" ?gt
today is 2005-04-18 please comeback nextweek
2005-04-25
16Days to Christmas Code
1 lthtmlgt ltheadgt lttitlegt days to Christmas
lt/titlegt lt/headgt 2 ltbodygt 3 lt?
4 today time() 5 day date( 'l, F d,
Y') 6 print "Todayday ltbrgt" 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 ?gtlt/bodygt lt/htmlgt
Get the current time since UNIX epoch.
Get the current day
Get the current epoch Seconds for 000000 Dec
25, 2004
17A little more on mktime() and date()
Converts 32nd day
lt?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" ?gt
Converts extra 13th month
Converts date in past
Converts 2 digit year
Jan-01-2011 Jan-01-2003 Jan-01-1998 Dec-01-2006
18Objectives
- 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
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
20Writing 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 'lttrgtlttdgtOnelt/tdgtlttdgtTwolt/tdgtlt/trgt'
-
- You can run the function by executing
- OutputTableRow()
21As a full example
Note Function definition can be before or after
function call
- 1. lthtmlgt
- 2. ltheadgtlttitlegt Simple Table Function lt/titlegt
lt/headgt ltbodygt - 3. ltfont color"blue" size"4"gt Here Is a Simple
Table lttable border1gt - 4. lt?php
- 5. function OutputTableRow()
- 6. print 'lttrgtlttdgtOnelt/tdgtlttdgtTwolt/tdgtlt/tr
gt' - 7.
- 8. OutputTableRow()
- 9. OutputTableRow()
- 10. OutputTableRow()
- 11. ?gt
- 12. lt/tablegtlt/bodygtlt/htmlgt
OutputTableRow() function definition.
Three consecutive calls to the OutputTableRow()
function
22Passing 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 values
- function OutputTableRow(col1, col2)
- print "lttrgtlttdgtcol1lt/tdgtlttdgtcol2lt/tdgtlt/trgt"
-
23Consider the following code
- 1. lthtmlgt
- 2. ltheadgtlttitlegt Simple Table Function lt/titlegt
lt/headgt ltbodygt - 3. ltfont color"blue" size4gt Revised Simple
Table lttable border1gt - 4. lt?php
- 5. function OutputTableRow( col1, col2 )
- 6. print "lttrgtlttdgtcol1lt/tdgtlttdgtcol2lt/tdgtlt
/trgt" - 7.
- 8. for ( i1 ilt4 i )
- 9. message1"Row i Col 1"
- 10. message2"Row i Col 2"
- 11. OutputTableRow( message1, message2
) - 12.
- 13. ?gt
- 14. lt/tablegtlt/bodygtlt/htmlgt
OutputTableRow() Function definition.
Four calls to OuputTableRow()
24Objectives
- 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
25Returning 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 gt num2) 5.
return(num1) 6. else 7.
return(num2) 8. 9.
For example largest Simple_calc(15, -22)
26Example 2 Function checks if its been 24 hours
since last post
lt?php lastpost mktime(5,15,0,04,15,2005) echo
'Last Post was ', date("M-d-Y Hms a",
lastpost), "\n" now date("M-d-Y Hms 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 Hms a", lastpost(360024)) fun
ction canPost(lastpost, diff) diff
diff3600 convert hourse into
seconds nextpost lastpostdiff
timenow time() if (timenow gt
nextpost) return true else
return false
Last Post was Apr-15-2005 050400 am Time is
Apr-19-2005 070409 am It is OK to Post
27Passing by Reference
- When want to change an argument must pass
reference. - 1 lthtmlgt ltheadgtlttitlegt Pass by Reference
lt/titlegt lt/headgt - 2 ltbodygt
- 3 lt?php
- 4 fname 'John'
- 5 lname 'Adams'
- 6 print "ltfont colorbluegt Pre call "
- 7 print "fnamefname lnamelname
lt/fontgtltbrgt" - 8 output_val( fname, lname )
- 9
- 10 print "ltbrgtltfont colorredgt Post call
" - 11 print "fnamefname lnamelname
lt/fontgt" - 12 function output_val( first, last )
- 13 first 'George'
- 14 last 'Washington'
- 15
- 16 ?gt lt/bodygtlt/htmlgt
The indicates pass by reference
The default is pass value
28Using Default Argument Values
- When want to change an argument must pass
reference. - 1 lthtmlgt ltheadgtlttitlegt Pass by
Referencelt/titlegt lt/headgt - 2 ltbodygt
- 3 lt?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 "ltfont sizesize
colorcolorgt" - 11 print "text lt/fontgt"
- 12
- 13 ?gt lt/bodygtlt/htmlgt
Call three different ways
Set default values for size and color
29Objectives
- 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
30Using 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 cant insert the
specified file.
Produce a warning if it cant 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.)
31Consider the following example
- 1. ltfont size4 color"blue"gt
- 2. Welcome to Harrys Hardware Heaven!
- 3. lt/fontgtltbrgt We sell it all for you!ltbrgt
- 4. lt?php
- 5. time date('Hi')
- 6. function Calc_perc(buy, sell)
- 7. per ((sell - buy ) / buy) 100
- 8. return(per)
- 9.
- 10. ?gt
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.
32header.php
- If the previous script is placed into a file
called header.php - 1. lthtmlgtltheadgtlttitlegt Hardware Heaven
lt/titlegtlt/headgt ltbodygt - 2. lt?php
- 3. include("header.php")
- 4. buy 2.50
- 5. sell 10.00
- 6. print "ltbrgtIt is time."
- 7. print "We have hammers on special for
\sell!" - 8. markup Calc_perc(buy, sell)
- 9. print "ltbrgtOur markup is only markup!!"
- 10. ?gt
- 11. lt/bodygtlt/htmlgt
Include the file header.php
Calc_perc() is defined in header.php
33More Typical Use of External Code Files
- Might use one or more files with only functions
and other files that contain HTML - For example,
- lthrgt
- Hardware Harry's is located in beautiful downtown
Hardwareville. - ltbrgtWe are open every day from 9 A.M. to
midnight, 365 days a year. - ltbrgtCall 476-123-4325. Just ask for Harry.
- lt/bodygtlt/htmlgt
- Can include using
- lt?php include("footer.php") ?gt
34config.php
More Typical Use of External Code Files
- lt?php
- HOME /home/dlash
- email dlash01_at_yahoo.com
- color red
- size 122
- function output_val( text, size 3,
color 'blue' ) - print "ltfont sizesize
colorcolorgt" - print "text lt/fontgt"
-
- ?gt
35Summary
- 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
36Module 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
- ltinput typeradio namename valuevalue1gt
label1 - ltinput typeradio namename valuevalue2gt
lable2 - otextbox( name, label, size )
- Would output
- ltinput typetext namename sizesizegt 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.
37One possible solution
- 1 lthtmlgt ltheadgt lttitlegt form test lt/titlegt
lt/headgt - 2 ltbodygt
- 3 lt?php
- 4 include('lab3.php')
- 5 oform( 'lab3_handle.php')
- 6 otextbox( "name", 'What is your
name?', 20 ) - 7 print "ltbrgtDid you enjoy the course?"
- 8 oradio( 'enjoy', 'yes', 1, 'no', 0)
- 9 ?gt
- 10 ltbrgtltinput typesubmitgt
- 11 lt/formgt lt/bodygt lt/htmlgt
38The file lab3.php
1 lt?php 2 function oradio( name,
label1, value1, label2, name2 ) 3
print "ltinput typeradio namename
valuevalue1gt label1" 4 print "ltinput
typeradio namename valuevalue2gt label2"
5 6 function otextbox( name, label,
size 40 ) 7 print "label
ltinput typetext namename sizesizegt "
8 9 function oform ( action ) 10
if ( empty(action) ) 11
print "Error actionaction cannot be empty
ltbrgt" 12 exit 13
14 print "ltform actionaction
methodpostgt" 15 16 ?gt
39Hands-on Lab 2
Ask 2 survey questions
Common footer
Must answer both questions
40Front end-Survey
survey.php
lthtmlgt ltheadgt lttitlegtScheduleslt/titlegt lt/headgt
ltbody bgcolor"ffffff"gt lth1gt Precourse Survey
for Building Web Applications with PHP and Mysql
lt/h1gt lttable cellpadding"6" cellspacing"0"
border"0" gt ltform action'results.php'
methodpostgt lttrgt lttdgt 1. What is your experience
using any programming language? lt/tdgt lttdgt ltinput
typeradio nameprogramming value0gt none ltinput
typeradio nameprogramming value1gt some ltinput
typeradio nameprogramming value2gt lots lt/tdgt
lt/trgt lttrgt lttdgt 2. What is your experience using
any php/mysql ? lt/tdgt lttdgt ltinput typeradio
namephp value0gt none ltinput typeradio namephp
value1gt some ltinput typeradio namephp value2gt
lots lt/tdgt lt/trgt lttrgt lttdgt ltinput typesubmitgt
lt/tdgt lt/formgt lt/tablegt lt?php include 'footer.php'
?gt lt/bodygt lt/htmlgt
footer.php
lthrgt ltcentergt David Lash ltbrgt 13 13 Mockingbird
Lane ltbrgt dlash_at_yahoo.com
41One possible solution
lthtmlgt ltheadgt lttitlegtScheduleslt/titlegt lt/headgt
ltbody bgcolor"ffffff"gt lth1gt Survey Results
lt/h1gt lt?php if ( !isset( _POST'php' )
!isset( _POST'programming' ) ) print
"Error you must specify a value for Q1 and Q2
ltbrgt" include 'footer.php'
exit else prog _POST'programming'
print "Received Q1 prog ltbrgt" print
"Received Q2 _POST'php' ltbrgt" include
'footer.php' ?gt lt/bodygt lt/htmlgt
42Which Can Be Modified To . . .
lthtmlgt ltheadgt lttitlegtScheduleslt/titlegt lt/headgt
ltbody bgcolor"ffffff"gt lth1gt Survey Results
lt/h1gt lt?php if ( !isset( _POST'php' )
!isset( _POST'programming' ) ) print
"Error you must specify a value for Q1 and Q2
ltbrgt" include 'footer.php'
exit else prog _POST'programming'
print "Received Q1 prog ltbrgt" print
"Received Q2 _POST'php' ltbrgt" addr
'dlash_at_condor.depaul.edu' subj 'Survey
Results' msg "Q1prog \n Q2php "
mail( "addr", "Indelible Survey Results",
msg) include 'footer.php' ?gt lt/bodygt lt/htmlgt