Vous êtes sur la page 1sur 23

Network Programming

Fall, 2014-2015

Question 1: Consider the web-page shown in Figure 1. It consists of


a single form (name it formy) with 4 textboxes and a normal 3
buttons. It is shown exactly as it would look when first loaded into
a 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 attribute
executes the JavaScript function getResult( ) shown in Script_1?
d) What does the \r at the end of the function getResult( ) shown in
Script_1 code accomplish?
e) What (exactly) gets displayed (and where does it appear) if the user
clicks the button (Erase!), and the button's onclick
function getResult()
attribute executes the JavaScript function
{
eraseMe( ) shown in Script_1?
with (document.formy)
f) What (exactly) gets displayed (and where does it
{
appear) if the user clicks the button (DMe!), and
x1=yearsBox.value;
the button's onclick attribute executes the
var
x2=ageBox.value;
resultsBox.value= "In " + x1 +
JavaScript function dMe( ) shown in Script_1?
" you will be " + x2 +
g) What is the scope (local or global) of the variable
yearsBox.value + " years old.\r";
x1 and x2 shown in function getResult( )?
}
h) If Script_1 is stored in a file called script1.js in
}
the same folder as your HTML page in part (a),
function eraseMe(x1)
show how you can include this JavaScript file into
{
your page.

Answer:
1:

Figure 1

Script_1

x1.value="";
}
function dMe()
{
with (document.formy)
{
ageDBox.value= (ageBox.value*2) + " years old.";
}
}

<form name="formy" id="formy">


<p>Enter your current age: <input
name="ageBox" id="ageBox" value="18"
size="5" ></p>
<p>Enter a number of years: <input
name="yearsBox" id="yearsBox"
value="5" size="5" ></p>
<p>Results: <input name="resultsBox" id="results" size="30" >
<p>Click to get the result: <input type="button" value="Result!" onclick="getResult()"></p>
<p>Click to erease: <input type="button" value="Erase!"
onclick="eraseMe(document.formy.resultsBox)" ></p>
<p> D Me result: <input name="ageDBox" id="ageDBox" value=" " ></p>
<p> Click to Execute D Me: <input type="button" value="Double!" onclick="doMe()" ></p>
</form>

2:
<body onload="document.formy.ageBox.focus(); document.formy.ageBox.select();">
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.

Network Programming: Answered review questions

Page 1/23

Network Programming

Fall, 2014-2015

8: In the head section <head> </head>, we use the <script> tag to include the script_1.js as follows
<script type="text/javascript" language="Javascript" src="script_1.js">
</script>

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


1 <?php
define(myvalue, "10");
2
$myarray[10] = "Dog";
3
Answer:
The value is: Dog
$myarray[]
=
"Human";
4
$myarray['myvalue'] = "Cat";
5
$myarray["Dog"] = "Cat";
6
print "The value is: ";
7
print $myarray[myvalue]."\n";
8
9 ?>
Question 3: Which values should be assigned to the variables $a, $b and $c in order for the following script
to display the string Hello, World!?
1 <?php
2 $string = "Hello, World!";
3 $a = ?;
4 $b = ?;
5 $c = ?;
6 if($a){
if($b && !$c) {
7
echo "Goodbye Cruel World!";
8
}else if(!$b && !$c) {
9
echo "Nothing here";
10
}
11
12 }else{
if(!$b){
13
if(!$a && (!$b && $c)){
14
echo "Hello, World!";
15
}else{
16
echo "Goodbye World!";
17
}
18
}else{
19
echo "Not quite.";
20
Answer:
}
$a = false; $b = false; $c = true;
21
22 }
23 ?>

Network Programming: Answered review questions

Page 2/23

Network Programming
Question 4: What will the following script output?
1 <?php
$array = '0123456789ABCDEFG';
2
$s = '';
3
for ($i = 1; $i < 50; $i++) {
4
$s .= $array[rand(0,strlen ($array) - 1)];
5
}
6
echo $s;
7
8 ?>

