Lecture 13 Introduction to PHP

Document Sample
Lecture 13 Introduction to PHP Powered By Docstoc
					                                                                            3/11/2010




Lecture 13:

Introduction to PHP

Rory Duggan
rory.duggan@nuigalway.ie
http://danu.it.nuigalway.ie/rduggan

                                         CT532/CT870 Internet Programming




Housekeeping

• Course Website - Lecture 13 Added
• Labwork 5/6 - Final Extension
   – Due: 5pm Tuesday 16th March
          p
• ASP Example Website
   – Feedback Form now validates
   – Table sort field now works
      • Change data type from TEXT to VARCHAR
• .shtml SSI don’t work on Lugh2
   – ASP/PHP includes do
                                         CT532/CT870 Internet Programming




Rescheduled Lectures

• 4 hours to reschedule
• 2.5 weeks of term left
• Proposing:
                         ( p )
   – Two 2 hour sessions (5-7pm):
      • 2 hours next week
      • 2 hours following week
   – Dates/times to be confirmed (hopefully tomorrow)
      • Notified by email
      • Course website will be updated
                                         CT532/CT870 Internet Programming




                                                                                   1
                                                                            3/11/2010




PHP: Hypertext Preprocessor



Alternative to Microsoft’s Active Server Pages



                                         CT532/CT870 Internet Programming




PHP

• Server side scripting language
  – Similar functionality to ASP
  – Scripts are executed on the server
      • Like ASP, scripts are hidden from client browser
• Open source
  – Free to download, use and contribute towards
• Cross platform compatible
  – Operating systems, databases, etc


                                         CT532/CT870 Internet Programming




PHP Pages

• Pages using PHP must use .php extension
  – index.php, mypage.php, etc
• Normal HTML pages
  – May contain scripts
• Scripts contained within script code tags
  – Like with ASP
• PHP scripts can contain HTML tags
  – Like with ASP


                                         CT532/CT870 Internet Programming




                                                                                   2
                                                                          3/11/2010




PHP Code Tags

• PHP scripts must be contained within code tags
• Longhand:
  <?php
    Code goes here
  ?>
• Shorthand:
  <?
    Code goes here
  ?>
                                       CT532/CT870 Internet Programming




PHP Syntax

• PHP is very similar to C
• Braces used to denote code blocks               { }
• Lines must end with semi-colon                  ;
• Comments
  – Single line with double forward slash         //
  – Multiple lines between /* and */
       /* All of this code block
          is commented */

                                       CT532/CT870 Internet Programming




First PHP Page - info.php

• PHP Information Page
  – Server’s PHP Version
  – Server settings
  – etc


  <?php
  phpinfo();
  ?>


                                       CT532/CT870 Internet Programming




                                                                                 3
                                                                          3/11/2010




Outputting to User

• ASP used Response.Write() object
• PHP uses echo or print
   – Functionally the same, more common to use echo


   <?php
   echo(“This is a string being outputted”);
   print (“This is also a string being
     outputted”);
   ?>

                                       CT532/CT870 Internet Programming




Escaping Characters

• Certain special characters are reserved in PHP
   – Semi-colon, single and double quotes, backslash
• These characters must be “escaped”
   – Enter a backslash before the special character
        • Backslashes must be escaped too!
• Important for HTML attributes being quoted!

• Consider the following string:
  the next word is "quoted" for effect

                                       CT532/CT870 Internet Programming




Escaping Characters

echo ("the next word is "quoted" for effect");


Output:       the next word is
  NB:         Code following will likely break


echo ("the next word is \"quoted\" for effect");


Output:       the next word is “quoted” for effect

                                       CT532/CT870 Internet Programming




                                                                                 4
                                                                         3/11/2010




Escaping Characters - Continued

• echo("The path is C:\\Home\\Something");
  Outputs: The path is C:\Home\Something
• echo("Semicolons (\;) must also be
  escaped");
  escaped )
  Outputs: Semicolons (;) must also be escaped
