+ All Categories
Home > Documents > Week 4- Intro to PHP

Week 4- Intro to PHP

Date post: 07-Aug-2018
Category:
Upload: jsgumban
View: 250 times
Download: 1 times
Share this document with a friend

of 61

Transcript
  • 8/21/2019 Week 4- Intro to PHP

    1/61

    Important!

    Please use the following site to test yourPhp codes (as of this moment).

    http://codepad.org/

    ->and select Php -> write the codes on the text area

    provided , the click submit

    http://codepad.org/http://codepad.org/
  • 8/21/2019 Week 4- Intro to PHP

    2/61

  • 8/21/2019 Week 4- Intro to PHP

    3/61

  • 8/21/2019 Week 4- Intro to PHP

    4/61

    Learning PHP

  • 8/21/2019 Week 4- Intro to PHP

    5/61

    Drawbacks of HTML

    HTML only allows for creating static webpages, or web pages that do not change

    It does not, by itself, provide a way for

    users to interact

  • 8/21/2019 Week 4- Intro to PHP

    6/61

    Learning PHP

    PHP is a powerful server-side scripting languagefor creating dynamic and interactive websites.

    PHP is the widely-used and free.

    PHP is perfectly suited for Web developmentand can be embedded directly into the HTMLcode.

    The PHP syntax is very similar to C.

    PHP is often used together with Apache (webserver) on various operating systems.

  • 8/21/2019 Week 4- Intro to PHP

    7/61

    Introduction to PHP

    A PHP file may contain text, HTML tagsand scripts.

    Scripts in a PHP file are executed on the

    server.

  • 8/21/2019 Week 4- Intro to PHP

    8/61

    How PHP Works

    When a user navigates in her browser to a page that ends with a .php extension, the request is sent to a webserver, which directs the request to the PHP interpreter.

    As shown in the diagram above, the PHP interpreter processes the page, communicating with file systems,databases, and email servers as necessary, and then delivers a web page to the web server to return to thebrowser.

  • 8/21/2019 Week 4- Intro to PHP

    9/61

    What You Should Already Know

    Before you continue you should have abasic understanding of the following:

    HTML / XHTML

    Some scripting knowledge

  • 8/21/2019 Week 4- Intro to PHP

    10/61

    What is PHP?

    PHP standsfor PHP: Hypertext Preprocessor

    PHP is a server-side scripting language

    PHP scripts are executed on the server PHP supports many databases (MySQL,

    etc.)

    PHP is an open source software PHP is free to download and use

  • 8/21/2019 Week 4- Intro to PHP

    11/61

    What is a PHP File?

    PHP files may contain text, HTML tagsand scripts

    PHP files are returned to the browser as

    plain HTML PHP files have a file extension of ".php",

    ".php3", or ".phtml"

  • 8/21/2019 Week 4- Intro to PHP

    12/61

    Why PHP?

    PHP runs on different platforms (Windows,Linux, Unix, etc.)

    PHP is compatible with almost all servers

    used today (Apache, etc.) PHP is FREE to download from the official

    PHP resource:www.php.net

    PHP is easy to learn and runs efficientlyon the server side

    http://www.php.net/http://www.php.net/http://www.php.net/
  • 8/21/2019 Week 4- Intro to PHP

    13/61

    Where to Start?

    Install an Apacheserver on a Windows orLinux machine

    Install PHPon a Windows or Linux

    machine Install MySQLon a Windows or Linux

    machine

    Or

    you can install XAMMP

  • 8/21/2019 Week 4- Intro to PHP

    14/61

    Setup and installation of XAMPP

    Download XAMPP for your operatingsystem from:

    www.apachefriends.org/en/xampp.html

    If you are using Windows, just run theinstaller (disable proxies)

    If you are using Linux, untar the package

    to the appropriate directory and run:/opt/lampp/lampp start

  • 8/21/2019 Week 4- Intro to PHP

    15/61

    How do you make a PHP program?

    The process is identical to how you make anHTML page, even if you use a visual tool likeDreamweaver

    Create an HTML page in any editor (even

    notepad will work)

    Add PHP code to the page

    Save in your webserver directory

    opt\lampp\htdocsin Linux C:\Program Files\xampp\htdocsin Windows

    View in any web browser

  • 8/21/2019 Week 4- Intro to PHP

    16/61

    PHP Syntax

  • 8/21/2019 Week 4- Intro to PHP

    17/61

    PHP Syntax

    You cannot view the PHP source code byselecting "View source" in the browser -you will only see the output from the PHP

    file, which is plain HTML. This is because the scripts are executed

    on the server before the result is sent back

    to the browser.

  • 8/21/2019 Week 4- Intro to PHP

    18/61

    Basic PHP Syntax

    A PHP scripting block always startswith . A PHP scriptingblock can be placed anywhere in the document.

  • 8/21/2019 Week 4- Intro to PHP

    19/61

    Basic PHP Syntax

    A PHP file normally contains HTML

    tags, just like an HTML file, and somePHP scripting code.

    We have an example of a simple PHPscript which sends the text "HelloWorld" to the browser.

    Each code line in PHP must end with asemicolon.

    The semicolon is a separator and isused to distinguish one set ofinstructions from another.

    There are two basic statements tooutput text with PHP: echoand print.

    In the example above we have usedthe echo statement to output the text"Hello World".

  • 8/21/2019 Week 4- Intro to PHP

    20/61

    Comments in PHP

    In PHP, we use // tomake a single-linecomment or /* and */to make a large

    comment block.

  • 8/21/2019 Week 4- Intro to PHP

    21/61

    Hands-on 1: Hel lo world Please open a text editor, Notepad if you are in windows

    Type the follow into the text editor:

    Me and PHP

    Save the file as handson1.php(add quotes if you areusing Windows)

    Open a web browser

    Type http://localhost/handson1.php and hit

  • 8/21/2019 Week 4- Intro to PHP

    22/61

    Expected Output:

  • 8/21/2019 Week 4- Intro to PHP

    23/61

    PHP Variables

    Variables are used for storing values,such as numbers, strings or function

    results, so that they can be used manytimes in a script.

  • 8/21/2019 Week 4- Intro to PHP

    24/61

    Variables in PHP

    All variables in PHPstart with a $ signsymbol. Variablesmay contain strings,

    numbers, or arrays. In the example, the

    PHP script assignsthe string "HelloWorld" to a variablecalled $txt.

  • 8/21/2019 Week 4- Intro to PHP

    25/61

    Variables in PHP

    To concatenate twoor more variablestogether, use the dot(.) operator.

    The output of thescript will be: "HelloWorld 1234".

  • 8/21/2019 Week 4- Intro to PHP

    26/61

    Variable Naming Rules

    A variable name must start with a $ sign symboland then followed by a letter or an underscore"_"

    A variable name can only contain alpha-numeric

    characters and underscores (a-Z, 0-9, and _ )

    A variable name should not contain spaces.

    If a variable name should be more than one

    word, it should be separated with underscore($my_string), or with capitalization ($myString)

    H d 2

  • 8/21/2019 Week 4- Intro to PHP

    27/61

    Hands -on 2:

    Exper iment ing w ith var iables

    Create a PHP program with variable namedtest (remember the dollar sign). Then do thefollowing:

    a. store the number 35 to test and print the

    result;

    b. add 10.0000 to test and print the result;

    c. subtract 5.123123 from test and print it out;

    d. store the character string happy to behere to test and print;

    e. add 10.0000 to the variable test and print.

    Save it as handson2.php, and demonstrate it.

  • 8/21/2019 Week 4- Intro to PHP

    28/61

    PHP Operators

    Operators are used to operate onvalues.

    This section lists the different operatorsused in PHP.

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    29/61

    Arithmetic OperatorsOperator Description Example Result

    + Addition x=2x+2

    4

    - Subtraction x=2

    5-x

    3

    * Multiplication x=4

    x*5

    20

    / Division 15/5

    5/2

    3

    2.5

    % Modulus (division

    remainder)

    5%2

    10%8

    10%2

    1

    2

    0++ Increment x=5

    x++

    x=6

    -- Decrement x=5

    x--

    x=4

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    30/61

    Assignment Operators

    Operator Example Is The Same As

    = x=y x=y

    += x+=y x=x+y

    -= x-=y x=x-y

    *= x*=y x=x*y

    /= x/=y x=x/y

    %= x%=y x=x%y

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    31/61

    Comparison Operators

    Operator Description Example

    == is equal to 5==8 returns

    false

    != is not equal 5!=8 returns

    true

    > is greater than 5>8 returns

    false

    < is less than 5= is greater thanor equal to

    5>=8 returnsfalse

  • 8/21/2019 Week 4- Intro to PHP

    32/61

    Logical Operators

    Operator Description Example

    && and x=6

    y=3

    (x < 10 && y >

    1) returns

    true|| or x=6

    y=3

    (x==5 || y==5)

    returns false

    ! not x=6

    y=3

    !(x==y) returns

    true

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    33/61

    Conditional Statements

    Very often when you write code, you want toperform different actions for different decisions.

    You can use conditional statements in your codeto do this.

    if...else statement- use this statement if youwant to execute a set of code when a conditionis true and another if the condition is not true

    elseif statement- is used with the if...elsestatement to execute a set of code if oneofseveral condition are true

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    34/61

    The If...Else Statement

    Example

    The following examplewill output "Have a niceweekend!" if the currentday is Friday, otherwise it

    will output "Have a niceday!":

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    35/61

    The If...Else Statement

    If more than one line should beexecuted if a condition istrue/false, the lines should beenclosed within curly braces:

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    36/61

    The ElseIf Statement

    Example

    The following example willoutput "Have a nice weekend!"if the current day is Friday, and"Have a nice Sunday!" if thecurrent day is Sunday.

    Otherwise it will output "Have anice day!":

  • 8/21/2019 Week 4- Intro to PHP

    37/61

    PHP Switch Statement

    Example

    This is how it works: A single expression (most

    often a variable) is evaluatedonce

    The value of the expression iscompared with the values foreach case in the structure

    If there is a match, the codeassociated with that case isexecuted

    After a code isexecuted, break is used to stop

    the code from running into thenext case

    The default statement is usedif none of the cases are true

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    38/61

    PHP Looping

    Looping statements in PHP are

    used to execute the same block ofcode a specified number of times.

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    39/61

    Looping

    Very often when you write code, you want the sameblock of code to run a number of times. You can uselooping statements in your code to perform this.

    In PHP we have the following looping statements: while - loops through a block of code if and as long as a

    specified condition is true do...while- loops through a block of code once, and then

    repeats the loop as long as a special condition is true

    for - loops through a block of code a specified number of times

    foreach - loops through a block of code for each element in an

    array

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    40/61

    The while Statement

    Example

    The following example demonstrates a loop that will continue to run as long asthe variable i is less than, or equal to 5. i will increase by 1 each time theloop runs:

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    41/61

    The do...while Statement

    Example

    The following example will increment the value of i at least once, and it willcontinue incrementing the variable i as long as it has a value of less than 5:

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    42/61

    The for Statement

    Example

    The following example prints the text "Hello World!" five times:

    SameWith

    C

  • 8/21/2019 Week 4- Intro to PHP

    43/61

    Hands-on 3: Loop

    Write a PHP program and create a variablenamed $age. Using control structures, test $age.

    a. If $age is less than 18, it should print novote.

    b. If $age is greater than or equal to 18, itshould print vote.

    c. Using a loop of your choice, make the

    program print happy birthday $age times (so if $age is 15, it will print 15 times)

    Save it as handson3.php, and demonstrate it.

  • 8/21/2019 Week 4- Intro to PHP

    44/61

    PHP Arrays

    An array can store one or more

    values in a single variable name.

  • 8/21/2019 Week 4- Intro to PHP

    45/61

    What is an array?

    When working with PHP, sooner or later, youmight want to create many similar variables.

    Instead of having many similar variables, youcan store the data as elements in an array.

    Each element in the array has its own ID so thatit can be easily accessed.

    There are three different kind of arrays: Numeric array- An array with a numeric ID key Associative array- An array where each ID key

    is associated with a value Multidimensional array- An array containing

    one or more arrays

    N i A

  • 8/21/2019 Week 4- Intro to PHP

    46/61

    Numeric ArraysA numeric array stores each element with a numeric ID key.There are different ways to create a numeric array.

    Example 1In this example the ID key is automatically assigned:

    $names = array("Peter","Quagmire","Joe");

    Example 2In this example we assign the ID key manually:

    $names[0] = "Peter";$names[1] = "Quagmire";$names[2] = "Joe";

    The ID keys can be used in a script:

  • 8/21/2019 Week 4- Intro to PHP

    47/61

    Associative ArraysAn associative array, each ID key is associated with a value.With associative arrays we can use the values as keys and assign values to them.

    Example 1In this example we use an array to assign ages to the different persons:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

    Example 2This example is the same as example 1, but shows a different way of creating the array:

    $ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";

    The ID keys can be used in a script:

    The code above will output:Peter is 32 years old.

    M ltidi i l A

  • 8/21/2019 Week 4- Intro to PHP

    48/61

    Multidimensional Arrays

    In a multidimensional array, each element in the main array can also

    be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with

    automatically assigned ID keys:

    $families = array("Griffin"=>array("Peter","Lois",Megan"),"Quagmire"=>array("Glenn"),"Brown"=>array("Cleveland","Loretta","Junior")

    );

    echo value is.$families[Brown][1];

    M ltidi i l A

  • 8/21/2019 Week 4- Intro to PHP

    49/61

    Multidimensional Arrays

    The array above would look like this if written to the output:

    Array([Griffin] => Array([0] => Peter[1] => Lois[2] => Megan

    )[Quagmire] => Array([0] => Glenn)

    [Brown] => Array(

    [0] => Cleveland[1] => Loretta[2] => Junior)

    )

    Th f h St t t

  • 8/21/2019 Week 4- Intro to PHP

    50/61

    The foreach Statement

    The foreach statement is

    used to loop through arrays. For every loop, the value of

    the current array element isassigned to $value (and thearray pointer is moved by

    one) - so on the next loop,you'll be looking at the nextelement.

    Example

    The following exampledemonstrates a loop that willprint the values of the givenarray.

    H d 4 A

  • 8/21/2019 Week 4- Intro to PHP

    51/61

    Hands-on 4: Array

    Write a PHP program and create an arrayof 10 integers named $array_of_scores.Using control structures, do the following:

    a. Print all the integers. b. Get the sum of all the integers and print;

    c. Among the integers, count the number

    of odd and even integers, then, print;

    Save it as handson4.php, and demonstrate it.

  • 8/21/2019 Week 4- Intro to PHP

    52/61

    PHP Functions

    The real power of PHP comes from itsfunctions.

    In PHP - there are more than 700 built-in functions available.

    C t PHP F ti

  • 8/21/2019 Week 4- Intro to PHP

    53/61

    Create a PHP Function

    A function is a block of code that can be executedwhenever we need it.

    Creating PHP functions:

    All functions start with the word "function()"

    Name the function - It should be possible to understandwhat the function does by its name. The name can startwith a letter or underscore (not a number)

    Add a "{" - The function code starts after the openingcurly brace

    Insert the function code

    Add a "}" - The function is finished by a closing curlybrace

    C t PHP F ti

  • 8/21/2019 Week 4- Intro to PHP

    54/61

    Create a PHP Function

    Example

    A simple function that writes my name when it is called:

    U PHP F ti

  • 8/21/2019 Week 4- Intro to PHP

    55/61

    Use a PHP Function

    Now we will use the function in a PHP script:

    The output of the code above will be:

    Hello world!My name is Kai Jim Refsnes.That's right, Kai Jim Refsnes is my name.

  • 8/21/2019 Week 4- Intro to PHP

    56/61

    PHP Functions Addingparameters

    Our first function (writeMyName()) is a verysimple function. It only writes a static string.

    To add more functionality to a function, we canadd parameters.

    A parameter is just like a variable.

    You may have noticed the parentheses after thefunction name, like: writeMyName().

    The parameters are specified inside theparentheses.

    PHP Functions - Adding

  • 8/21/2019 Week 4- Intro to PHP

    57/61

    PHP Functions Addingparameters

    Example 1

    The following example will writedifferent first names, but the samelast name:

    The output of the code above willbe:

    My name is Kai Jim Refsnes. My name is Hege Refsnes. My name is Stale Refsnes.

    PHP Functions - Adding

  • 8/21/2019 Week 4- Intro to PHP

    58/61

    PHP Functions Addingparameters

    Example 2

    The following function has twoparameters:

    The output of the code above willbe:

    My name is Kai Jim Refsnes.

    My name is Hege Refsnes! My name is Stle Refsnes...

    PHP F ti R t l

  • 8/21/2019 Week 4- Intro to PHP

    59/61

    PHP Functions - Return values

    Functions can also be used to return values.

    Example

    The output of the code above will be:

    1 + 16 = 17

    Hands on 5: Functions

  • 8/21/2019 Week 4- Intro to PHP

    60/61

    Hands-on 5: Functions

    Write a PHP program and create the followingfunctions:

    a. description(): print any statement to describe yourbest body feature, asset, or talent;

    b. function to print the array of integers (fromhandson4).

    Save it as handson5.php, and demonstrate it.

    Online References

  • 8/21/2019 Week 4- Intro to PHP

    61/61

    Online References.

    To help you work with the activity, you canaccess the following online PHP tutorials:

    a. http://www.tizag.com/phpT

    b. http://www.learnphp-tutorial.com c. http://www.killerphp.com/videos/

    d. http://www.w3schools.com

    e. any other online PHP tutorials.

    http://www.tizag.com/phpThttp://www.learnphp-tutorial.com/http://www.killerphp.com/videos/http://www.killerphp.com/videos/http://www.learnphp-tutorial.com/http://www.learnphp-tutorial.com/http://www.learnphp-tutorial.com/http://www.tizag.com/phpT

Recommended