Download - Math 275 FINAL FALL 2012

Transcript
  • 7/25/2019 Math 275 FINAL FALL 2012

    1/19

    | P a g e

    Faculty Of Computer StudiesM275

    Web Development using PHP and MySQL

    Final Examination- SolutionFall 2012-2013

    Date Saturday January 12, 2013( 2.5) HoursTime Allowed:Number of Exam Pages: 19

    Instructions:

    This exam consists of 3 parts [ Total is 100 Marks ]

    1. Part A [Total marks available is 10] consists of a set of

    multiple choice questions all of which must be answered2. Part B [ Total marks available is 40 ] ; the student should

    .of them4answer any3. Part C Long Coding [Total marks available is 50 ] , The

    .questions2answerstudent should

  • 7/25/2019 Math 275 FINAL FALL 2012

    2/19

    2| P a g e

    PART A [ 10 Marks ] :

    Choose the correct answer [ 2 Mark for each question ] :

    1) _______ types are often returned by functions that deal with external applications or files.

    a. Resourceb. Datac. Nulld. None

    2) PHP provides the function _________ to change the type of a variable.a. gettype()b. settype()c. testtype()d. None.

    3) PHP has both a require() statement, which performs a similar function to ________a. include(), and a require_once() statement.

    b. include()

    c. include_once()d. None

    4) What will be the output from the following code fragment?$test_val = 5.5466;settype($test_val, integer);echo $test_val;

    a. 5.5b. 6

    c. 5d. 4

    5) The MySQL _______________ transform a string into lowercase or uppercase:a. LCASE() and UCASE() functionsb. CASEL() and CASEU() functionsc.

    LCASE()d.

    None

    Part B [ 40 Marks ] : Answer ONLY 4 questions [ 10 Marks for each ] :

    1) a. MySQL checks three things during the authentication process. The actions associated with these threethings are performed in two steps . Detail the two steps . [ 5 marks ]

    Answer :1. MySQL looks at the host you are connecting from and the username andpassword pair that you are using. If your host is allowed to connect, yourpassword is correct for your username, and the username matches oneassigned to the host, MySQL moves to the second step.2. For whichever SQL command you are attempting to use, MySQL verifiesthat you have the ability to perform that action for that database, table,and field.

  • 7/25/2019 Math 275 FINAL FALL 2012

    3/19

    3| P a g e

    b. From a Linux/Unix operating system, how would you get help on configuration options (the options that youpass to the configure script in your PHP distribution)? [5 marks ]

    Answers1. You can get help on configuration options by calling the configure script inthe PHP distribution folder and passing it the --help argument:./configurehelp

    2) Create a calculator script that enables the user to submit two numbers and choose an operation (addition,multiplication, division, or subtraction) to perform on them. [ 10 Marks]

    solution :

    a basic PHP calculator:

  • 7/25/2019 Math 275 FINAL FALL 2012

    4/19

    4| P a g e

    else

    {

    if($_POST[' compute '] == 'add')

    {

    $calc = ($_POST['value1']+$_POST['value2']);

    $op = '+';

    }

    if($_POST[' compute '] == 'subtract')

    {

    $calc = ($_POST['value1']-$_POST['value2']);

    $op = '-';

    }

    if($_POST[' compute '] == 'divide')

    {

    $calc = ($_POST['value1']/$_POST['value2']);

    $op = '/';

    }

    if($_POST[' compute '] == 'multiply')

    {

    $calc = ($_POST['value1']*$_POST['value2']);

    $op = '*';

    }

    echo $_POST['value1'].' '.$op.' '.$_POST['value2'].' = '.$calc;

    }

    ?

  • 7/25/2019 Math 275 FINAL FALL 2012

    5/19

    5| P a g e

    3) Write a PHP script that uses cookie session to create a page counter for a website . [ 10 marks] .

    Title

    4) Create a PHP function works out a 10 percent discount of the total payment by a customer . You onlywant to apply the discount if the customer spent over 100 Dollar if not, don't apply the discount. In bothcases, you want the function to return the answer to your questionWhat do I charge this customer? .Suppose the total payment is initiated to 120 dollar . [10 Marks]

    Answer :

  • 7/25/2019 Math 275 FINAL FALL 2012

    6/19

    6| P a g e

    ?>

    5) The following real-world organizationalchart of a department that has department ID and Name

    indicates a connection between this department and a number of employees . each employee has an ID , FirstName and last name to identify him/her [10 Marks]

    a. State the degree of Department- Employee relationship .b. Draw the table representation showing the degree of the relation and stating the normalization Form of it

    .

    :Solution

    In a one-to-many relationship, keys from one table appear multiple times in asecond normalization formrelated table

    6) a. State the four basic steps to create an Image in PHP . b. Write a PHP script to create an image of simple line graph with the label Sales given that hight andwidth = 200 . [ 10 Marks]Solution :

    1- Creating a canvas image on which to work

  • 7/25/2019 Math 275 FINAL FALL 2012

    7/19

    7| P a g e

    2- Drawing shapes or printing text on that canvas3- Outputting the final graphics

    4- Cleaning up resources .

    Part C : Long Coding Problems [ 50 Marks ] Answer 2 Questions :

    1) What You are going to do for this question is to accept a number from the user. That number willrepresent one of the following:

    The radius of a circle.

    The length of one side of a square.

    The length of one side of an equalateral triangle.The user will specify the number and what it represents and then you will use PHP to calculate the area of thatobject, return the value, and rewrite the form so the user can enter another number and calculate a differentresult [ 25 Marks]Hints :

    Create a form that allows the user to enter a value that is used to calculate the area of a basic geometricshape: a circle, a square, or an equalateral triangle.

    Include a set of radio buttons that allows them to determine which shape they want to calculate the areaof.

    Use PHP to accept the data from the form using a POST method.

    Use PHP to test for legal values.

    Use an if statement in PHP to test for legal values.

    Use a switch statement in PHP to determine which calculation is to be performed. Use PHP to calculate and report on the values.

    Solution :

    Step 1: Our Form

    First thing you can do to get started is open up homework two and save it as hw03.php or whatever you want tocall it. These directions assume the assignment is named hw03.php. The document should have four sections.

  • 7/25/2019 Math 275 FINAL FALL 2012

    8/19

    8| P a g e

    A heading that describes the document. A footer at the bottom containing your name and copyright info.

    A form to enter the information into. An output area to write the output to.

    How you organize these elements is up to you. However, you will make life much easier on yourself if you putthe output area before the form in the code. It means you will be able to do almost all your PHP work in a singlecoding block.

    Here is the code for a simple example of how the form can be put together. I will be working from this model inthe assignment.

    Enter a number here :

    This number is a:
    : the radius of a circle
    : the length of one side of a square
    : the length of one side of an equalateral triangle

    Hopefully, this form should be self-explanatory.

    The PHP Code

    The best way to write the code is to put our output section before our form. That way we can put most of ourPHP code in a single block. So above the form, put in your PHP block.

    Notice that the form has two submit buttons. One is marked "Calculate" and the other is marked "Clear". Thereason for this is that the button marked clear is actually a reset button. Since we will be using PHP to get theform field values to dynamically persist, a regular reset button will not work.

    If the user clicks "Calculate", it perform the calculation, and if they click "Clear" it will reset the form. Thus wewant to start of with a conditional that tests which direction to go with the form.

  • 7/25/2019 Math 275 FINAL FALL 2012

    9/19

    9| P a g e

    The first thing we want in the block is a test for which direction to go in. This test will form the primarystatement in the block. If fact, depending on how you write it, it is the only statement in the block, sinceeverything else is nested within it.

    So how do we test which button was clicked? Well, you will notice that both submit buttons are named "submit".Since pressing a submit button with a name and value will associate that value with the name and send it back tothe server, which just need to determine whether submit equals "Calculate" or "Clear".

    All the form fields submitted by was of the post method are stored by PHP in an array called$HTTP_POST_VARS. So what we have to do is test the value of $HTTP_POST_VARS['submit']. In newerversions of PHP, we can also use the short form of $_POST['submit']. We can test test for the "Clear" value first,since it is less code, then test for "Calculate".

    Let's start with clearing the form, since it is our first statement. How do we clear the form?

    To answer this requires thinking ahead a little. We need to set the value of our text form element to an emptystring, as well as unselect any radio buttons.

    We could work with our array elements directly, but it is good form to leave those as is and assign the values tonew variables internal to the script which are then written back to the form when we are done. So let us come upwith two variables, one for the text box and one for the two radio button group. Then we can set them to spaces.

    While we are at it, let's also set them for when the "Calculate" button is clicked. In that case we want to pass itthe values from the form fields in question, vfld gets written to $workValue and tfld gets written to $workType.

    if ($HTTP_POST_VARS['submit'] == "Clear") {$workValue = "";$workType = "";}

    elseif ($HTTP_POST_VARS['submit'] == "Calculate") {$workValue = $HTTP_POST_VARS['vfld'];$workType = $HTTP_POST_VARS['tfld'];}

    Getting Info to Persist

    Before we go any further, we should set up our form to allow for data persistence. This will make it easier to testthe code. To do that we want to assign a value to our text field if it already had one assigned before thesubmission and assign a checked attribute to whichever radio button the user selected.

  • 7/25/2019 Math 275 FINAL FALL 2012

    10/19

    1| P a g e

    In order for this to work as described, we have to have our PHP processing block before the form in the code,because we are using the variables we just created in the if statement above.

    For our text field, this is easy. We just echo workValue as a value to the value attribute of the form field.

    Enter a number here : />: the radius of a circle
    />: the length of one side of a square
    />: the length of one side of an equalateral triangle

    Pay careful attention to how the PHP is nested inside the HTML and how the HTML is nested inside the PHP inthese examples. It may look like a complicated mess, but it works, and it is how it is supposed to work.

    With this much done, you have a program that doesn't actually do anything, but if you save it and test it, theinformation should persist when you enter information in the fields and click "Calculate" and clicking "Clear"should clear the form.

    Error Messages

    Next step is to add the error messages. That way you can keep testing as you go along.

    First we want to test whether we have been given a number to work with. The number must have threeproperties:

    It must exist. Which is to say, the user has to enter a value.

    It must be a numberic value. Thus "four" is not a valid value, but "4" is.

    It must be a positive value. Although not technically required, we will include it.

  • 7/25/2019 Math 275 FINAL FALL 2012

    11/19

    | P a g e

    Now, everything comes out of the form fields as strings. So we first want to convert our number to a numericdata type. Since measurements don't always come in whole numbers, we want to use floating point. So first wewant to cast our number as a floating point number. We can do this with our other assignments. Let's call ourvalue for testing and calculation $calcValue. We can use the (float) cast operator to cast it as a floating pointnumber from $workValue to our new variable.

    elseif ($HTTP_POST_VARS['submit'] == "Calculate") {$workValue = $HTTP_POST_VARS['vfld'];$workType = $HTTP_POST_VARS['tfld'];$calcValue = (float) $workValue;}

    Then we want to begin our tests. Our first test is for existence. Best place to test this is with the vfld value in the$HTTP_POST_VARS array. PHP has a function called empty() that returns true if a given variable has no value.Thus we can say that if our field value is empty, generate an error. We will use an echo statement to write theerror directly to the screen.

    elseif ($HTTP_POST_VARS['submit'] == "Calculate") {

    $workValue = $HTTP_POST_VARS['vfld'];$workType = $HTTP_POST_VARS['tfld'];$calcValue = (float) $workValue;if (empty($HTTP_POST_VARS['vfld'])) {echo "Error";echo "

    You must enter a value!

    \n";}

    }

    Now we need to test for valid, positive numbers. We can test for whether a number is value by checking itsvalue. If something is cast to a floating point number that is not a valid number it will cast to a value of 0 (zero).Since we can't really do anything with zero for calculating our values, we will assume zero means an invalid

    value. We can also test for negative numbers by seeing whether our floating point numer is less than zero.

    We also have to test for whether the user has selected a calculation type. We can do this by checking the value of$workType, which is what we assigned the value to, or checking the $HTTP_POST_VARS array for its tfldvalue. Let's check the array for this with the empty() function.

    That expands our if statement as follows.

    elseif ($HTTP_POST_VARS['submit'] == "Calculate") {$workValue = $HTTP_POST_VARS['vfld'];$workType = $HTTP_POST_VARS['tfld'];$calcValue = (float) $workValue;

    if (empty($HTTP_POST_VARS['vfld'])) {echo "Error";echo "

    You must enter a value!

    \n";}

    elseif ($calcValue == 0) {// error message goes here}

    elseif ($calcValue < 0) {// error message goes here

  • 7/25/2019 Math 275 FINAL FALL 2012

    12/19

    2| P a g e

    }elseif (empty($HTTP_POST_VARS['tfld'])) {// error message goes here}

    }

    I'll leave it to you to add your own error messages here.

    Generating the Output

    Yes, we are finally there. Generating the output. Believe it or not, this entire assignment, including the HTMLcode, will only be about 100 lines when you finish it. There is just a fair amount of description going on here.

    In order to generate the output you need to add one last else to our if structure. The last else says, in essence, ifnone of the errors conditions came up, then do the following. Within that else you are going to put the switchstatement I asked you to use to calculate the output. That means that our complete if structure looks like this:

    elseif ($HTTP_POST_VARS['submit'] == "Calculate") {

    $workValue = $HTTP_POST_VARS['vfld'];$workType = $HTTP_POST_VARS['tfld'];$calcValue = (float) $workValue;if (empty($HTTP_POST_VARS['vfld'])) {echo "Error";echo "

    You must enter a value!

    \n";} elseif ($calcValue == 0) {// error message goes here}

    elseif ($calcValue < 0) {// error message goes here

    }

    elseif (empty($HTTP_POST_VARS['tfld'])) {// error message goes here}

    else {// put switch statement here

    }

    We need to test whether the user wants a circle, square or triangle. Since we have created a set of radio buttonsnamed tfld that can have the value of circle, square, or triangle depending in which was selected, all we have todo is check what value was returned. We have already stored our tfld value in a variable called $workTypeabove. We can use that in the switch statement.

    Since a switch statement is made up of a switch expression to be tested and case expressions which represent thepossible values for the switch expression, we also need case expressions that have circle, square, and triangle forlabels.

    else {switch ($workType) {case "circle":// calculate and write out circlebreak;

  • 7/25/2019 Math 275 FINAL FALL 2012

    13/19

    3| P a g e

    case "square":// calculate and write out squarebreak;case "triangle":// calculate and write out trianglebreak;}

    }

    In order to perform our calculation, we need to know the equations. They are as follows:

    Area of a CircleThe user is supposed to supple you with a value equal to the length of the radius. The equation tocompute the area of a circle from the radius isarea = radius * radius * PI.Since our input value is now stored in $calcValue and since PHP has a function called pi() whose solepurpose is to return the value of PI, we can change our equation to$areaValue = $calcValue * $calcValue * pi();

    Area of a SquareFor a square, the user is supposed to provide the length of a side of a square. Since a square is a rectangleall of whose sides are the same, and since a rectangle's area can be determined by multiplying the heightof the rectangle by the width of the rectangle, we can get our area by simply multiplying the value theuser has given us by itself, giving us:$areaValue = $calcValue * $calcValue;

    Area of a Equalateral TriangleAn equalateral triangle is one whose sides are all the same length. Thus if we have the length of one side,we have the length of all three sides. The way you calculate the area of an equalateral triangle is bycutting it down the middle so you can put the two long sides together as the diagonals in a rectangle.

    Since we know two side of the new half triangles (the cut side is half as long as the original long side, wecan figure out the length of the third side and use that value to calculate the area of the triangle bymultiplying it by the half side (just like a rectangle of those dimensions). In other words, the area is equalto the height times one half the base. The equation for this is a little more involved since we need to usePythagoras' theorem and the sqrt() function to get the height of the triangle, which is the distance fromthe base to the point if you cut it up the middle.$areaValue = ($calcCalue / 2) * sqrt($calcValue*$calcValue) - (($calcCalue / 2)*($calcCalue / 2));We can make life easier by doing this in steps:$halfSide = $calcValue/2;

    $otherSide = sqrt(($calcValue*$calcValue) - ($halfSide*$halfSide));$areaValue = $otherSide * $halfSide;

    Since the triangle is the hardest one, let me show you how it works, then you can set up the other two cases forthe circle and the square.

    switch ($workType) {case "circle":

    // calculate and write out circle

  • 7/25/2019 Math 275 FINAL FALL 2012

    14/19

    4| P a g e

    break;case "square":

    // calculate and write out squarebreak;

    case "triangle":$halfSide = $calcValue/2;$otherSide = sqrt(($calcValue*$calcValue) -

    ($halfSide*$halfSide));$areaValue = $otherSide * $halfSide;echo "The area of an equalateral triangle whose

    sides are {$calcValue} is {$areaValue}.";break;

    2)Design a process for a simple discussion forum using PHP & MySQL which includes developing thedatabase tables, user input forms, and display of the results. The design specification should be as follows :

    a. Designing the database tables :forum_topics( topic_id int auto_increment, topic_title varchar (150), topic_create_time datetime,topic_owner varchar (150))forum_posts(post_id int not null primary key auto_increment, topic_id int not null, post_text text,post_create_time datetime, post_owner varchar (150)

    solution :mysql> create table forum_topics (-> topic_id int not null primary key auto_increment,-> topic_title varchar (150),-> topic_create_time datetime,-> topic_owner varchar (150)-> );

    mysql> create table forum_posts (-> post_id int not null primary key auto_increment,-> topic_id int not null,-> post_text text,-> post_create_time datetime,-> post_owner varchar (150)-> );

    b. Create the form shown in the following figure for a new topic creation, which includes a space for the firstpost in the topic with the following specification :

  • 7/25/2019 Math 275 FINAL FALL 2012

    15/19

    5| P a g e

    i.Create the entry in the forum_topics table, you use the topic_title and topic_owner fields from the input form.The topic_id and topic_create_time fields will be filled in automatically. Similarly, in the forum_posts table, youuse the post_text and topic_owner fields from the input form, and the post_id, post_create_time, and the topic_idfields will be filled in automatically. Because you need a value for the topic_id field to be able to complete theentry in the forum_posts table, you know that query must happen after the query to insert the record in theforum_topics table.ii.Define mysql_insert_id() function that retrieves the primary key ID of the last record inserted into thedatabase by this script which will become the entry for the topic_id field in the forum_posts table. Create andinsert the second query, again using a mixture of information known and supplied by the system.iii. Creates a message for the user as it is shown above ..

    Solution :2: 3: Add a Topic4: 5: 6: Add a Topic7: 8:

    Your E-Mail Address:
    9: 10:

    Topic Title:
    11:

    12:

    Post Text:
    13: 14:

    15: 16: 17:
  • 7/25/2019 Math 275 FINAL FALL 2012

    16/19

    6| P a g e

    1:

    30: 31: 32: New Topic Added33: 34: 35: New Topic Added36: 37: 38:

    3) Suppose you have a system in place that allows employees to enter hours spent on particular tasks, on certaindates, for a given company. Each Employee has ID e_id tinyint auto_increment , firt name e_fname

    varchar(50) , and a last name e_lname varchar(50) should be insterted in his profile once hired . Client tableshould have two fields , ID c_id tinyint auto_increment, and client name c_name varchar(255) , suchinformation are important for the record . The Task table has task_id tinyint , task_name varchar(50), andtask_fee float(4,2) with 0.00 default value. Finally, in the billable_hours table, you have the individual entries.Note that all entries in the billable_hours table use the appropriate ID fields of the employee, client, and taskstables in order to relate back to the master record for each. The field are bh_id int auto_increment, work_date,e_id , c_id , task_id , billable_time float(4,2) default 0.00.

  • 7/25/2019 Math 275 FINAL FALL 2012

    17/19

    7| P a g e

    a. Create the systems tables as described above showing the relation n between if there any.

    Solution :CREATE TABLE tasks (task_id tinyint PRIMARY KEY NOT NULL auto_increment,task_name varchar(50) NOT NULL default ,task_fee float(4,2) NOT NULL default 0.00);

    In the employees table, the names of employees are stored:CREATE TABLE employees (e_id tinyint PRIMARY KEY NOT NULL auto_increment,e_fname varchar(50) NOT NULL default ,e_lname varchar(50) NOT NULL default );

    In the clients table, the names of clients are stored:CREATE TABLE clients (

    c_id tinyint PRIMARY KEY NOT NULL auto_increment,c_name varchar(255) NOT NULL default );

    Finally, in the billable_hours table, you have the individual entries. Note that all entries in the billable_hourstable use the appropriate ID fields of the employee, client, and tasks tables in order to relate back to the masterrecord for each.

    CREATE TABLE billable_hours (bh_id int PRIMARY KEY NOT NULL auto_increment,work_date date,e_id tinyint,

    c_id tinyint,task_id tinyint,billable_time float(4,2) NOT NULL default 0.00);

    b.Suppose the following data insertion statements :

    INSERT INTO tasks VALUES (1, Programming, 150.00);INSERT INTO tasks VALUES (2, Database Design, 200.00);INSERT INTO tasks VALUES (3, Project Management, 150.00);INSERT INTO tasks VALUES (4, Data Entry, 75.00);

    INSERT INTO tasks VALUES (5, Graphic Design, 150.00);

    INSERT INTO employees VALUES (1, John, Doe);INSERT INTO employees VALUES (2, Jane, Doe);INSERT INTO employees VALUES (3, Michael, Smith);INSERT INTO employees VALUES (4, Ralph, Jones);

  • 7/25/2019 Math 275 FINAL FALL 2012

    18/19

    8| P a g e

    INSERT INTO clients VALUES (1, ABC Company);INSERT INTO clients VALUES (2, XYZ Company);INSERT INTO clients VALUES (3, Acme Telesystems);INSERT INTO clients VALUES (4, GoNutz Inc.);

    INSERT INTO billable_hours VALUES (, 2003-08-25, 1, 3, 2, 1.75);INSERT INTO billable_hours VALUES (, 2003-08-25, 1, 3, 1, 3.50);INSERT INTO billable_hours VALUES (, 2003-08-25, 2, 1, 3, 4.25);INSERT INTO billable_hours VALUES (, 2003-08-26, 2, 1, 4, 7.25);INSERT INTO billable_hours VALUES (, 2003-08-26, 2, 2, 1, 3.50);INSERT INTO billable_hours VALUES (, 2003-08-26, 3, 3, 1, 4.00);INSERT INTO billable_hours VALUES (, 2003-09-01, 3, 4, 2, 6.75);INSERT INTO billable_hours VALUES (, 2003-09-01, 3, 4, 2, 4.25);INSERT INTO billable_hours VALUES (, 2003-09-01, 4, 3, 3, 5.00);INSERT INTO billable_hours VALUES (, 2003-09-05, 4, 1, 3, 4.50);

    1-Write a subquesry that lists distinct tasks performed by any employee, Acme Telesystems . State out theresult of this subquesry .

    mysql> select distinct t.task_name as theTasks-> from billable_hours as bh-> left join tasks as t on t.task_id = bh.task_id-> where bh.c_id = (select c_id from clients where c_name = AcmeTelesystems);

    +--------------------+| theTasks |

    +--------------------+| Database Design || Programming || Project Management |+--------------------+

    2-Write a subquesry to view work done by Michael Smith for GoNutz Inc.:Solution

    mysql> select t.task_name as theTask,-> bh.billable_time * t.task_fee as theTotal-> from billable_hours as bh

    -> left join tasks as t on t.task_id = bh.task_id-> where-> (-> (bh.c_id = (select c_id from clients where c_name = GoNutz Inc.))-> and-> (bh.e_id = (select e_id from employees where (e_fname = Michael ande_lname = Smith)))->);

  • 7/25/2019 Math 275 FINAL FALL 2012

    19/19

    9| P a g e

    +-----------------+---------+| theTasks |theTotal |+-----------------+---------+| Database Design |1350.00 || Database Design |850.00 |+-----------------+---------+