Fall, 2014-2015

Answer:
87D6ECDC558E9E509A160525G24E0DF649DF
415F3B659G4B9

Question 5: Consider the following segment of code:


1 <?php
define("STOP_AT",1024);
2
$result = array();
3
/* Missing code */
4
{
5
$result[] = $idx;
6
}
7
print_r($result);
8
What should go in the marked segment to produce the following array output?
Array
{
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
}
?>

=>
=>
=>
=>
=>
=>
=>
=>
=>
=>

1
2
4
8
16
32
64
128
256
512

Answer:
for($idx = 1; $idx < STOP_AT; $idx *= 2)

Question 6: What is the value displayed when the following testscript.php is executed? Assume that the
code was executed using the following URL: testscript.php?c=25
<?php
1
2 function process($c, $d = 25)
3 {

Network Programming: Answered review questions

Page 3/23

Network Programming
global $e;
4
$retval = $c + $d - $_GET['c'] - $e;
5
return $retval;
6
7 }
8 $e = 10;
9 echo process(5);
10 ?>

Fall, 2014-2015

Answer:
-5

Question 7: What will the following script output?


1 <?php
Answer:
2 echo 'Testing ' . (1 + 2) . '45';
Testing 345
?>
3
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 to
function correctly?
1 <?php
2 $file = fopen("test.txt", "r");
Answer:
3 while(!feof($file)) {
fgets($file)
echo
????????????;
4
5 }
6 fclose($file);
7 ?>
Question 9:
Give a complete PHP code that will send an email from KYH@yyy.ed.eg to xyz@yyy.ed.eg with the subject "This is
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 the
email to the server then true is returned and the message "The email to xyz from KYH was
successfully sent" is displayed. If an error occurred then false is returned and the message "An error
occurred when sending the email to xyz from KYH" is displayed.

Answer:
<?php
$to = "xyz@bue.ed.eg";
$from = "KYH@ bue.ed.eg";
$subject = "This is a test email";
$message = "Dear xyz,\n\n\n This is just a test email.\n\n
Yours KYH";
$headers = "From: $from\r\n";
$success = mail($to, $subject, $message, $headers);
if ($success)

Network Programming: Answered review questions

Page 4/23

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 an
HTML page called order2.html as shown in
Script_2. You are asked to develop a suitable
PHP form processor to get the "item" and
"quantity" inputs that are specified in the HTML
form shown in Script_2. This your processor
should return the following two messages in two
separate lines:
You ordered (the user quantity) (the user item)
Thank you for ordering from Art Supplies!

Answer:

Script_2
<html>
<body>
<h4>Art Supply Order Form</h4>
<form action="process2.php" method= "get" >
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" value= "submit Query" />
</form>
</body>
</html>

process.php Code
<html>
<body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ".$quantity." ".$item. ".<br />";
echo "Thank you for ordering from Art Supplies!";
?>
</body>
</html>
Question 11:
What is DOM and what can it be used for? In addition to objects representing HTML elements
in DOM, JavaScript provides several other objects that are ready for use. Give one example of these objects and
explain 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 the
content, 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 the
computer, e.g. Wed Apr 05 22:56:24 GMT+0300 (EET) 2008
The building blocks of an interactive web page is the JavaScript event system. Javascript programs are typically
event-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 is
called event handler. often, event handlers are placed within the HTML tag which creates the object on which
the event acts:

Network Programming: Answered review questions

Page 5/23

Network Programming

Fall, 2014-2015

<tag attribute1 attribute2 onEventName="javascript code;">


Example:
<a href=http://www.bue.edu.eg/index.html onMouseOver="popupFunc();">

Question 12:

What is JavaScript? What is the main benefit of it? Where can it be used compared with PHP?
What can it is used for?

