SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
IELM 511 Information Systems Design
                           Lab 4: Fundamental PHP functions: II

This lab will use a few more exercises to build up your experience with PHP scripts. In
subsequent labs, you will write CGI programs that connect to a Database and exchange
information with the DB, returning the feedback to the web client. Since most data in DBs
is stored in tables, and cell entries are mostly strings, therefore the two data types we need
to handle in our programs are (multi-dimensional) arrays, and strings. In this lab, we will
build up some more experience with these, working on basic language skills for PHP.

Objectives of this lab
Gain some familiarity with the following concepts:
(a) Basic data structures in PHP: multi-dimension arrays
(b) Program flow control: functions
(c) Regular expressions and string parsing.

As before, if you need to look up the syntax of some operator/function in PHP, you can use
a good online PHP tutorial site, such as: http://www.w3schools.com/PHP/

The lab tasks are below.

Step 1. [Re-use from past lab]. Make a simple web-form (file: run_cgi.html) with one
input field and one text-box field (use or modify the file given to you in the lab materials).

Step 2. Try the following code using phpDesigner, and then modify it as instructed.
In most php program, we work with strings; common examples:
    - If you read a line of data from a file, you will read it as a string of characters;
    - The most common data types stored in a Database are strings.
PHP provides several useful string functions and operators.

   <?php
    $x = "I love"; // declare a variable, $x, and define its value(of type string)
    $y = " PHP !"; // declare and define variable $y
    $z = $x . $y;     // the dot-operator, ‘.’ is used to join two or more strings.
    echo $z;     // This should print: I love PHP !
    echo "<br>";

     $z = $z . " Yes, " . $z . " Oh yes, " . $z;
     echo( $z); // This example shows how to join many strings using ‘.’
     echo "<br>";

     $z = str_replace( "love", "hate", $z); // replace a part of a string with another
     echo $z, "<br>";
if ( substr_count( $z, "hate") >= 2) {
    /* substr_count( ) counts no of times a sub-string
      occurs in a given string */
          echo "Oh no, why do you hate me so much ?", "<br>";
     }
   ?>

What you learnt:
1. Useful string functions: str_replace, substr_count.

Exercise: Modify the code above as follows: $x should store the abstract of a paper written
by your advisor (or your favorite professor). $y should be an array of keywords of the
paper. Your program should output how many times each keyword occurs in the abstract.


