networkprogramming review sheet.pdf 11206

Upload: mohamedkhaled

Post on 02-Jun-2018

252 views

Category:

Documents


7 download

TRANSCRIPT

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    1/23

    Network Programming: Answered review questions Page 1/2

    Network Programming Fall, 2014-2015

    Question 1: Consider the web-page shown in Figure 1. It consists ofa single form (name it formy) with 4 textboxes and a normal 3buttons. It is shown exactly as it would look when first loaded intoa browser. Use the names (or ids) ageBox, yearsBox, resultsBox,

    and ageDBox for the names or ids of the four textboxes,respectively.a) Write the HTML for this form.b) Use the onload attribute of the body tag to make sure that the first

    textbox has the focus and is selected when the page loads.c) What (exactly) gets displayed (and where does it appear) if the user

    clicks the button (Result!), and the button's onclick attributeexecutes the JavaScript function getResult( ) shown in Script_1?

    d) What does the \r at the end of the function getResult( ) shown inScript_1 code accomplish?

    e) What (exactly) gets displayed (and where does it appear) if the userclicks the button (Erase!), and the button's onclickattribute executes the JavaScript functioneraseMe( ) shown in Script_1?

    f) What (exactly) gets displayed (and where does itappear) if the user clicks the button (DMe!), andthe button's onclick attribute executes theJavaScript function dMe( ) shown in Script_1?

    g) What is the scope (local or global) of the variablex1 and x2 shown in function getResult( )?

    h) If Script_1 is stored in a file called script1.js inthe same folder as your HTML page in part (a),show how you can include this JavaScript file intoyour page.

    Answer:1:

    Enter your current age:

    Enter a number of years:

    Results:

    Click to get the result:

    Click to erease:

    D Me result:

    Click to Execute D Me:

    2:

    3: In the textbox named resultsBox, the string "In 5 years you will be 185 years old." will appear with a newline

    after it.

    4: It adds a return or newline.5: This will erase the contents of the textbox named resultsBox and keep it empty.6: In the textbox named ageDBox, the number 36 then the string years old will appear.7: X1 is local and x2 is global.

    function getResult()

    {with (document.formy)

    {x1=yearsBox.value;

    var x2=ageBox.value;

    resultsBox.value= "In " + x1 +

    " you will be " + x2 +

    yearsBox.value + " years old.\r";

    }}

    function eraseMe(x1)

    {

    x1.value="";

    }function dMe()

    {with (document.formy)

    {

    ageDBox.value= (ageBox.value*2) + " years old.";

    }

    }

    Figure 1

    Script_

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    2/23

    Network Programming: Answered review questions Page 2/2

    Network Programming Fall, 2014-2015

    8: In the head section , we use the tag to include the script_1.js as follows

    Question 2: What is displayed when the following script is executed?

    1

    Question 3: Which values should be assigned to the variables $a, $b and $c in order for the following scripto display the string Hello, World!?

    1

    Answer:The value is: Dog

    Answer:$a = false; $b = false; $c = true;

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    3/23

    Network Programming: Answered review questions Page 3/2

    Network Programming Fall, 2014-2015

    Question 4: What will the following script output?

    1

    Question 5: Consider the following segment of code:

    1

    Question 6: What is the value displayed when the following testscript.php is executed? Assume that thecode was executed using the following URL: testscript.php?c=25

    1

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    4/23

    Network Programming: Answered review questions Page 4/2

    Network Programming Fall, 2014-2015

    4 global $e;

    5 $retval = $c + $d - $_GET['c'] - $e;

    6 return $retval;

    7 }

    8 $e = 10;9 echo process(5);

    10 ?>

    Question 7: What will the following script output?

    1

    Question 8: Consider the following PHP script, which reads a file, line-by-line, from a text file called

    test.txt . Which function call should be inserted in place of the question marks in order for the script tofunction correctly?

    1

    Question 9:Give a complete PHP codethat will send an [email protected]@yyy.ed.egwith the subject "This

    a test email"

    and its body contains the following three statements separated by a single line;How are you xyz

    This is just a test email.

    Yours KYH

    Use a conditional function from which a Boolean is returned upon completion. If PHP successfully passed th

    email to the server then true is returned and the message "The email to xyz from KYH wa

    successfully sent"is displayed. If an error occurred then false is returned and the message"An erro

    occurred when sending the email to xyz from KYH"is displayed.

    Answer:

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    5/23

    Network Programming: Answered review questions Page 5/2

    Network Programming Fall, 2014-2015

    echo "The email to $to from $from was successfully sent";

    else

    echo "An error occurred when sending the email to $to from$from";

    ?>

    Question 10: Consider you are given anHTML page called order2.html as shown inScript_2. You are asked to develop a suitablePHP form processor to get the "item" and"quantity" inputs that are specified in the HTMLform shown in Script_2. This your processorshould return the following two messages in twoseparate lines:

    You ordered(the user quantity) (the user item)

    Thank you for ordering from Art Supplies!

    Answer:

    process.php Code

    Question 11: What is DOM and what can it be used for? In addition to objects representing HTML elementsin DOM, JavaScript provides several other objects that are ready for use. Give one example of these objects andexplain its function. Describe the way events are handled in DOM using JavaScript and give an example.

    Answer:DOM is a platform and language-neutral interface that allow programs and scripts to dynamically access and update thcontent, structure and style of documents.Examples

    Number.toString(radix) Returns the string representation of the number. The optional radix argument (2..36)specifies the base of the number.Date.toString(); Returns a string representation of the date and time in a form specific to the locale of thecomputer, e.g. Wed Apr 05 22:56:24 GMT+0300 (EET) 2008The building blocks of an interactive web page is the JavaScript event system. Javascript programs are typicallyevent-driven. Events are actions that occur on the Web page.Triggering an event is the way of calling Javascript functions. The function which is called upon an event iscalled event handler. often, event handlers are placed within the HTML tag which creates the object on whichthe event acts:

    Art Supply Order Form

    Paint

    Brushes

    Erasers

    Quantity:

    Script_

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    6/23

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    7/23

    Network Programming: Answered review questions Page 7/2

    Network Programming Fall, 2014-2015

    Question 15: Examine the following code segments and draw the appropriate output

    or(var i=10; i>2; i=i-3){ocument.write(" *0XX0*");

    witch(i){ase 7:ocument.write("106");reak;efault:ocument.write("98");}}ocument.write("
    End!");/script>

    Answer:

    Question 16: Examine the following code segments and draw the appropriate outputvar b=0;document.write("");for(var a=10; a>2; a=a-2){

    document.write("");for(var c=3; c

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    8/23

    Network Programming: Answered review questions Page 8/2

    Network Programming Fall, 2014-2015

    Question 17: You need to create an option list (combo box) using one of the HTML input element. The optiolist must contain the list of years from 1900 until the current year (2015). Write the combination of HTML codes anthe PHP script to create the option list, using one repetition statement.

    Answer:

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    9/23

    Network Programming: Answered review questions Page 9/2

    Network Programming Fall, 2014-2015

    Answer:

    1: The following is the script admin.php, which provides the starting point for these tasks

    AdministrationCurrent Questions:

    No questions currently configured

    Add New Question:

    Question

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    10/23

    Network Programming: Answered review questions Page 10/2

    Network Programming Fall, 2014-2015

    Option #1

    Option #2

    Option #3

    Option #4

    Option #5

    2: As you can see, there are two sections in this script. The first half connects to the database and prints a list oall available questions, with "view report" and "delete" links next to each. The second half contains a simplform for the administrator to add a new question and up to five possible answers.

    Once the form is submitted, the data entered by the administrator gets POST-ed to the script add.php, whichvalidates it and saves it to the database.

    Here is the code:Administration

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    11/23

    Network Programming: Answered review questions Page 11/2

    Network Programming Fall, 2014-2015

    die('ERROR: Please enter at least two answer choices');}

    // include configuration fileinclude('config.php');

    // open database connection$connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to

    connect!');

    // select databasemysql_select_db($db) or die('ERROR: Unable to select database!');

    // generate and execute query to insert question$query = "INSERT INTO questions (qtitle, qdate) VALUES ('{$_POST['qtitle']}',

    NOW())";$result = mysql_query($query) or die("ERROR: $query.".mysql_error());// get the ID of the inserted record$qid = mysql_insert_id();

    // reset variablesunset($query);unset ($result);

    // now insert the options// linking each with the question IDforeach ($atitles as $atitle) {

    $query = "INSERT INTO answers (qid, atitle, acount) VALUES ('$qid', '$atitle', '0')"$result = mysql_query($query) or die("ERROR: $query. ".mysql_error());

    }

    // close connectionmysql_close($connection);

    // print success messageecho "Question successfully added to the database! Click here to return to the main page";}else {

    die('ERROR: Data not correctly submitted');}

    ?>

    This script has a lot of things happening in it, so let's go through it step-by-step.

    The first order of business is to sanitizethe data entered by the user. There are a bunch of lines ocode at the top of the script that do this, by checking for a question title and verifying that at least twanswer choices are present. Notice my use of the trim()function to weed out any input that containonly empty spaces, and the sizeof()function that verifies the presence of at least two valid answechoices in the $POST['options']array. Any failure here results in an error message, and the scripwill refuse to proceed further.

    http://devzone.zend.com/manual/function.mysql-connect.phphttp://devzone.zend.com/manual/function.mysql-select-db.phphttp://devzone.zend.com/manual/function.mysql-query.phphttp://devzone.zend.com/manual/function.mysql-error.phphttp://devzone.zend.com/manual/function.mysql-insert-id.phphttp://devzone.zend.com/manual/function.mysql-query.phphttp://devzone.zend.com/manual/function.mysql-error.phphttp://devzone.zend.com/manual/function.mysql-close.phphttp://devzone.zend.com/manual/function.mysql-close.phphttp://devzone.zend.com/manual/function.mysql-error.phphttp://devzone.zend.com/manual/function.mysql-query.phphttp://devzone.zend.com/manual/function.mysql-insert-id.phphttp://devzone.zend.com/manual/function.mysql-error.phphttp://devzone.zend.com/manual/function.mysql-query.phphttp://devzone.zend.com/manual/function.mysql-select-db.phphttp://devzone.zend.com/manual/function.mysql-connect.php
  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    12/23

    Network Programming: Answered review questions Page 12/2

    Network Programming Fall, 2014-2015

    Assuming all the data is acceptable, the next step is to saveit to the database. First, the question isaved to the questions table via an INSERT query. The ID generated by this INSERT query iretrieved via the mysql_insert_id() function, and used to link the answer choices to the questiowhen saving them to the answers table. Since there will be more than one answer choice for eachquestion, a foreach()loop is used to repeatedly run an INSERTquery - once for each possible answe

    choice.That takes care of adding questions and answers.Now, what about removingthem?Well, go back and take a look at the admin.php script. You'll see that, next to each questiodisplayed, there is a "delete" link, which points to the script delete.php. You'll also see that this scripis passed an input parameter, the question ID, on the URL itself. It's clear, then, that delete.phpcause this input parameter to identify the corresponding question in the questions table (as well as itanswers - the question ID is common to both tables, remember) and run a DELETEquery to erasthis data from the system.

    Here's the code that actually does the work:

    Administration

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    13/23

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    14/23

    Network Programming: Answered review questions Page 14/2

    Network Programming Fall, 2014-2015

    However it can happen that the visitor submitted an empty form by just clicking on the Send button. In this

    case only one of the above mentioned array element exists and it is the submitForm. In case of submitting HTML form the submit button value always be present in the $_POSTarray. Now we can create a simpleconditional statement to decide what to do. If the $_POST['submitForm']doesn't exist then we display theform else print out a message that the form was submitted.

    The code to do this looks like this:Code:1.4.5. 6. 7. Name:8. 9. 10. 11. Email:12. 13. 14. 15. Message:16. 17. 18. 19. 20. 21.22.

    Question 20: Given a file called test.txt, show how you can:

    i) Open and write string in this file ii) Open and read string from this file

    ii) Open and read characters from this file v) Open and read the whole file at onceAnswerLook at your lectures

    Question 21: Develop a Javascript code in a Web page that prompts the user for 10 words

    and then displays them in form of a list in two different ways; In the order in which the words werentered and In a sorted order.

    AnswerLook at your lectures

    http://www.phpf1.com/manual/issethttp://www.phpf1.com/manual/echohttp://www.phpf1.com/manual/echohttp://www.phpf1.com/manual/isset
  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    15/23

    Network Programming: Answered review questions Page 15/2

    Network Programming Fall, 2014-2015

    Question 22: Write the command (in PHP) to connect to a database named myDB that resides i186.106.11.30, using the username rootand the password dbserv. Check whether the connection is successful.

    Use the following Figure to solve the following questions:

    Figure 1: The tableInfostructure.1. Write the SQL command to fetch records with fields involved are only firstname, gender and ema

    where the gender only Male.2. use the function num_rows()to check if the table contains more than zero rows. If there is no row

    display 0 results3. Write the PHP script to display all the records resulted from the SQL query in (1).

    Answer

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    16/23

    Network Programming: unanswered review questions Page 16/23

    Network Programming Fall, 2014-2015

    Unanswered questionsQuestion 23:Given a file called test.txt, show how you can:

    v) Open and write string in this file i) Open and read string from this file

    ii) Open and read characters from this file ii) Open and read the whole file at onceQuestion 24: Develop a Javascript code in a Web page that prompts the user for 10 words,and then displays them in form of a list in two different ways; In the order in which the wordswere entered and In a sorted order.

    Question 25: Figure 1 shows a part of the database of the Employee Affairs System of the AhramUniversity in Cairo. It simply contains two related tables; employees and departments where one employee

    can work in one department, and one department can contain many employees. Figure 2 shows two web pages

    we consider. The first one titled as add.employee.php. The second is process.php. Figure 3 shows an HTML

    source of the page add.employee.php.

    Figure 1:System ER diagram

    Figure 2: System pages

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    17/23

    Network Programming: unanswered review questions Page 17/23

    Network Programming Fall, 2014-2015

    Figure 3: HTML ode of add.employee.php

    Assumptions:- Your mysql database is installed and ready to use.- The main DB server name is SE.- Username and password are admin,yes accordingly.- The DB name you need to select is named as WEB.

    Notes:- Your solution MUST handle errors using try and catch exception mechanism.- It is recommended you provide an object oriented solution.

    Requirements:

    (1)Write a Javascript code to verify the add.student form based on the following elements:- All values must not be empty.- Gender values must be either male or female.- ID must be numeric number.

    (2)Write a php code that does the verification elements mentioned in 1 in addition to the following:- Name value must be alphabetic.- ID must be obtained from the department table.

    (3)Write a php code that adds values inserted in the form of add.employee to the system database. This php code

    shall be encapsulated within process.php. A success message shall be shown when added successfully.Otherwise, a failure message should be shown accompanying the error type.

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    18/23

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    19/23

    Network Programming: unanswered review questions Page 19/23

    Network Programming Fall, 2014-2015

    i) Define a PHP function called get num_hands, which takes in an array like the one above and returns how manyhands have been played, e.g. 7 in the example above.

    ii) Define a PHP function called get wins which takes in an array like the one above and returns an indexed arrayof its values but with no duplicates, e.g. array(0, 3, 2) in the example above.

    iii) Define a PHP function called get league which takes in an array like the one above and returns a 2-dimensional

    array like the following:array(

    array("BB", "GG"),array(),array("JJ", "DD"),array("LL"),array(),array(),array(),array()

    )

    This is an indexed array. In position 0 is an array of people who have won no games; in position 1 is an array of peoplewho have won one game; and so on up to the total number of games played.

    (You may use the get num hands functions you defined in part (i) above, if you wish.)

    Question 29: LostPost determines postal rates depending on type (postcard, letter, or parcel), weight(in grams) and destination (within Lostland, Outer Lostland, or elsewhere). Suppose rates.html containsthis form:

    Write rates.php which takes data from this form and outputs the total delivery charge based on the following information:

    For delivery within Lostland, postcards cost 2 euros; letters cost 3. But if a postcard or letter weighs 100g ormore, then it does not qualify for these rates. It is instead charged at the same rates as parcels (below). In thiscase, as well as outputting the total delivery charge, also output a sentence that explains to the user that this iswhat has happened.

    For delivery within Lostland, parcels weighing no more than 1kg cost 6 euros in total; those weighing no morethan 2kg cost 8. Parcels that are heavier than 2kg cost 11 euros plus 1 euro for every extra 1kg of weight.

    For delivery to Outer Lostland, all rates are one-and-a-half times those given above; for delivery elsewhere, allrates are double those given above.

    A stylesheet is not required. Validation of user data is required.

    Question 30:1) Evaluate each of the following as PHP would, and state the value and type of $x after each statement:

    a. $x = 2 - 3 + 4;b. $x = 8 + 3 % 3;

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    20/23

    Network Programming: unanswered review questions Page 20/23

    Network Programming Fall, 2014-2015

    c. $x = abc. (2 + 3) . def;d. $x = 2 > 3 || (7 < 8 && 5 != 6);e. $x = (2 > 3 ? 10 : (5 3)

    {echo fizz ;}elseif ($x > 7){echo buzz ;}if ($x > 11){

    if ($x < 15){echo buzz ;

    }}

    function foo(&$a){

    $x = 0;foreach ( $a as $v ){

    $x ++;}return $x;

    }

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    21/23

    Network Programming: unanswered review questions Page 21/23

    Network Programming Fall, 2014-2015

    5) Consider the following function, whose parameter $n is an integer, and which is intended to compute the sumof all positive odd numbers up to and including $n (or up to and including one less than $n if $n is even):

    The function has no compile-time or run-time errors, but it does have a logic error.

    a. Explain the error. Use an example, if you wish.b. Explain how to fix the error.

    6) Compare this snippet of PHP:

    with this one:

    If you think they are equivalent (i.e. same outputs for the same inputs), state which one is more efficient and why it isthe more efficient. If you think they are not equivalent, how will their outputs differ?

    function sum_odds( $n ){$sum = 0 ;if (( $n % 2) == 0 ) // If $n iseven, make it odd{$n--;}

    whi l e ( $n > 0 ){

    $sum += $n ;$n--;

    }return $sum ;}

    $ i = (int) $_GET[number] ;while ($i > 0){

    $i--;echo $i;

    }

    for ($i = (int) $_GET[number];

    $i > 0; $i-- ){echo $i;

    }

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    22/23

    Network Programming: unanswered review questions Page 22/23

    Network Programming Fall, 2014-2015

    Question 31: Develop a PHP page to receive all the information from the form in Figure x. Insert all theinformation to the database in Figure y. The password must be encoded using md5 function before being inserted tothe database. Display the members information (inside a table) in this page, except the password.

    Database connection: host=localhost, username=root, password=abc123

    Figure 1: The membership form.

    Figure x: The structure of database itclub.

  • 8/10/2019 NetworkProgramming Review Sheet.pdf 11206

    23/23

    Network Programming: unanswered review questions Page 23/23

    Network Programming Fall, 2014-2015

    Question 33: The following Figureis a table namedBookInfoextracted from a database namedLibrary.Use the table to answer this question.

    Figure 3: TableBookInfo

    Let say a user would like to find a book on security but you do not know the complete title of the book. However heremembers that the book is published by John Wiley on 2004.

    a) Create a search application to facilitate the user to find the book he needs. The search form receives the part ofthe books title, the publisher and the year published. It also has a submit button. When the user key-in all theinformation, and click the submit button, the result of the book search will appear at the bottom of the form.

    b) Develop the complete HTML form to insert a new book to heBookInfotable. Include all fields appeared in theabove figure.

    The END

    Good Luck