Answer:
JavaScript is a compact, object-based scripting language for developing client and server Internet applications. JavaScript
statements can be embedded directly in an HTML page.
The main benefit of JavaScript is to add additional interaction between the website and its visitors with just a
little extra work by the web developer. JavaScript allows industrious web masters to get more out of their website
than HTML and CSS can provide.
By definition, JavaScript is a client-side scripting language. This means the web surfer's browser will be running
the script.
The opposite of client-side is server-side, which occurs in a language like PHP. PHP scripts are run by the web
hosting server. There are many uses for the powerful JavaScript language. Here are a few things that you may or
may not have seen in your web surfing days:
Clocks
Mouse Trailers (an animation that follows your mouse when you surf a site)
Drop Down Menus
Alert Messages
Popup Windows
HTML Form Data Validation

Question 13:

With respect to objects, describe the difference between a property and a method. Feel free to
use words like thing, action, description, attribute, and so forth. What is the difference between an event
and an event handler? And where are event handlers placed in the XHTML document?

Answer:
An object is a thing, a property is an attribute, and a method is an action.
An event is an occurrence such as click, load, and mouseover. An event handler is an attribute embedded in an
XHTML tag as onclick, onload, and onmouseover, that points to some JavaScript code to execute when the
corresponding event occurs. Event handlers are embedded in XHTML tags and are not placed in separate script blocks.

Question 14:

Describe the components of the client/server model as applied to the Internet; and the
difference between a dedicated web server and a co-located web server.

Answer:
An example of a Web Client is a computer running a browser software application such as Internet Explorer. The computer
is typically connected to the Internet only when needed. The Web browser software uses HTTP to request Web pages
and related resources from a Web server. A Web server is a computer that is continually connected to the Internet and
that runs some type of Web server software application. It uses the HTTP protocol to receive requests for Web pages
and related resources. It respond to these requests and sends the resources.
A dedicated Web server is owned and supported by the Web host company. The client company may choose to administer
it or may pay the Web host company to perform this task. A co-located server is owned by the client company and
housed at the Web host provider. This offers both the advantage of s reliable Internet connection at the Web host and
full control of the administration and support of the Web server

Network Programming: Answered review questions

Page 6/23

Network Programming
Question 15:

Fall, 2014-2015

Examine the following code segments and draw the appropriate output
<script language="javascript">
for(var i=10; i>2; i=i-3)
{
document.write(" *0XX0*");
switch(i)
{
case 7:
document.write("106");
break;
default:
document.write("98");
}
}
document.write("<br>End!");
</script>

Answer:

Question 16:
Examine the following code segments and draw the appropriate output
<script type="text/javascript">
var b=0;
document.write("<table border=1 width=30%>");
for(var a=10; a>2; a=a-2)
{
document.write("<tr>");
for(var c=3; c<10; c=c*2)
{
if(a==c)
{document.write("<td>"+b+"</td>");}
else
{document.write("<td>"+a+"</td>");}
}
document.write("</tr>");
}
document.write("</table>");

</script>
Answer:

Network Programming: Answered review questions

Page 7/23

Network Programming

Fall, 2014-2015

Question 17:

You need to create an option list (combo box) using one of the HTML input element. The option
list must contain the list of years from 1900 until the current year (2015). Write the combination of HTML codes and
the PHP script to create the option list, using one repetition statement.
Answer:
<html>
<form>
<select name="year">
<?php
$currentYear=2005; // initial year
while($currentYear <= 2020)
{
echo "<option value='$currentYear'>";
echo $currentYear;
$currentYear++; // adds one to year
}
?>
</select>
</form>
</html>

Question 18:
It is required to build an application to provide the administrator with an easy way to
add and delete questions and answers from the MySQL database. Here's what the administrator form looks
like:

Network Programming: Answered review questions

Page 8/23

Network Programming

Fall, 2014-2015