• echo("<p class=\"name\">Styled text
  here</p>")
  Outputs: Styled text here (as per CSS Style)

                                      CT532/CT870 Internet Programming




PHP Variables

• All PHP Variables preceded by $
• PHP is a loosely typed language
• Do not need to be declared before being used

  ASP                         PHP
  <%                          <?php
  dim varname                 $varname = value;
  varname=value               echo($varname);
  Response.Write(varname)     ?>
  %>

                                      CT532/CT870 Internet Programming




Outputting Variables

• Variables can be outputted within string literal
   – Since PHP is loosely typed
• Three variables:
  $var1=3;
  $var2=5;
  $var3=6;
  echo(“The variables are $var1, $var2,
     $var3”);
• Outputs: The variables are 3, 5, 6
                                      CT532/CT870 Internet Programming




                                                                                5
                                                                                3/11/2010




Simple Example

<?php
$num1=5;
$num2=15;
$num3=$num2-$num1;
echo(“$num2 minus $num1 equals $num3”);
?>
  Output:
                  15 minus 5 equals 10

                                             CT532/CT870 Internet Programming




Variables Outside Literal

• Can move variables outside string literal
     – Sometimes needed if variable is a function
         • Not directly assigned to a variable (later)
• Separate variables from the string with dot ( . )
  echo("First string" . $variable . "second string");

Previous example:
  echo($num1 . " minus " . $num2 . " equals " .
     $num3);

                                             CT532/CT870 Internet Programming




Arrays

• Declare an array with the array keyword
     $num=array(1,2,3);
• Output the array by index number (0 is first)
     echo (“The numbers are: $num[0], $num[1], $num[2]”);
• Easiest to use a For loop
     for ($i=0; $i<3; $i++)
     {
     echo(“Number $i is: $num[$i]”);
     }
                                             CT532/CT870 Internet Programming




                                                                                       6
                                                                 3/11/2010




Control / Looping



Same as with C



                              CT532/CT870 Internet Programming




PHP Control/Looping

• Same syntax as with C
    – Braces and semicolons
• Conditional Statements
    – If..Else
    – Switch
• Looping
    – While Loops
    – For Loops


                              CT532/CT870 Internet Programming




If ... Else

if ($variable1==$variable2)
{
    // Code goes here
}
else
{
    // Other code goes here
}



                              CT532/CT870 Internet Programming




                                                                        7
                                                                              3/11/2010




Switch

switch($variable)
{                           case 3:
case 1:                     {
{                               // Code if variable=3
    // Code if variable=1            ;
                                break;
    break;                  }
}                           default:
case 2:                         // Otherwise
    // Code if variable=2       break;
    break;                  }
}
                                           CT532/CT870 Internet Programming




While Loop

$i=0;                                    i is now 0
                                         i is now 1
while ($i<10)                            i is now 2
{                                        i is now 3
    // Code goes here                    i is now 4
                                         i is now 5
    echo(“i is now $i”);
                                         i is now 6
    $i++;                                i is now 7
}                                        i is now 8
                                         i is now 9


                                           CT532/CT870 Internet Programming




For Loop

                                         i is now 0
                                         i is now 1
                                         i is now 2
for ($i=0; $i<10; $i++)                  i is now 3
{                                        i is now 4
                                         i is now 5
    echo(“i is now $i”);
                                         i is now 6
}                                        i is now 7
                                         i is now 8
                                         i is now 9


                                           CT532/CT870 Internet Programming




                                                                                     8
                                                                            3/11/2010




Includes and Requires



Server Side Includes in PHP



                                         CT532/CT870 Internet Programming




Includes

• Used to “include” code from another file
   – Similar in function to Server Side Includes previously
   – e.g. Common Navigation File
• Code below will include the code in “file.php”
   – Code added to the page calling the file
  <?php
  include(“file.php”);
  ?>


                                         CT532/CT870 Internet Programming




Requires

• Also “includes” code from another file
• Includes give an error if file cannot be found
   – Warning appears in the area of the page it was called
   – Rest of script continues
• Requires must be included or the page breaks
   – Fatal Error appears and the script stops
  <?php
  require(“file.php”);
  ?>
                                         CT532/CT870 Internet Programming




                                                                                   9
                                                                          3/11/2010




PHP and Forms



Flow of Information



                                       CT532/CT870 Internet Programming




Flow of Information - Like ASP

• PHP uses forms to accept input from user
  – Normal HTML forms
     • Like with ASP
• Forms have an Action Script containing PHP
  – Fields passed with GET or POST methods
     • Like with ASP
• Action Script carries out necessary code
  – Simple calculations, DB interaction, etc
     • Like with ASP
                                       CT532/CT870 Internet Programming




GET and POST in PHP

• GET
  $var=$_GET[‘fieldname’];

• POST
  $var=$_POST[‘fieldname’];

• Either single or double quotes can be used

                                       CT532/CT870 Internet Programming




                                                                                10
                                                                       3/11/2010




Simple Form Example

• Form to accept two numbers from a user
• Action Script carries out calculations
• Results outputted to the user

                                            “num1”
                                            “num2”




                                    CT532/CT870 Internet Programming




Action Script: numbers.php

<html><head></head><body>
<?php
$num1=$_POST['num1'];
$num2=$_POST['num2'];


