Share
Web Development

Course Outline

Week 1
Week 2

INTRODUCTION TO PHP

  • Installation of Xampp Server
  • Basic Syntax and Statements
    • Variables
    • Operators
    • Control Structures
      • If statements
    • Loops
    Week 3
    Week 4
    Week 5
    Week 6

    SponsoredAdvertise

    Explanations to week content

    INSTALLATION OF XAMPP SERVER


    Xampp is a server application on your location machine.


    Install xampp to your machine.


    You can download xampp installer at:


    https://www.apachefriends.org/download.html


    Double click on the installer and follow the steps until you complete installation

     

    INSTALLATION OF PHP IDE

     

    There are a number of Integrated Development Environment (IDE) for PHP. You can install the one you think will be appropriate for you.

     

    The following are some of the PHP Free IDEs:

    • NetBeans IDE
    • Eclipse PDT
    • Notepad++

    Since we have already installed and used Notepad++ inweek 1, we will use the notepad ++ as our IDE for this course.

     

    Basic Syntax And Statements

     

    <?php
    
    ?>

     

    Commenting in PHP


    Like other programming languages, comments can be donein two ways

    1.     Single Line Comment by using //


    Examples


    //I am a comment

    //Process submitted form

    2.     Block Comment by starting with /*   and ending the comment with */


    Examples


    /* This software is developed by Kuulchat Media */

    /* This is myfirst php script */

    /* Last updated date 10/10/2019 */


    Variables



    Variable is a named memory location that you can use to store a value. A variable can hold only one value at a time, but the value it holds can change.

     

    Declaring Variables

     

    Unlike other programming languages, you don’t specify the data type (int, string, char, float, double etc) of your variable.

     

    You declare your variables simply by using the dollar sign ($)

     

    Variable is therefore declared in PHP as:

     

    $variableName;

     

    NOTE:

     

    Just like any other programming languages, PHP syntax ends with the semi colon (;)

     Like Other Programming Languages, variable names must follow these rules:

    • Must start with a letter (You can’t start variable name with a number)
    • Can't have special characters
    • Can’t have space between letters.
    • Must be declared before using them.
    • Can’t be a reserved word (E.g class, function etc)

    Variable names conventionally begin with lowercase letters to distinguish them from class Names.

    Beginning an identifier with a lowercase letter and capitalizing subsequent words within the identifier is a style known as camel casing. An identifier such as lastName resembles a camel because of the uppercase “hump” in the middle.


    Assigning a value to a variable


    The is used to assign a value to a variable


    Examples


    $firstName = “Godwin”;

    $lastName = “Ashong”;


    Operators


    Performing Arithmetic


    OperatorDescriptionExample
    +Addition1+2 = 3
    -Subtraction1-2 = -1
    *Multiplication1*2 = 2
    /Division½ = 0.5
    %Remainder (Modulus)5%2 = 1

     

    Examples Demonstrating The Usage Of The Operators


    <?php
    $a = 8; // assigns the value 8 to the variable a
    $b = 3; // assigns the value 3 to the variable b
    $c = $a + $b; // adds variables a and b and assign the result to variable c
    $d = $a - $b; // subtracts variable b from variable a and assign the result to variable d
    $e = $a * $b; // multiplies variables a and b and assign the result to variable e
    $f = $a/$b; // Divides variable a by b and assign the result to variable f
    $g = $a%$b; // The remainder of dividing variable a by b is assigned to variable g
    ?>
    


    Displaying Information


    The echo function is used to display information on the screen

    The text to be displayed is placed in the double quotation (“ ”) or single quotation (‘ ‘). When you start with a double quotation, you must use a double quotation to end it and when you use a single quotation to start, you must use a single quotation to end. You can’t mixed the two. Thus you can’t write echo “ ‘; That will produce a syntax error.

     

    Examples


    <?php
         echo “My name is Godwin Ashong”; // Displays My name is Godwin Ashong on the screen
         echo “It is fun learning PHP”; // Displays It is fun learning PHP on the screen
    ?>


    One wonderful beauty of PHP is that you can write aphp script in html code even though the file is in .php.


    Example


    <html>
        <head>
            <title>PHP Script</title>
        </head>
        <body>
            <p><?php echo “My name is Godwin Ashong”; ?></p>
            <p><?php echo “I am 20 years of age”; ?></p>
        </body>
    </html


    JOINING TEXT OR VARIABLES IN PHP


    Dot (.) is used to join two or morevariables together.


    Examples


    <?php
    $text_1= “My name is Godwin Ashong”;
    $text_2 = “ And I am 20 years old”;
    $text_3 = $text_1.$text_2; //Variable text 3 will have the two variable texts join together
    echo $text_3; // This will display My name is Godwin Ashong And I am 20 years old
        
    //More Examples
    $name = “Kofi Agyei”;
    $age = 18;
    echo “Your name is “.$name.” and you are “.$age.” years old”;
    //Displays Your name is Kofi Agyei and you are 18 years old
    //Your name is will be joined with the value stored in the name variable($name)
    // and joined with and you are and joined with the value stored in the age variable   
    // ($age) and finally joined with years old
    ?>
    


    NOTE:


    When joining texts or variables, remember to leave thespace(s) to the appropriate places. For instance in the above code:

    There is a space after the s in the “Yourname is” so that when the $name is joined to it, the name will not be next to the s. Thus to avoid Your name isKofi Agyei being displayed.

    Also there is a space after the e in the and you are so that when the $age is joined, it will not be next to the e. Thus to avoid and you are18.

     Also there is a space before the in the “ years old” so that when the $age is joined, the last digit of the age will not be next to the y. Thus to avoid and youare 18years old.


    CREATING YOUR FIRST PHP SCRIPT


    PHP is a server side script and so it needs a serverin order to run.

    The file extension for PHP script is .php

    Go to your c drive and to the folder where the xamppis installed

    Create a folder webdevelopment in the htdocs

    We will be saving our php files in this folder.


    NOTE:


    For future projects, you can create a folder for your project in the htdocs in xampp and give the folder a name. Usually the name should reflect the project you are working on.


    NOTE: 


    All projects must be placed in the htdocs of the xampp folder in the c drive

    Open your editor (Notepad++) and create a new file week_2_example_1.php and save it in the webdevelopment folder

    We then write a php script to display the text WELCOME TO WEB DEVELOPMENT COURSE

     

    Script


    <?php
        echo “WELCOME TO WEB DEVELOPMENT COURSE”;
    ?>


    You will need to start the xampp server before runningthe php scripts

    To start the xampp server, start the xampp applicationby clicking on the xampp icon



    Figure: Xampp Application


    Click on the first Start for the Apache module

    Once clicked, the Xampp server will then be started



    Figure: Xampp Apache Server started.


    To stop the server just click on the Stop.

    To test if the server is working, type localhost in the browser


    You should get a page like this:


     


    Figure: Xampp Server main page

     

    You can access your php scripts by using the link:

     

    localhost/php file path


     php file path is the path your php script is found.For instance if I have saved the week_1_example_1.php in the webdevelopment folder in the htdocs in the xampp,

     

    The php file path will be:

    webdevelopment/week_1_example_1.php

    Therefore the link to my php page will be:


    localhost/webdevelopment/week_1_example_1.php

     

    Control Structures

     

    If statements

     

    The if statement allows for conditional execution ofcode fragments. In PHP, the simple form

    of the if statement is as follows:

     

    if(expression){

           //blockof code to execute when condition is true comes here

    }

     

    The expression is evaluated to its boolean value. Ifexpression evaluates to TRUE, PHP

    will execute statement, and if it evaluates to FALSE –PHP will ignore it.

     

    Boolean value is one that can be reduced toone of two values: True or False

     

    A condition with two possible alternatives will alsobe in the form:

     

    if(expression){

          //block ofcode to execute when condition is true comes here

    }else{

        //block ofcode to execute when condition is false comes here

    }

     

    You can also check for multiple conditions using the elseif in the form shown below:

     

    if(expression){

        //executethis block of code

    }else if(expression){

       // if the topexpression is false but this expression is true, execute this block of code

    }else if(expression){

      // if thesecond expression is false but this third expression is true, execute thisblock of code

    }

    .

    .

    .

    else if(expression){

         // if theabove expressions are false but this expression is true, execute this block ofcode

    }else{

        // if noneof the above expressions are true, execute this block of code

    }

     

    Relational Operators

     

    OperatorMeaning
    ==Equal to
    !=Not equal to
    Less than
    <=Less than or equal to
    Greater than
    >=Greater than or equal to
    ||Or
    &&And

     

    Example


    The following is the grading system of a school. Writea PHP script that compute the grade of a score.

     

    Grading System


    80 - 100A
    75 - 79B+
    70 - 74B
    65 - 69C+
    60 - 64C
    55 - 59D+
    50 - 54D
    Below 50E

     

    Create a new PHP script and name it week_2_example_2.php in the webdevelopment folder in the htdocs of the xampp.


    Below is the same code for the above task.


    SAMPLE CODE


    <?php
     $score = 49;
     echo "<p>Examination Score:".$score."</p>";
     if($score>=80){
        echo "<p>Grade: A</p>";
     }else if($score>=75){
        echo "<p>Grade: B+</p>";
     }else if($score>=70){
        echo "<p>Grade: B</p>";
     }else if($score>=65){
        echo "<p>Grade: C+</p>";
     }else if($score>=60){
        echo "<p>Grade: C</p>";
     }else if($score>=55){
        echo "<p>Grade: D+</p>";
     }else if($score>=50){
        echo "<p>Grade: D</p>";
     }else{
        echo "<p>Grade: E</p>";
     }
    ?>
    


    The conditional expression is first checked from thetop.


    Expression 1 ($score >=80)


    Read as score is greater than or equal to 80

    Since the value (49) of the score variable ($score) isless than 80, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 2 ($score >=75)


    Read as score is greater than or equal to 75

    Since the value (49) of the score variable ($score) isless than 75, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 3 ($score >=70)


    Read as score is greater than or equal to 70

    Since the value (49) of the score variable ($score) isless than 70, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 4 ($score >=65)


    Read as score is greater than or equal to 65


    Since the value (49) of the score variable ($score) isless than 65, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 5 ($score >=60)


    Read as score is greater than or equal to 60


    Since the value (49) of the score variable ($score) isless than 60, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 6 ($score >=55)


    Read as score is greater than or equal to 55


    Since the value (49) of the score variable ($score) isless than 55, this expression will be false, hence the code in that { } of thatexpression will not be executed


    Expression 7 ($score >=50)


    Read as score is greater than or equal to 50


    Since the value (49) of the score variable ($score) is less than 50, this expression will be false, hence the code in that { } of that expression will not be executed

    else {

     

    }


    Since none of the above expressions is true, the code in the else{} will finally be executed.

    Change the value of the score and save. Refresh your php script in the browser and see the grade. Analyze the code and try to comprehend why the code that produce that grade was executed.

    An alternative to using series of if statements is the switch structure



    Switch

     

    Syntax:

     

    switch(value){

                casevalue_1:

               //code to execute if value matches value_1

               break;

                casevalue_2:

                //codeto execute if value matches value_2

               break;

                .

                .

                .

                casevalue_n:

              //code to execute if value matches value_n

              break;

              default:

              //code to execute if none of the case values matches the value

     

    }

     

    The switch structure uses four keywords:

    • switch starts the structure and is followed immediately by a test expression enclosed in parentheses.
    • case is followed by one of the possible values for the test expression and a colon.
    • break optionally terminates a switch structure at the end of each case.
    • default optionally is used prior to any action that should occur if the test variable does not match any case.


    Create a PHP script file and name it week_2_example_3.php and write the script below to demonstrate the switch structure


    <?php
     $year = 1;
     switch($year){
         case 1:
         echo "<p>Freshman</p>";
         break;
         case 2:
         echo "<p>Level 200</p>";
         break;
         case 3:
         echo "<p>Level 300</p>";
         break;
         case 4:
         echo "<p>Final Year</p>";
         default:
         echo "<p>Incorrect Year</p>";
     }
    ?>
    


    Run the script in the browser to see the result.


    Explanation


    The test expression is the value of the $year


    Case 1:


    if the value of the year is 1, the code after this syntax will be executed

    echo "<p>Freshman</p>";

    The break will be executed which end the execution ofthe block of codes in the switch{}


    Case 2:


    if the value of the year is 2, the code after this syntax will be executed

    echo "<p>Level 200</p>";

    The break will be executed which end the execution ofthe block of codes in the switch{}


    Case 3:


    if the value of the year is 3, the code after this syntax will be executed

    echo "<p>Level 300</p>";

    The break will be executed which end the execution ofthe block of codes in the switch{}


    Case 4:


    if the value of the year is 4, the code after this syntax will be executed

    echo "<p>Final Year</p>";

    The break will be executed which end the execution ofthe block of codes in the switch{}


    default:


    if none of the values matches any of the cases, thecode after the default: will be executed.

    Default is just like the last else in the if statement.

    Change the value of the $year value and run the scriptagain. Try to analyze the code and see the reason why that output


    Looping


    loop is a structure that allows repeatedexecution of a block of statements. Within a looping structure, a Booleanexpression is evaluated. If it is true, a block of statements called the loopbody executes and the Boolean expression is evaluated again. As long as theexpression is true, the statements in the loop body continue to execute. Whenthe Boolean evaluation is false, the loop ends. One execution of any loop iscalled an iteration.



    Figure: Flowchart of a loop structure


    Types of Loops


    There are three types of loops.


    1.    A while loop, in which the loop controlling Boolean expression is the first statement in the loop

    2.    A for loop, which is usually used as a concise format in which to execute loops

    3.    A do…while loop, in which the loop controlling Boolean expression is the last statement in the loop


    Syntax


    while(conditional statement is true){

           //Blockof codes come here to perform a particular task.

    }


    NOTE


    1.

    Initialize the variable that will make the condition to be true in order for the loop to be executed at least once.

    2.


    For a while loop to end at a particular point in time, the variable that makes the condition to be true needs to be updated in order to make the condition false at a particular point in time during the iteration(s)

    Write a program that prints 1 to 10. Thus outputs something like this:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10


    Create a PHP script and name it week_2_example_4.phpand type the script below to demonstrate how a while loop is used.


    <?php
     $i=1;
     while($i<11){
        echo "<p>".$i."</p>";
        /* Update the value of i so that the loop can end at a particular time*/
        $i++;// $i=$i+1;
     }
    ?>
    


    Explanation


    The variable ($i) that controls the loop is initialized

    The expression ($i<11)  in the while loop is then verified, if it istrue, the block of code in the while loop is executed.

    Since $i is 1, the expression will be true so the loopwill start to iterate.

    $i++ means an increment. Is the same as $i = $i+1;Meaning 1 will be added to the current value of $i and the result is stored inthe same $i variable


    Tabular Illustration


    IterationValue of $iExpressionBoolean
    1$i = 1$i < 11True
    2$i = 2, Thus $i = 1+1$i < 11True because 2 is less than 11
    3$i = 3, Thus $i = 2+1$i < 11True because 3 is less than 11
    4$i = 4, Thus $i=3+1$i < 11True because 4 is less than 11
    5$i = 5, Thus $i = 4+1$i < 11True because 5 is less than 11
    6$i = 6, Thus $i = 5+1$i < 11True because 6 is less than 11
    7$i = 7, Thus $i=6+1$i < 11True because 7 is less than 11
    8$i = 8, Thus $i=7+1$i < 11True because 8 is less than 11
    9$i = 9, Thus $i = 8+1$i < 11True because 9 is less than 11
    10$i = 10, Thus $i = 9+1$i < 11True because 10 is less than 11
    11$i = 11, Thus $i = 10+1$i < 11False because 11 is not less than 11

     

    The loop will end when the 11th iteration is about to take place. Since the expression is false, the codes in the block of the while loop is skipped and the loop ends.

     

    NOTE:


    For decrement, the -- is used.

    Thus $i-- is the same as $i = $i - 1


    To display the numbers from 10 to 1, the above code could be modified as shown below:


    <?php
     $i=10;
     while($i>=1){
        echo "<p>".$i."</p>";
        /* Update the value of i so that the loop can end at a particular time*/
        $i--;//$i = $i-1;
     }
    ?>
    


    Modify the code in week_2_example_4.php file as the above code and run the script. Try to analyze why that output


    for loop


    Syntax:


    for(initialize variable; condition to end loop; increment or decrement to change initialized variable){

          //block of code to run

    }

    Write a program that prints 1 to 10. Thus outputs something like this:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10


    Create a PHP script and name it week_2_example_5.php and type the code below:


    <?php
     for($i=1;$i<=10;$i++){
         echo "<p>".$i."</p>";
     }
    ?>
    


    Run the script.

    The loop ends when $i is 11 since 11 is not less than10.

     Modify the code to print from 10 to 1 on the screen


    <?php
     for($i=10;$i>=1;$i--){
         echo "<p>".$i."</p>";
     }
    ?>
    


    Save the file and run the script.


    You realize that the $i is initialized to 10 since we are starting the print out from 10 and it is then decreased using the decrementing order to end the loop.

    The loop ends when $i is 0 since 0 is not greater than1.


    do…while Loop


    For the while loop and for loop, the loop body might execute many times, but it is also possible that the loop will not execute at all when the initial condition that will make the loop iterate is false.

     

    Both while loops and for loops are pretest loops—ones in which the loop control variable is tested before the loop body executes.

    Sometimes, you might need to ensure that a loop body executes at least one time. If so, you want to write a loop that checks at the “bottom” of the loop after the first iteration. The do…while loop checks the value of the loop control variable at the bottom of the loop after one repetition has occurred. The do…while loop is a post test loop—one in which the loop control

    variable is tested after the loop body executes.

     


    Figure: General structure of a do…while loop

     

    Example


    Enter this line of code to the week_2_example_5.php file.


    <?php
     $i = 10;
     do{
        echo "<p>".$i."</p>";
        $i++;
     }while($i<10);
    ?>
    

     

    Save and run your script.


    You will realize that even though $i is 10 and 10 is not less than 10, the loop is executed at least once because the testing of the expression is done after the block of the loop. After the first iteration, the test expression is false and hence the loop ends.

     

    ASSIGNMENT

     

    Write a program that output the multiplication table for a variable. For instance, if a user enters 2, the output should look something like this:

     

    1 x 2 = 2

    2 x 2 = 4

    3 x 2 = 6

    4 x 2 = 8

    5 x 2 = 10

    6 x 2 = 12

    7 x 2 = 14

    8 x 2 = 16

    9 x 2 = 18

    10 x 2 = 20

    11 x 2 = 22

    12 x 2 = 24

    SponsoredAdvertise

    Kuulchat Premium