Answer:
1: The following is the script admin.php, which provides the starting point for these tasks
<html>
<head><basefont face = 'Arial'></head>
<body>
<h2>Administration</h2>
<h4>Current Questions:</h4>
<table border = '0' cellspacing = '10'>
<?php
// include configuration file
include('config.php');
// open database connection
$connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to connect!');
// select database
mysql_select_db($db) or die('ERROR: Unable to select database!');
// generate and execute query
$query = 'SELECT qid, qtitle, qdate FROM questions ORDER BY qdate DESC';
$result = mysql_query($query) or die('ERROR: $query. '.mysql_error());
// if records are present
if (mysql_num_rows($result) > 0) {
// iterate through resultset
// print question titles
while($row = mysql_fetch_object($result)) {
?>
<tr>
<td><?php echo $row->qtitle; ?></td>
<td><font size = '-2'><a href = 'view.php?qid=<?php echo $row->qid; ?>
'>view report</a></font></td>
<td><font size = '-2'><a href = 'delete.php?qid=<?php echo $row->qid;?>
'>delete</a></font></td>
</tr>
<?php
}
}
// if no records are present, display message
else {
?>
<font size='-1'>No questions currently configured</font>
<?php
}
// close connection
mysql_close($connection);
?>
</table>
<h4>Add New Question:</h4>
<form action = 'add.php' method ='post'>
<table border = '0' cellspacing = '5'>
<tr>
<td>Question</td>
<td><input type = 'text' name = 'qtitle'></td>
</tr>
<tr>

Network Programming: Answered review questions

Page 9/23

Network Programming

Fall, 2014-2015

<td>Option #1</td>
<td><input type = 'text' name = 'options[]'></td>
</tr>
<tr>
<td>Option #2</td>
<td><input type = 'text' name = 'options[]'></td>
</tr>
<tr>
<td>Option #3</td>
<td><input type = 'text' name = 'options[]'></td>
</tr>
<tr>
<td>Option #4</td>
<td><input type = 'text' name = 'options[]'></td>
</tr>
<tr>
<td>Option #5</td>
<td><input type = 'text' name = 'options[]'></td>
</tr>
<tr>
<td colspan = '2' align = 'right'><input type = 'submit' name = 'submit' value =
'Add Question'></td>
</tr>
</table>
</form>
</body>
</html>

