intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

PHP and MySQL by Example- P8

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

84
lượt xem
14
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p8', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: PHP and MySQL by Example- P8

  1. 3 function get_info(){ $record=array(); 4 $result_set=mysql_query("SELECT * FROM Shippers"); 5 while($row=mysql_fetch_assoc($result_set)){ array_push($record, $row); } 6 return($record); } ?> Explanation 1 The  PHP  mysql_connect()  function  opens  up  a  connection  to  the  MYSQL   server  and  returns  a  link  to  the  server  so  that  now  we  can  access  a  database. 2 This  is  where  the  database  is  selected.  A  popular  database  called  northwind  is   opened  and  a  resource  handle  is  returned  to  give  access  to  it.  A  resource  type   holds  a  special  handler  to  the  database  connection  created  when  the  database   connection  was  made. 3 The  function,  get_info(),  is  defined.  It  will  retrieve  all  the  records  from  the   Shippers  table  and  return  them  to  the  caller. 4 The  mysql_query()  function  sends  a  query  to  the  currently  active  northwind   database  and  returns  a  reference  to  the  data  it  selected;  that  is,  all  of  the   records  in  Shippers. 5 The  mysql_fetch_assoc()  function  returns  an  associative  array  that   corresponds  to  the  fetched  row  and  moves  the  internal  data  pointer  ahead  to   the  next  row. 6 A  set  of  records  from  the  Shippers  table  are  returned  to  the  caller  as  an  array   of  associative  arrays. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. 7 The  get_info()  function  is  called.  An  array  of  records  (associative  arrays)  is   returned  and  assigned  to  $company_list. 8 The  foreach  loop  is  used  to  iterate  through  the  keys  and  values  of  the  three   arrays,  each  of  which  contains  an  associative  array. 9 This  inner  foreach  loop  retrieves  the  keys  and  values  from  each  of  the   associative  arrays  returned  from  the  function,  which  is  each  record  in  the   Shippers  table.  The  output  is  shown  in  Figure  9.13. Figure 9.13. A function that returns an associative array. Output from Example 9.10.   9.1.4. Using Callback Functions A callback function is one that is not directly invoked in the program; instead it is invoked by another function. What that means is that one function takes another function, called the callback function, as its argument. Callback functions are often used to perform some arbitrary task on each item in a list of items. One function traverses the list, and the other provides the code to represent the task that will be performed on each item. PHP provides a number of array functions that utilize “callbacks.” Some of these functions are preg_replace(), array_filter(), array_map(), and so on. (Callback functions cannot only be simple functions, but also object methods including static class methods. See Chapter 17, “Objects.”) A PHP function is simply passed by its name as a string. You can pass any built-in or user-defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print(), and unset(). The array_map() Function The following example uses PHP’s array_map() function to demonstrate the use of a callback function. The array_map() function returns an array containing all the elements of the original array after applying the callback function to each element. The number of parameters that the callback function accepts should match the number of arrays passed to array_map(). Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. Format array array_map ( callback callback, array arr1 [, array ...] )   Example: function square($n){ // User-defined callback function return $n * $n; } $numbers=array(1,4,6,8); $squared_list = array_map("square", "$numbers"); Example 9.11. Explanation 1 This  is  a  user-­‐defined  callback  function.  It  will  be  called  for  each  element,   $price,  in  an  array  of  values  that  it  receives  from  another  function,  called   array_map(). 2 The  value  of  each  element  of  an  array  will  be  returned  after  the  sales  tax  has   been  applied  to  it. 3 An  array  called  $after_prices  is  returned  by  the  callback  function  after  it  has   performed  a  calculation  on  each  element  of  $before_prices. 4 The  array_map()  function  applies  a  specific  task  to  each  element  of  an  array   by  using  a  callback  function  to  perform  the  task.  In  this  example,  the   array_map()  function  takes  two  arguments:  $salesprice,  the  name  of  the   callback  function  (passed  as  a  string)  that  will  be  called  for  each  element  in  an   array;  and  $before_prices,  the  name  of  the  array  on  which  the  callback   function  will  perform  the  same  task  for  each  of  the  elements.  Simply,  each   price  in  the  list  will  have  a  sales  tax  applied  to  it.  The  new  array,   $after_prices,  will  reflect  the  price  after  the  sales  tax  was  added  in. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. 5 The  original  prices  are  printed. 6 The  new  prices,  after  the  sales  tax  is  calculated,  are  printed.  See  Figure  9.14.   Figure 9.14. A callback function. Output from Example 9.11. The array_walk_recursive() Function The array_walk_recursive() applies a user-defined callback function to every element of an array and will recurse into nested arrays. Normally the array_walk_recursive() function takes two arguments: the first one the array being walked over, and the second one the value of the key or index of the array. A third, optional argument is an additional value that you can send to the callback function. The functon returns true on success and false on failure. If your callback function needs to be working with the actual values of the array, specify the first parameter of the callback as a reference. Then, any changes made to those elements will be made in the original array itself. Format bool array_walk_recursive ( array &input, callback funcname [, mixed userdata] )   Example: $employee=array("Name"=>"Bob", "Title"=>"President"); array_walk_recursive($employee, 'callback_function'); Example 9.12. Code  View:   Walking Through a Multidimensional Array Using a Callback Function with a Multidimensional Array
  5. array(20,25,30,35), ); 2 function cube(&$element,$index){ print $index; // prints 012301230123 $element=$element*$element*$element; } ?> The array_walk_recursive() function
  6. Figure 9.15. Using a callback function. Output from Example 9.12.   9.1.5. Scope Scope refers to the parts of a program that can see or access a variable; that is, where the variable is visible. Lifetime is how long the variable exists. There are three types of scope for PHP variables: local, global, and static. Local variables are visible within a function and their life ends when the function ends. Global variables are visible to a script, but not normally to a function. They live throughout the run of the script, and die when the script ends. Static variables are local to a function but retain their value from one function call to another. They die when the script ends. Let’s look at some examples to see how scope and lifetime work. Local Scope By default, all variables declared within functions are local to the function; that is, they are not visible outside the function and die when the function exits. In computer jargon, these variables are pushed onto a stack when the function starts and popped off when the function ends. Example 9.13. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. Explanation 1 $friend  is  a  global  variable  in  that  it  is  visible  to  the  main  script,  and  will  disappear   when  the  script  ends.  It  will  not  be  visible  within  functions. 2 The  function  called  who()  is  defined. 3 Even  though  this  variable  is  also  called  $friend,  it  is  a  different  variable.  It  is  local  to  the   function  and  will  disappear  when  the  function  ends.  If  this  variable  had  not  been   defined,  the  original  $friend  would  still  not  be  visible  here. 4 The  function,  who(),  is  called.  Once  in  the  function  the  $friend  value  Sam  is  out  of  scope   until  the  function  ends.  Joe  is  the  friend. 5 Outside  the  function,  global  variable  $friend  is  now  in  scope  and  Sam  is  the  friend.  See   Figure  9.16.   Figure 9.16. Local scope. Output from Example 9.13. Global Scope From within a function you cannot access variables that were declared outside the function unless you pass the variable to the function as an argument, by reference. If you need to access an external variable within a function without passing it by reference, then you can use the global statement. By placing the global keyword in front of a variable name, the variable that was defined outside the function can now be accessed. Format global variable_name1, variable_name2, variable_name3.....;   Example: global$salary; Example 9.14. Function Arguments
  8. ?> 6 Congratulations! Your new salary is $."; Explanation 1 The  function  raise_sal()  is  defined. 2 The  keyword,  global,  allows  this  function  to  have  access  to  the  variable,  $salary,   defined  outside  this  function. 3 The  global  $salary  is  being  modified  in  the  function. 4 The  variable,  $salary,  is  defined  outside  the  function  and  is  not  available  to  the   function,  unless  it  is  passed  by  reference  or  is  made  global  within  the  function. 5 The  raise_sal()  function  is  called. 6 The  HTML  output  shows  that  the  salary  was  changed  in  the  function.  See  Figure  9.17.   Figure 9.17. Global scope. Output from Example 9.14. The $GLOBALS() Array The other way to access a global variable within a function is with the $GLOBALS[] array. It contains all the variables that have global scope in the script (i.e., any variables declared outside of functions). Example 9.15. Function Arguments Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. 2 Congratulations! Your new salary is $. Explanation 1 The  $_GLOBALS[]  array  gives  the  function  access  to  variables  defined  from  outside  the   function;  in  this  case,  $salary.  The  name  of  the  variable  becomes  the  key  in  the   $_GLOBALS[]  associative  array.  This  example  is  exactly  like  Example  9.14  except,  in  that   example,  the  global  keyword  was  used  to  make  the  variable  $salary  available  to  the   function. 2 The  HTML  output  shows  that  the  salary  was  changed  in  the  function.  See  Figure  9.18.   Figure 9.18. Using the $GLOBALS array. Output from Example 9.15. Static Variables The variables declared within functions normally disappear when the function ends. They are local to the function. They are created when the function is called and die when it ends. A static variable is local to the function, meaning it is not visible outside of the function, but it does not die when the function ends. Once initialized a static variable will not lose its value between function calls. It “remembers” the value it held from one call to the next. Example 9.16. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. Explanation 1 By  making  the  variable  static,  it  will  retain  its  value  even  after  the  function  exits.  Each   time  trackme()  is  called,  the  count  will  be  incremented  by  1.  The  variable,  $count,  is   only  initialized  to  zero  the  first  time  the  function  is  called. 2 The  value  of  $count  is  incremented  by  1. 3 The  function  trackme()  is  called  three  times.  Each  time  it  is  called,  the  value  of  the   counter  is  incremented  and  displayed.  See  Figure  9.19. Figure 9.19. Static variables. Output from Example 9.16. Example 9.17. Code  View:   Function Arguments 5
  11. } ?> Explanation 1 The  function  increase_font()  is  defined.  It  has  parameter,  $size,  which  represents  the   font  size  for  the  verdana  font  listed  above. 2 The  static  variable  $total  is  defined  and  is  assigned  an  initial  value  of  0.  This  variable   will  not  forget  its  value  after  the  function  exits.  Static  variables  retain  their  value  from   function  call  to  function  call. 3 The  variable,  $newfont,  is  increased  by  1  when  the  function  is  called. 4 The  value  of  variable,  $newfont,  is  added  to  $total. $total  is  static;  that  is,  it  retains   its  value  from  the  last  function  call.  Otherwise,  it  would  be  set  back  to  zero  each  time  the   function  is  called. 5 The  value  of  the  new  font  size  is  assigned. 6 When  the  accumulated  total  reaches  a  value  greater  than  10,  the  script  exits. 7 Each  time  through  the  for  loop,  the  function,  increase_font()  is  called,  causing  the   font  to  be  increased  by  1  point  size.  See  Figure  9.20.   Figure 9.20. Static variables. Output from Example 9.17. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. 9.1.6. Nesting Functions PHP supports nesting functions. A nested function is defined and called from within another function. The outer function, also called the parent function, has to be invoked for the nested function to become available to the program. Nested functions are rarely used. Format function OuterFunction(){ function NestedFunction(){ /*OuterFunction() must be called before NestedFunction() is available.*/ statements; } } PHP functions can also be nested inside other statement blocks, such as conditional statements. As with nested functions, such functions will only be defined when that block of code has been executed. Example 9.18. Explanation 1 The  function  outer()  will  be  the  parent  function  for  the  function  nested  within   it. 2 This  is  the  declaration  for  the  nested  function  square().  Because  it  is  nested  in   the  outer()  function,  it  will  not  be  defined  until  outer()  has  been  called. 3 The  return  value  from  this  nested  function  is  the  square  of  its  parameters. 4 The  value  returned  will  be  the  sum  of  $a  and  $b  after  the  nested  square()   function  has  squared  them  both. 5 The  parent  function,  called  outer(),  is  called,  the  two  numbers  are  passed,  and   the  sum  of  their  squared  values  is  returned.  Once  outer()  is  called  the  nested   function  will  be  defined.  See  Figure  9.21. 6 Just  like  any  other  function,  the  nested  function,  square(),  is  available  once  it   is  defined.  It  is  not  available  until  the  outer()  function  has  been  called.  See   Figure  9.22. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. is  defined.  It  is  not  available  until  the  outer()  function  has  been  called.  See   Figure  9.22.   Figure 9.21. Using nested functions. Figure 9.22. Output from Example 9.18. Once the outer or parent function has been executed, the nested function is defined and accessible from anywhere within the current program just like any other function. You can only execute the parent function once if it contains nested functions; otherwise, PHP will generate a fatal error as shown in Figure 9.23. Example 9.19.
  14. $sum=outer(5,8); echo "The sum of the squares is: $sum\n
  15. 3 $count++; 4 switch($num) { case 0: return(0); break; case 1: return(1); break; default: // Including recursive calls 5 return(fib($num - 1) + fib($num - 2)); break; } } ?> Fibonacci Sequence
  16. 5 This  is  the  heart  of  the  recursive  program.  The  result  of  the  first  call  to  the  fib()   function  is  added  to  the  result  of  another  call  to  fib().  The  function  will  continue  to  call   itself  until  it  reaches  a  point  where  it  either  returns  0  or  1.  If  the  $num  is  4,  then  fib()  is   called  9  times.  The  sequence  goes  something  like  this:     call 1 fib(4) 3 Returns 3 call 2 fib(3) + call 7 fib(2) 2 + 1 Returns 3 call 8 fib(1) + call 9 fib(0) 1 + 0 Returns 1 call 3 fib(2) + call 6 fib(1) 1 + + Returns 2 call 4 fib(1) + call 5 fib(0) 1 + 0 Returns 1 6 The  for  loop  will  iterate  through  10  numbers,  starting  at  0.  Each  number  will  be  sent,  in   turn,  to  the  fib()  function  for  evaluation. 7 This  is  the  first  call  to  the  fib()  function.  The  next  value  in  the  Fibonacci  series  will  be   returned  by  adding  the  current  value  and  its  previous  value.  For  example,  if  5  is  passed   to  fib(),  the  number  returned  will  be  5  +  3,  or  8.  See  Figure  9.24. 8 This  number  shows  you  how  many  times  the  function  fib()  was  called  to  produce  the   sequence  shown  in  the  table  in  Figure  9.24.   Figure 9.24. Recursive function. Output from Example 9.20.   9.1.8. Function Libraries—Requiring and Including If you have a function or set of functions that you will reuse in other PHP programs, then you can save the functions in a file, called a library. When you are ready to use the functions, just include the library in the current script with the include() or require() built-in functions. Suppose, for example, you have two functions: one called total() to calculate the total of a set of numbers, and another called ave() to calculate the average of a set of numbers. We will store these user-defined functions in a library file called mylibrary.php shown in Figure 9.25: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. Figure 9.25. The library file.   The require() and include() Constructs PHP provides the require() and include() constructs to allow you to use the functions from the library file in a PHP script as shown here: Format Code  View:   ------------------------------------------------------------------ ----------- The include() and require() constructs cause a specified file to be included and evaluated in your script, similar to pasting the contents of a file in your script at the line where they were requested. When you place a function within an external file that will later be included, be sure to enclose the function within PHP tags, because, when a file is included, if the PHP tags are missing, PHP automatically starts processing the included file as an HTML document. The only difference between include() and require() is how they deal with failure. The include() produces a warning and allows the script to continue executing while require() produces a fatal error. For PHP to find the file you want to include, it searches an include_path defined in the php.ini file[1], and if the file is not in the path, this would cause an error. (Files for including are first looked for in the include_path relative to the current working directory and then in the include_path relative to the directory of current script. If a filename begins with ./ or ../, it is looked for only in include_path relative to the current working directory.) [1] To change include_path from your program, use the built-in ini_set function described in the PHP manual: http://www.php.net/manual/en/function.ini-set.php. With require() the missing file would cause the script to exit, whereas with include(), the program will continue to run. You can also use an absolute path such as require('C:\pub\library\file.php') or include('/usr/htdocs/file.php'). Just like require() and include(), the require_once() and include_once() statements, respectively, include and evaluate the specified file during the execution of the script, but require_once() and include_once() will only include a file once, even if you have more require or include statements throughout the script. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. Include files are often used to help manage the content of a Web site. The files are external to the program and included as needed. For a discussion on content management, see “Managing Content with Include Files” on page 487. Example 9.21. Code  View:   Including a file ------------------------------------------------------------------ --- (file: test.library) 6 Explanation 1 The  variable,  $color,  is  assigned  the  color  "red". 2 The  require_once()  function  includes  a  file  given  as  its  argument.  At  the  point  this   file  is  loaded,  all  variables  and  functions  within  it  are  available  to  this  program.  The   require_once()  function  only  loads  the  file  once,  so  that  if  in  the  future  another   require()  function  is  executed,  it  will  not  be  included  again.  The  value  of  the   variable,  $color,  in  the  required  file,  is  purple. 3 The  user-­‐defined  function,  welcome(),  is  called.  Its  definition  is  in  the  included  file.   The  color  of  the  font  will  be  purple  because  the  variable,  $color,  is  assigned  "purple"   in  the  required  file  on  line  7.  See  Figure  9.26. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. 4 The  variable  $color  is  a  global  variable.  It  is  assigned  the  value  "blue"  on  line  4. 5 The  user-­‐defined  function,  welcome(),  is  called  again.  This  time  the  color  of  the  text   will  be  "blue".  The  function  defined  a  global  variable,  $color.  It  gets  the  value  of  the   color  defined  outside  the  function. 6 The  included  file  contains  PHP  code.  Remember,  if  you  do  not  enclose  the  code  of  the   included  file  with  PHP  tags,  when  PHP  starts  processing,  it  will  treat  the  code  as   though  it  were  an  HTML  document,  causing  an  error. 7 When  a  file  is  required,  the  variables  defined  within  it  become  part  of  the  current   PHP  script.  Notice  that  when  the  welcome()  function  is  called,  the  color  of  the  text  is   purple,  not  red,  because  the  required  file  redefined  $color,  overwriting  the   $color="red"  with  $color="purple". 8 This  is  where  the  user-­‐defined  function  is  defined  within  the  external  file. 9 To  make  variables  from  outside  the  function  available  to  the  function,  the  keyword   global  is  used. 10 The  variable,  $mood,  is  defined  as  a  local  variable. 11 It  is  not  seen  outside  the  function.  The  color  of  the  font  changes  as  the  value  of  $color   changes.  See  Figure  9.26.   Figure 9.26. Storing functions in an external file. Output from Example 9.21. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. 9.2. Chapter Summary 9.2.1. What You Should Know Now that you have finished this chapter you should be able to answer the following questions: 1. What  is  the  definition  of  a  function?   2. How  do  you  invoke  a  function?   3. How  do  you  pass  arguments  to  a  function  by:     a. Reference? b. Value? 4. How  do  you  return  values  from  a  function?   5. What  are  default  arguments?   6. What  is  the  difference  between  local,  global,  and  static  scope?   7. How  do  you  make  a  variable  that  is  defined  outside  of  a  function  available  to  that   function?   8. What  is  recursion?   9. What  is  a  callback  function?   10. How  do  you  nest  a  function  within  other  functions?   11. How  do  you  include  a  function  defined  in  another  file?   12. What  is  the  difference  between  require()  and  include()?   9.2.2. What’s Next? Now that you have a good handle on functions, it is time to talk about how PHP and HTML work together when producing forms. In Chapter 10, “More on PHP Forms,” you will see a number of functions to handle incoming data, most of them user defined. Chapter 9 Lab 1. Ask  the  user  how  many  Euros  he  or  she  spent  in  Germany?  Write  a  function  to   convert  the  Euros  to  U.S.  dollars  based  on  today’s  exchange  rate.   2. Create  a  function  called  converter()  that  will  take  two  arguments.  The  first   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2