$add=$num1+$num2;
$sub=$num1-$num2;
$mult=$num1*$num2;
$div=$num1/$num2;

                                    CT532/CT870 Internet Programming




Action Script: numbers.php

echo("<p>The two numbers were: <b>$num1</b>
  and <b>$num2</b></p>");
echo("<p>Added:     $num1 plus $num2 =
  $add</p>");
echo("<p>Subtracted:
       p                  $num1 minus $num2 =
  $sub</p>");
echo("<p>Multiplied:      $num1 times $num2 =
  $mult</p>");
echo("<p>Divided:     $num1 divided by $num2 =
  $div</p>");
?></body></html>
                                    CT532/CT870 Internet Programming




                                                                             11
                                                                          3/11/2010




Output of numbers.php




                                       CT532/CT870 Internet Programming




MySQL Database



Alternative to Microsoft’s SQL Server



                                       CT532/CT870 Internet Programming




MySQL Database

• Comparable to MS SQL Server
• Commonly used with PHP
• Open Source
• Cross platform compatible
  – OS:            Linux, Windows, Mac, etc
  – Scripts:       PHP and ASP

     • FAQ for connecting ASP to MySQL available at:
       http://lugh2.it.nuigalway.ie/samples

                                       CT532/CT870 Internet Programming




                                                                                12
                                                                      3/11/2010




LAMP Method

• Linux
  – Server Operating System
• Apache
  – HTTP Server Application
• MySQL
  – Database
• PHP
  – Scripting Language


                                   CT532/CT870 Internet Programming




Cross platform compatible

• PHP and MySQL no longer Linux specific
• Other platforms can run PHP
  – Windows, Mac
     • Lugh2 has PHP installed
• No longer simply LAMP
  – WAMP           Windows Apache MySQL PHP
  – MAMP           Macintosh Apache MySQL PHP
  – etc


                                   CT532/CT870 Internet Programming




Most Common PHP/MySQL Commands

• Open a Connection:
  mysql_connect(“server”,”username”,”pass”);
• Select a Database:
  mysql_select_db( dbname );
  mysql select db(“dbname”);
• Execute a Query:
  mysql_query(“sqlstring”);
• Close a Conenction:
  mysql_close();

                                   CT532/CT870 Internet Programming




                                                                            13
                                                                             3/11/2010




PHP and Lugh2

• PHP installed on Lugh2
  – No need to create new web space for PHP work
• Must use longhand script tags
  <?php ... ?>            Will work on danu2
  <? ... ?>               Won’t work on lugh2!
• Scripts on Lugh2 can connect to MySQL DB
  – MySQL DB created on Linux Danu2 server
  – Created through IT Intranet
     • Same process as creating SQL Server DB
                                          CT532/CT870 Internet Programming




phpMyAdmin

• Graphical interface for managing a MySQL DB
  – http://danu2.it.nuigalway.ie/phpmyadmin
  – Must have MySQL DB setup
     • Login with details sent in email
• Create/Edit/Delete
  – Tables
  – Data
  – etc
• Next Labwork will involve using this
                                          CT532/CT870 Internet Programming




PHP Example:
Student Records System



Simple two table database



                                          CT532/CT870 Internet Programming




                                                                                   14
                                                                          3/11/2010




Student Records System

• Simple system to hold information on:
  – Courses available
  – Registered students
• Database will contain two tables
  – courses
     • To hold course information
  – students
     • To hold student information


                                       CT532/CT870 Internet Programming




Student Records System

• Courses:
  – courseid      int           Unique course number
  – name          varchar       Name of course
  – level         int           NFQ Level (8,9,10)
  – duration      int           Number of years
• Courseid is primary key
  – Set to Auto_Increment
     • i.e. AutoNumber or Identity Specification


                                       CT532/CT870 Internet Programming




Students Table

• Students:
  – studentid     int           Unique student number
  – firstname     varchar       Student’s first name
  – surname       varchar       Student’s surname
  – phone         varchar       Phone number
  – email         varchar       Email address
  – dob           varchar       Date of Birth
  – courseid      int           ID number of course
                                student is enrolled in (FK)

                                       CT532/CT870 Internet Programming




                                                                                15
                                                                          3/11/2010




Functions of Records System

• Addition of new entries
   – INSERT query from form elements
• Retrieval of existing records
   – SELECT query
• Edit of existing records
   – SELECT query
      • to retrieve existing record
   – UPDATE query
      • to insert new data
                                       CT532/CT870 Internet Programming




CT532/CT870
Internet Programming



Rory Duggan
rory.duggan@nuigalway.ie
http://danu.it.nuigalway.ie/rduggan

                                       CT532/CT870 Internet Programming




                                                                                16

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:13
posted:11/28/2011
language:English
pages:16