2: As you can see, there are two sections in this script. The first half connects to the database and prints a list of
all available questions, with "view report" and "delete" links next to each. The second half contains a simple
form 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, which
validates it and saves it to the database.
Here is the code:
<html>
<head><basefont face = 'Arial'></head>
<body>
<h2>Administration</h2>
<?php
if (isset($_POST['submit'])) {
// check form input for errors
// check title
if (trim($_POST['qtitle']) == '') {
die('ERROR: Please enter a question');
}
// clean up options
// add valid ones to a new array
foreach ($_POST['options'] as $o) {
if (trim($o) != '') {
$atitles[] = $o;
}
}
// check for at least two options
if (sizeof($atitles) <= 1) {

Network Programming: Answered review questions

Page 10/23

Network Programming

Fall, 2014-2015

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


}
// include configuration file
include('config.php');
// open database connection
$connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to
connect!');
// select database
mysql_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 variables
unset($query);
unset ($result);
// now insert the options
// linking each with the question ID
foreach ($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 connection
mysql_close($connection);
// print success message
echo "Question successfully added to the database! Click <a
href='admin.php'>here</a> to return to the main page";
}
else {
die('ERROR: Data not correctly submitted');
}
?>
</body>
</html>

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 sanitize the data entered by the user. There are a bunch of lines of
code at the top of the script that do this, by checking for a question title and verifying that at least two
answer choices are present. Notice my use of the trim() function to weed out any input that contains
only empty spaces, and the sizeof() function that verifies the presence of at least two valid answer
choices in the $POST['options'] array. Any failure here results in an error message, and the script
will refuse to proceed further.

Network Programming: Answered review questions

Page 11/23

Network Programming

Fall, 2014-2015

Assuming all the data is acceptable, the next step is to save it to the database. First, the question is
saved to the questions table via an INSERT query. The ID generated by this INSERT query is
retrieved via the mysql_insert_id() function, and used to link the answer choices to the question
when saving them to the answers table. Since there will be more than one answer choice for each
question, a foreach() loop is used to repeatedly run an INSERT query - once for each possible answer
choice.
That takes care of adding questions and answers.
Now, what about removing them?
Well, go back and take a look at the admin.php script. You'll see that, next to each question
displayed, there is a "delete" link, which points to the script delete.php. You'll also see that this script
is passed an input parameter, the question ID, on the URL itself. It's clear, then, that delete.php can
use this input parameter to identify the corresponding question in the questions table (as well as its
answers - the question ID is common to both tables, remember) and run a DELETE query to erase
this data from the system.
Here's the code that actually does the work:
<html>
<head><basefont face = 'Arial'></head>
<body>
<h2>Administration</h2>
<?php
if ($_GET['qid'] && is_numeric($_GET['qid'])) {
// include configuration file
include('config.php');
// open database connection
$connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to connect!');
// select database
mysql_select_db($db) or die('ERROR: Unable to select database!');
// generate and execute query
$query = "DELETE FROM answers WHERE qid = '".$_GET['qid']."'";
$result = mysql_query($query) or die("ERROR: $query. ".mysql_error());
// generate and execute query
$query = "DELETE FROM questions WHERE qid = '".$_GET['qid']."'";
$result = mysql_query($query) or die("ERROR: $query. ".mysql_error());
// close connection
mysql_close($connection);
// print success message
echo "Question successfully removed from the database! Click <a href =
'admin.php'>here</a> to return to the main page";
}
else {
die('ERROR: Data not correctly submitted');
}
?>
</body>
</html>

As you can see, the question ID passed through the GET method is retrieved by the script, and used inside two
DELETE queries to remove all the records linked to that ID.

Network Programming: Answered review questions

Page 12/23

Network Programming

Fall, 2014-2015

Question 19:
Almost each company web site has a contact form where the visitor can send a message
to the site owner. On such a contact form usually there are more fields: one for the visitor name, one for the
email address and one for the main message itself. The HTML code of a basic contact form looks something
similar:
Code: (form.php)
1. <form action="form.php" method="POST">
2.
<table>
3.
<tr>
4.
<td>Name:</td>
5.
<td><input type="text" name="name"></td>
6.
</tr>
7.
<tr>
8.
<td>Email:</td>
9.
<td><input type="text" name="email"></td>
10.
</tr>
11.
<tr>
12.
<td>Message:</td>
13.
<td><textarea name="mesg"></textarea></td>
14.
</tr>
15.
<tr>
16.
<td><input type="submit" name="SubmitForm" value="Send"></td>
17.
</tr>
18.
<form>

This code results an output like this:

Create a compact PHP page, which will display the HTML form if the user visit it. If the form is
submitted, your program will recognize it and instead of displaying the form it will process the submitted
data. If a form was submitted and the script defined in the action parameter of the form tag is called then
a so-called super global array will be populated with the user-entered information.

Answer:
In this problem we have 4 inputs: 2 input text fields, 1 textarea and 1 input submit button. Each of them has its
own name. As we defined to send form data as POST (See the method form parameter) so to $_POST array
will contain 4 elements. Something like that:
Code:
1.
2.
3.
4.

$_POST['name'] : "xyz"
$_POST['email'] : "xyz@xyz.com"
$_POST['mesg'] : "Hello, my nam is Xyz!"
$_POST['submitForm'] : "Send"

What does it mean? It means that we can check this array. If it is filled then the user has submitted the form
and if it is empty then no submission was done so we need to display the form.

Network Programming: Answered review questions

Page 13/23

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 a
HTML form the submit button value always be present in the $_POST array. Now we can create a simple
conditional statement to decide what to do. If the $_POST['submitForm'] doesn't exist then we display the
form else print out a message that the form was submitted.
The code to do this looks like this:
Code:
1. <?php
2. if (!isset($_POST['submitForm'])) {
3. ?>
4. <form action="form.php" method="POST">
5.
<table>
6.
<tr>
7.
<td>Name:</td>
8.
<td><input type="text" name="name"></td>
9.
</tr>
10.
<tr>
11.
<td>Email:</td>
12.
<td><input type="text" name="email"></td>
13.
</tr>
14.
<tr>
15.
<td>Message:</td>
16.
<td><textarea name="mesg"></textarea></td>
17.
</tr>
18.
<tr>
19.
<td><input type="submit" name="SubmitForm" value="Send"></td>
20.
</tr>
21. <form>
22. <?php
23.
} else {
24.
echo "Form submitted!";
25. }
26. ?>

Question 20:

i)
iii)

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