Step 3. User-defined functions and multi-dimensional arrays
In this example, you will learn:
     (i) How to define your own functions
     (ii) Note how to return values from your functions: these can be variables, arrays, etc.
     (iii) Learn how to define named constants (same as #define in C++)
     (iv) Learn some math functions in PHP
     (v) Learn how to use “printf” function for formatted output.

   <?php
    // We define a function to multiply a 1x2 vector with a 2x2 matrix
   function vect_mult_mat( $vec, $mat) {
     $out[0] = $vec[0] * $mat[0][0] + $vec[1] * $mat[1][0];
     $out[1] = $vec[0] * $mat[0][1] + $vec[1] * $mat[1][1];
     return $out;
   }

    // The define function is similar to #define in C++
    // PHP has all common math functions, e.g. sin, cos, …
   define ("PI", 3.1415926);
   $cos_theta = cos( PI/4.0);
   $sin_theta = sin( PI/4.0);
    // item-by-item definition of a multi-dimensional array
   $rot_matrix[0][0] = $cos_theta; $rot_matrix[0][1] = $sin_theta;
   $rot_matrix[1][0] = -1.0 * $sin_theta; $rot_matrix[1][1] = $cos_theta;
   $my_vector = array( 2.0, 2.0);
    // We call the function defined earlier; notice that it returns an array!
   $rotated_vector = vect_mult_mat( $my_vector, $rot_matrix);
   echo "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to
   [ $rotated_vector[0], $rotated_vector[1] ] <br>n";
// Notice how echo prints floating point numbers -- quite ugly!
    // For formatted output, it is better to use the printf function of PHP
   printf( "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ %4.2f,
   %4.2f ] <br>n", $rotated_vector[0], $rotated_vector[1] );
   ?>

What you learnt:
1. One way to define a multi-dimensional array. Such arrays will be very useful when you
need to handle data coming from a DB – since each DB table is similar to a 2D array.
2. One way to define and use your own functions in PHP; notice that our function worked
by passing the value of its arguments; PHP also allows you to pass references to arguments,
which is sometimes useful.
3. A simple use of the printf function; this function is quite useful in generating pretty
output.

Exercise: Modify the code above as follows. First create a multi-dimensional array called
$loans, with the data from the table below (no need to store the attribute names). Write a
function which takes a 2-dimensional array as input, and outputs an HTML table that looks
like the table below (namely, it prints the top row with the given attribute names, and then
the rows of the array). Your main PHP program should output sub-arrays from the input
array such that each sub-array has only the data for a particular loan (e.g. there will be an
array of three rows for L17). Call the print_table function once for each sub-array and
display the output via the web client.



  customer     loan_no amount      branch_name
 111-12-0000      L17      1000      Downtown
 222-12-0000      L23      2000       Redwood
 333-12-0000      L15      1500      Pennyridge
 444-00-0000      L93      500         Mianus
 666-12-0000      L17      1000      Downtown
 111-12-0000      L11      900       Round Hill
 999-12-0000      L17      1000      Downtown
 777-12-0000      L16      1300      Pennyridge




Step 4. Working with strings: Regular expressions.
When working with web-based applications and DB, you will often be processing data in the
form of strings of characters.
Regular expressions (RegExps) are a very powerful method to do pattern matching on
strings. Many string functions use RegExps.
<?php
       // Define a string
      $text = "Never let a fool kiss you, never let a kiss fool you";
      echo "Text is: $text <br>n";

       // Two ways to search for a constant string in a long string:
       // strstr( ), and preg_match( )
       // Notice how the ‘’ is used to escape the "-mark in the argument of echo.
      if ( strstr( $text, "fool") ) { echo "strstr: Found "fool" in text <br>n";}

      if ( preg_match( "/fool/", $text) ) { echo "preg_match: Found "fool" in text <br>n";}

       // preg_match_all( ) can be used for case-insensitive search,
       // and multiple matches
       // In the RegExp, the pattern to match is between the /…/
       // the ‘i’ at the end indicates that the match should be case-insensitive
      $no_of_hits = preg_match_all( "/never/i", $text, $matches);
      echo "preg_match_all: Found $no_of_hits instances of "never" in text; they were: ";
      for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
      echo "<br> n";

       // to catch all instances of ‘fool’ or ‘kiss’, use the ‘|’ in the RegExp
      $no_of_hits = preg_match_all( "/fool|kiss/", $text, $matches);
      echo "preg_match_all: Found $no_of_hits instances of "fool" or "kiss" in text; they
      were: ";
      for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
      echo "<br> n";
      ?>

What you learnt:
1. Regular expressions are in fact a very powerful concept; we only saw the simplest
RegExps. You will see many other uses in future labs – you can use RegExps to search for
very complicated and patterns.

Exercise: Write a CGI program that will receive the abstract of a paper submitted by a form
via a web client. Your CGI program should search for the following incorrectly spelt words
in the abstract. It should then return the same text to the web client, except that all the
incorrectly spelt words should be colored in red, and the corrected spelling is suggested in
brackets, in blue color.

List of incorrect spellings to check:
teh     the
Teh      The
acn      can
abotu about
actualyl actually

For example, if the input text is:
Teh quick brown fox acn jump over the lazy fox.
Then the output should be:
Teh [do you mean: The] quick brown fox acn [do you mean: can] jump over the lazy fox.


References:
1. HTML quick reference file.
2. PHP tutorials and function references: (from www.php.net)
3. PHP tutorial site: http://www.w3pop.com/learn/view/p/3/o/0/doc/php_ref_string/
4. Another PHP tutorial/reference: http://www.w3schools.com/PHP/php_ref_array.asp



Lab materials for IELM 511 prepared by WEI Xiangzhi, Dept of IELM, HKUST.

Contenu connexe

Tendances

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer. Haim Michael
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev AssistantDave Cross
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
Perl programming language
Perl programming languagePerl programming language
Perl programming languageElie Obeid
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating stringsNicole Ryan
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perlsana mateen
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Roy Zimmer
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 

Tendances (20)

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
Data types in php
Data types in phpData types in php
Data types in php
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Perl
PerlPerl
Perl
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
 
PHP
PHP PHP
PHP
 
Download It
Download ItDownload It
Download It
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 

En vedette

Jeni J2 Me Bab02 Memulai Pemrograman Mobile
Jeni J2 Me Bab02 Memulai Pemrograman MobileJeni J2 Me Bab02 Memulai Pemrograman Mobile
Jeni J2 Me Bab02 Memulai Pemrograman MobileIndividual Consultants
 
P Oral Ang T Dr
P Oral Ang T DrP Oral Ang T Dr
P Oral Ang T DrKaty
 
R3WiND MEDiA THRILLER OPENING IDEA'S
R3WiND MEDiA THRILLER OPENING IDEA'SR3WiND MEDiA THRILLER OPENING IDEA'S
R3WiND MEDiA THRILLER OPENING IDEA'SRahib
 
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek Pelc
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek PelcThe European Commitment to Wilderness - Report from Prague by Dr. Frantisek Pelc
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek PelcWILD Foundation
 
Jeni Intro1 Bab04 Dasar Dasar Pemrograman
Jeni Intro1 Bab04 Dasar Dasar PemrogramanJeni Intro1 Bab04 Dasar Dasar Pemrograman
Jeni Intro1 Bab04 Dasar Dasar PemrogramanIndividual Consultants
 
Magnifying Organic SEO via Infographics
Magnifying Organic SEO via InfographicsMagnifying Organic SEO via Infographics
Magnifying Organic SEO via Infographicsshuey03
 

En vedette (9)

Jeni Intro2 Bab12 Stream Io Lanjut
Jeni Intro2 Bab12 Stream Io LanjutJeni Intro2 Bab12 Stream Io Lanjut
Jeni Intro2 Bab12 Stream Io Lanjut
 
Jeni J2 Me Bab02 Memulai Pemrograman Mobile
Jeni J2 Me Bab02 Memulai Pemrograman MobileJeni J2 Me Bab02 Memulai Pemrograman Mobile
Jeni J2 Me Bab02 Memulai Pemrograman Mobile
 
P Oral Ang T Dr
P Oral Ang T DrP Oral Ang T Dr
P Oral Ang T Dr
 
R3WiND MEDiA THRILLER OPENING IDEA'S
R3WiND MEDiA THRILLER OPENING IDEA'SR3WiND MEDiA THRILLER OPENING IDEA'S
R3WiND MEDiA THRILLER OPENING IDEA'S
 
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek Pelc
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek PelcThe European Commitment to Wilderness - Report from Prague by Dr. Frantisek Pelc
The European Commitment to Wilderness - Report from Prague by Dr. Frantisek Pelc
 
Presentatie Henk van Erp, Twinfield Masterclass
Presentatie Henk van Erp, Twinfield MasterclassPresentatie Henk van Erp, Twinfield Masterclass
Presentatie Henk van Erp, Twinfield Masterclass
 
Jeni Intro1 Bab04 Dasar Dasar Pemrograman
Jeni Intro1 Bab04 Dasar Dasar PemrogramanJeni Intro1 Bab04 Dasar Dasar Pemrograman
Jeni Intro1 Bab04 Dasar Dasar Pemrograman
 
Ad-journal
Ad-journalAd-journal
Ad-journal
 
Magnifying Organic SEO via Infographics
Magnifying Organic SEO via InfographicsMagnifying Organic SEO via Infographics
Magnifying Organic SEO via Infographics
 

Similaire à lab4_php

Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical HackingBCET
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshotsrichambra
 
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP TechnologyFnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technologyfntsofttech
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questionssekar c
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questionssubash01
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 

Similaire à lab4_php (20)

Php
PhpPhp
Php
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
 
Learn php with PSK
Learn php with PSKLearn php with PSK
Learn php with PSK
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP TechnologyFnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Php
PhpPhp
Php
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

lab4_php

  • 1. IELM 511 Information Systems Design Lab 4: Fundamental PHP functions: II This lab will use a few more exercises to build up your experience with PHP scripts. In subsequent labs, you will write CGI programs that connect to a Database and exchange information with the DB, returning the feedback to the web client. Since most data in DBs is stored in tables, and cell entries are mostly strings, therefore the two data types we need to handle in our programs are (multi-dimensional) arrays, and strings. In this lab, we will build up some more experience with these, working on basic language skills for PHP. Objectives of this lab Gain some familiarity with the following concepts: (a) Basic data structures in PHP: multi-dimension arrays (b) Program flow control: functions (c) Regular expressions and string parsing. As before, if you need to look up the syntax of some operator/function in PHP, you can use a good online PHP tutorial site, such as: http://www.w3schools.com/PHP/ The lab tasks are below. Step 1. [Re-use from past lab]. Make a simple web-form (file: run_cgi.html) with one input field and one text-box field (use or modify the file given to you in the lab materials). Step 2. Try the following code using phpDesigner, and then modify it as instructed. In most php program, we work with strings; common examples: - If you read a line of data from a file, you will read it as a string of characters; - The most common data types stored in a Database are strings. PHP provides several useful string functions and operators. <?php $x = "I love"; // declare a variable, $x, and define its value(of type string) $y = " PHP !"; // declare and define variable $y $z = $x . $y; // the dot-operator, ‘.’ is used to join two or more strings. echo $z; // This should print: I love PHP ! echo "<br>"; $z = $z . " Yes, " . $z . " Oh yes, " . $z; echo( $z); // This example shows how to join many strings using ‘.’ echo "<br>"; $z = str_replace( "love", "hate", $z); // replace a part of a string with another echo $z, "<br>";
  • 2. if ( substr_count( $z, "hate") >= 2) { /* substr_count( ) counts no of times a sub-string occurs in a given string */ echo "Oh no, why do you hate me so much ?", "<br>"; } ?> What you learnt: 1. Useful string functions: str_replace, substr_count. Exercise: Modify the code above as follows: $x should store the abstract of a paper written by your advisor (or your favorite professor). $y should be an array of keywords of the paper. Your program should output how many times each keyword occurs in the abstract. Step 3. User-defined functions and multi-dimensional arrays In this example, you will learn: (i) How to define your own functions (ii) Note how to return values from your functions: these can be variables, arrays, etc. (iii) Learn how to define named constants (same as #define in C++) (iv) Learn some math functions in PHP (v) Learn how to use “printf” function for formatted output. <?php // We define a function to multiply a 1x2 vector with a 2x2 matrix function vect_mult_mat( $vec, $mat) { $out[0] = $vec[0] * $mat[0][0] + $vec[1] * $mat[1][0]; $out[1] = $vec[0] * $mat[0][1] + $vec[1] * $mat[1][1]; return $out; } // The define function is similar to #define in C++ // PHP has all common math functions, e.g. sin, cos, … define ("PI", 3.1415926); $cos_theta = cos( PI/4.0); $sin_theta = sin( PI/4.0); // item-by-item definition of a multi-dimensional array $rot_matrix[0][0] = $cos_theta; $rot_matrix[0][1] = $sin_theta; $rot_matrix[1][0] = -1.0 * $sin_theta; $rot_matrix[1][1] = $cos_theta; $my_vector = array( 2.0, 2.0); // We call the function defined earlier; notice that it returns an array! $rotated_vector = vect_mult_mat( $my_vector, $rot_matrix); echo "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ $rotated_vector[0], $rotated_vector[1] ] <br>n";
  • 3. // Notice how echo prints floating point numbers -- quite ugly! // For formatted output, it is better to use the printf function of PHP printf( "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ %4.2f, %4.2f ] <br>n", $rotated_vector[0], $rotated_vector[1] ); ?> What you learnt: 1. One way to define a multi-dimensional array. Such arrays will be very useful when you need to handle data coming from a DB – since each DB table is similar to a 2D array. 2. One way to define and use your own functions in PHP; notice that our function worked by passing the value of its arguments; PHP also allows you to pass references to arguments, which is sometimes useful. 3. A simple use of the printf function; this function is quite useful in generating pretty output. Exercise: Modify the code above as follows. First create a multi-dimensional array called $loans, with the data from the table below (no need to store the attribute names). Write a function which takes a 2-dimensional array as input, and outputs an HTML table that looks like the table below (namely, it prints the top row with the given attribute names, and then the rows of the array). Your main PHP program should output sub-arrays from the input array such that each sub-array has only the data for a particular loan (e.g. there will be an array of three rows for L17). Call the print_table function once for each sub-array and display the output via the web client. customer loan_no amount branch_name 111-12-0000 L17 1000 Downtown 222-12-0000 L23 2000 Redwood 333-12-0000 L15 1500 Pennyridge 444-00-0000 L93 500 Mianus 666-12-0000 L17 1000 Downtown 111-12-0000 L11 900 Round Hill 999-12-0000 L17 1000 Downtown 777-12-0000 L16 1300 Pennyridge Step 4. Working with strings: Regular expressions. When working with web-based applications and DB, you will often be processing data in the form of strings of characters. Regular expressions (RegExps) are a very powerful method to do pattern matching on strings. Many string functions use RegExps.
  • 4. <?php // Define a string $text = "Never let a fool kiss you, never let a kiss fool you"; echo "Text is: $text <br>n"; // Two ways to search for a constant string in a long string: // strstr( ), and preg_match( ) // Notice how the ‘’ is used to escape the "-mark in the argument of echo. if ( strstr( $text, "fool") ) { echo "strstr: Found "fool" in text <br>n";} if ( preg_match( "/fool/", $text) ) { echo "preg_match: Found "fool" in text <br>n";} // preg_match_all( ) can be used for case-insensitive search, // and multiple matches // In the RegExp, the pattern to match is between the /…/ // the ‘i’ at the end indicates that the match should be case-insensitive $no_of_hits = preg_match_all( "/never/i", $text, $matches); echo "preg_match_all: Found $no_of_hits instances of "never" in text; they were: "; for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; } echo "<br> n"; // to catch all instances of ‘fool’ or ‘kiss’, use the ‘|’ in the RegExp $no_of_hits = preg_match_all( "/fool|kiss/", $text, $matches); echo "preg_match_all: Found $no_of_hits instances of "fool" or "kiss" in text; they were: "; for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; } echo "<br> n"; ?> What you learnt: 1. Regular expressions are in fact a very powerful concept; we only saw the simplest RegExps. You will see many other uses in future labs – you can use RegExps to search for very complicated and patterns. Exercise: Write a CGI program that will receive the abstract of a paper submitted by a form via a web client. Your CGI program should search for the following incorrectly spelt words in the abstract. It should then return the same text to the web client, except that all the incorrectly spelt words should be colored in red, and the corrected spelling is suggested in brackets, in blue color. List of incorrect spellings to check: teh the Teh The acn can
  • 5. abotu about actualyl actually For example, if the input text is: Teh quick brown fox acn jump over the lazy fox. Then the output should be: Teh [do you mean: The] quick brown fox acn [do you mean: can] jump over the lazy fox. References: 1. HTML quick reference file. 2. PHP tutorials and function references: (from www.php.net) 3. PHP tutorial site: http://www.w3pop.com/learn/view/p/3/o/0/doc/php_ref_string/ 4. Another PHP tutorial/reference: http://www.w3schools.com/PHP/php_ref_array.asp Lab materials for IELM 511 prepared by WEI Xiangzhi, Dept of IELM, HKUST.