Open and write string in this file


Open and read characters from this file

ii)
iv)

Open and read string from this file


Open and read the whole file at once

Answer
Look 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 were
entered and In a sorted order.
Answer
Look at your lectures

Network Programming: Answered review questions

Page 14/23

Network Programming

Fall, 2014-2015

Question 22:

Write the command (in PHP) to connect to a database named myDB that resides in
186.106.11.30, using the username root and the password dbserv. Check whether the connection is successful.

Use the following Figure to solve the following questions:

Figure 1: The tableInfo structure.


1. Write the SQL command to fetch records with fields involved are only firstname, gender and email,
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 rows
display 0 results
3. Write the PHP script to display all the records resulted from the SQL query in (1).

Answer
<?php
$dbhost = 186.106.11.30;
$dbuser = 'XYZ';
$dbpass = 'XYZpass';
$dbname = ' myDB';
$table = ' tableInfo';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error()); }
if (!mysql_select_db($dbname))
die("Can't select database");

$sql = SELECT firstname, gender, email


FROM tableInfo
WHERE gender=male;
$result = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error()); }
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysql_fetch_assoc($result))
{
echo "First Name :{$row[firstname']} <br> ".
"Gender: {$row['gender']} <br> ".
"email : {$row['email']} <br> ".
"--------------------------------<br>"; }
}
echo "Fetched data successfully\n";
else
{ echo "0 results"; }
mysql_close($conn); ?>

Network Programming: Answered review questions

Page 15/23

Network Programming

Fall, 2014-2015

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

v)
vii)

Open and write string in this file


Open and read characters from this file

vi)
viii)

Open and read string from this file


Open and read the whole file at once

Question 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 words
were entered and In a sorted order.
Question 25:

Figure 1 shows a part of the database of the Employee Affairs System of the Ahram
University 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

Network Programming: unanswered review questions

Page 16/23

Network Programming

Fall, 2014-2015

Figure 3: HTML Code 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.

Network Programming: unanswered review questions

Page 17/23

Network Programming
Question 27:

Fall, 2014-2015

ARBAirways uses the following two database tables to record the flights it offers and the

airports it uses:

Suppose destinations.html contains this form:


<form action="destinations.php" method="get">
<input type="text" name="going_from" />
<input type="submit" />
</form>
The user enters the code of the airport from which s/he likes to travel. Write destinations.php which receives the users
input, queries the database, and outputs a well-formed HTML unordered list of countries to which there is at least one
direct flight from the users chosen airport, including nested lists of flight numbers to that country.
For example, using the database shown above, if the user enters ORK, the users browser will display something like
the following:
England
o ea101
France
o ea104
Scotland
o ea102
o ea103
You may assume that the following function invocation will connect your script to the database:

connect_to_database( my_server, me, my_passsword, my_db );


You may use any built-in functions that you wish, including: mysql query( $sql ) to execute query $sql on the database;
mysql num rows( $dbresult ) to find out how many rows the result-set $dbresult contains; and mysql fetch assoc(
$dbresult ), which returns the next row of the result-set or false when there are no more rows.
A stylesheet is not required. Validation of user data is not required.

Question 28:
others:

In your answers to this question, you may use the following built-in functions but no

The array function for creating an array, e.g. array() creates an empty array.
The in array function, whereby in_array( $v, $vs ) returns true if $v is an element in array $vs; otherwise, it
returns false. For example, it returns true if $v is 7 and $vs is array(3, 1, 7, 13).
A group of friends use an associative array to record their names and the number of hands of poker each has won, e.g.:

array("BB" => 0, "LL" => 3, "JJ" => 2, "DD" => 2, "GG" => 0)
Network Programming: unanswered review questions

Page 18/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 many
hands 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 array
of 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 people
who 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 contains
this form:
<form action="rates.php" method="get">
<input type="radio" name="type" value="postcard" />
<input type="radio" name="type" value="letter" />
<input type="radio" name="type" value="parcel" />
<input type="text" name="weight_in_g" value="0" />
<input type="radio" name="dest" value="within" />
<input type="radio" name="dest" value="outer" />
<input type="radio" name="dest" value="elsewhere" />
<input type="submit" />
</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 or
more, then it does not qualify for these rates. It is instead charged at the same rates as parcels (below). In this
case, as well as outputting the total delivery charge, also output a sentence that explains to the user that this is
what has happened.
For delivery within Lostland, parcels weighing no more than 1kg cost 6 euros in total; those weighing no more
than 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, all
rates 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;
Network Programming: unanswered review questions

Page 19/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 <= 6 ? 20 : 30));
2) Suppose that variable $x contains an integer, and consider the following:
if ($x > 3)
{
echo fizz ;
}
elseif ($x > 7)
{
echo buzz ;
}
if ($x > 11)
{
if ($x < 15)
{
echo buzz ;
}
}

Precisely state for what range of values the output will be


a. just fizz?
b. just buzz?
c. both fizz and buzz?
d. neither?
3) Consider the following function, whose parameter $a is an array:
function foo(&$a)
{
$x = 0;
foreach ( $a as $v )
{
$x ++;
}
return $x;
}

a. Describe what it computes and returns.


b. Suggest a more appropriate name for the function.

Network Programming: unanswered review questions

Page 20/23

Network Programming

Fall, 2014-2015

5) Consider the following function, whose parameter $n is an integer, and which is intended to compute the sum
of all positive odd numbers up to and including $n (or up to and including one less than $n if $n is even):
function sum_odds( $n )
{
$sum = 0 ;
if (( $n % 2) == 0 )
// If $n is
even, make it odd
{
$n--;
}
whi l e ( $n > 0 )
{
$sum += $n ;
$n--;
}
return $sum ;
}
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:

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

with this one:


for ($i = (int) $_GET[number]; $i > 0; $i-- )
{
echo $i;
}
If you think they are equivalent (i.e. same outputs for the same inputs), state which one is more efficient and why it is
the more efficient. If you think they are not equivalent, how will their outputs differ?

Network Programming: unanswered review questions

Page 21/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 the
information to the database in Figure y. The password must be encoded using md5 function before being inserted to
the 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.

Network Programming: unanswered review questions

Page 22/23

Network Programming

Fall, 2014-2015

Question 33:
The following Figure is a table named BookInfo extracted from a database named Library.
Use the table to answer this question.

Figure 3: Table BookInfo


Let say a user would like to find a book on security but you do not know the complete title of the book. However he
remembers 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 of
the books title, the publisher and the year published. It also has a submit button. When the user key-in all the
information, 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 he BookInfo table. Include all fields appeared in the
above figure.

The END
Good Luck

Network Programming: unanswered review questions

Page 23/23

Vous aimerez peut-être aussi