PHP Test 2 Study Guide

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

15. What is the difference between a break statement in a loop and a continue statement?

The break and continue statements give you additional control over loops. The break statement causes the loop to end immediately. The continue statement causes the loop to skip the remaining code in the loop and start back at the beginning of the loop. When you're working with nested loops, the break and continue statements apply only to the loop that they're in.

10. Write example code for a conditional operator as explained in our textbook

The conditional operator begins by evaluating the conditional expression. Then, if the conditional expression is TRUE, the value that results from the middle expression is returned. Otherwise, the value that results from the last expression is returned.

4. In MVC pattern, what is the purpose of the controller (the "C")?

The controller consist of PHP files that receive HTTP requests from browsers, get the appropriate data from the model, and return the appropriate views to the browsers.

13. What is a do loop? Write example code for a do loop

The do-while loop is similar to the while loop except that the conditional expression is tested at the end of the loop. As a result, the code inside the loop is always executed at least once. The do-while statement executes the block of statements within its braces as long as its conditional expression is TRUE. $rolls = 0; do { $rolls++; } while (mt_rand(1, 6) != 6); // get a random number from 1 to 6 echo 'Number of times to roll a six: ' . $rolls;

12. How do you display data with the echo and print statements?

The echo and print statements send strings to the web page. Non-string values are converted to strings before they are sent to the web page. The echo statement can accept one or more string values, but the print statement can only accept one value. The echo statement doesn't return a value and cant be used as part of an expression; however the print statement returns a value of 1 so it can be used as part of an expression.

1. What is the goal of testing your code?

The goal of testing your code is to try every possible combination of input data and user actions in order to make an application fail. This will ensure that the application works in every case

14. What does the sprintf function do?

The sprintf function returns a string that contains one or more values that are formatted as specified by the $format parameter. You can use this function to code a single format string that formats multiple string and numeric values based on their corresponding format codes. sprintf($format, $val1[, val2 ...])

3. In MVC pattern, what is the purpose of the view (the "V")?

The view consists of the HTML and PHP files that represent the user interface of the application. As a general rule, the view files contain the HTML tags for the application with some embedded PHP tags that display the dynamic data that's returned from the database.

6. How do you call a custom function in PHP?

To call a function, you code the function name followed by a set of parentheses that contains the arguments that are required by the function. When you code these arguments, they must be in the same order as the parameters in the parameter list that's defined by the function, and they must have compatible data types. Examples: $products = get_products_by_category($category_id); add_product($category_id, $code, $name, $price);

12. How do you round a number in PHP?

To round a number in PHP, the round function must be used. round($value[, $precision]) Returns the value that results from rounding $value to the number of decimal points specified by $precision. If $precision is omitted, its default is 0. If $precision is negative, this method rounds to a whole number. For example, -1 rounds to the nearest ten and -2 rounds to the nearest hundred. $subtotal = 15.99; $tax_rate = 0.08; $tax = round($subtotal * $tax_rate, 2); // 1.28 instead of 1.2792

7. How do you replace one string with another string in PHP?

Use the str_ireplace function. str_ireplace($str1, $new, $str2) $message = 'Hello Ray'; $message = str_ireplace('hello', 'Hi', $message); // $message is 'Hi Ray'

• refactoring

modifying the organization or structure of an application

4. What are relational operators and why are they important to us in this class?

When you use relational operators, the operands are converted to the same types. When both operands are strings, they are compared character by character from the start of the strings based on the ASCII value of each character.

6. How do you code a solution to break a full name into first and last name strings? (HINT: substrings)

$name = 'Ray Harris'; $length = strlen($name); $first_name = substr($name, 0, 3); $last_name = substr($name, 4);

13. Write the PHP code to randomly generate a seven digit number.

$number = 0; $places = 7; // Number of decimal places for($i = 0; $i < $places; $++) { $number += mt_rand(0,9); // Add the random number } echo $number; // For example 1234567

4. What is a "radio button group"?

A group of options that are selectable by the user. Only one selection may be made from the group

• parameter list

a group of parameters that are specified within the parentheses of a function

8. What control do you use to create a list box and how does it work?

A list box works similarly to a drop-down list; however, you set the size attribute of the <select> tag to the number of options that you want displayed in the list box. A list box allows a user the select zero or more options from a group of options.

8. Explain how a nested if statement works

A nested if statement is an if-else statement with another if statement as the if body or the else body. It allows the programmer to move on to a certain set of instructions if the first if statement produces a certain result.

13. What is a "HTML character entity"?

An HTML character entity lets you display some special characters on a webpage. Ie. (&lt;) is the character entity for the less than sign (<).

5. How do you trace the execution of your PHP application?

An easy way to trace the execution of a PHP application is to insert echo statements at key points in the code. The echo statements can display the values of variables or display messages that indicate what portion of the code is being executed. When you see an incorrect value displayed, there is a good chance that you have a logic error between the current echo statement and the previous one.

7. Write an example custom function to add items to an inventory database.

function add_product($category_id, $code, $name, $price) { global $db; $query = 'INSERT INTO products (categoryID, productCode, productName, listPrice) VALUES (:category_id, :code, :name, :price)'; $statement = $db->prepare($query); $statement->bindValue(':category_id;, $category_id); $statement->bindValue(':code', $code); $statement->bindValue(':name', $name); $statement->bindValue(':price', $price); $statement->execute(); $statement->closeCursor(); }

5. Explain the syntax used to create a custom function in PHP.

function function_name([parameter_list]) { // statements that are executed by the function } When coding the name of the function, you must choose a unique name. Function name can't begin with a number and can only contain letters, numbers and underscores. Within the parentheses of a function, you can code an optional parameter list that contains one or more parameters which are separated by commas. If you want a function to return data, you can code a return statement within the body of the function. This statement ends the execution of the function and returns the specified value.

• type="radio"

selection tool that allows a user to select one option from a group of options

5. What is the syntax to test for the length of a string (like checking how long a password is)?

strlen($str) ie: $length = strlen($name);

3. Compare equality operators to identity operators

Equality operators perform type coercion. Identity operators do not perform type coercion. If the two operands are of different types, the result will always be false.

9. What function should you use to compare two strings?

$result = strnatcasecmp($name_1, $name_2); if ($result < 0) { echo $name_1 . ' before ' . $name_2; } else if ($result == 0) { echo $name_1 . ' matches ' . $name_2; } else { echo $name_1 . ' after ' $name_2; }

5. What are these operators? What do they have in common? ! || &&

1. ! - NOT: Returns the opposite Boolean value of its expression 2. || -- OR: Returns TRUE when the expression on either side or both sides is TRUE. 3. && -- AND: Returns TRUE only when the expressions on both sides are TRUE. The logical operators return a Boolean value based on the expression.

6. List the five orders of precedence for operators in conditional expressions and define them:

1. ! NOT 2. < , <= , > , >= , <> RELATIONAL OPERATORS 3. == , != , === , !== EQUALITY & IDENTIFIERS 4. && AND 5. || OR Parentheses have the highest order of precedence so the operations within parentheses are done first, working from the innermost sets of parentheses to the outermost sets.

10. What is 2,147,483,647 in PHP? What happens in PHP when an integer exceeds this value?

2,147,483,647 is the maximum positive integer that can be represented by PHP. PHP stores this value in the constant named PHP_INT_MAX. If an integer exceeds this value, PHP converts the value to a floating-point value.

7. What control do you use to create a drop down list and how does it work?

A drop down list is created by using the <select> and <option> tags. Since a drop-down list forces the user to select an option, a name/value pair for the drop-down list will always be submitted to the server

11. Explain what a floating-point value is?

A floating-point number is a numerical value that has a fractional component. Floating-point numbers are also known as floats, doubles or real number and they always use base 10.

14. What is a for loop? Write example code for a for loop

A for loop provides a convenient way to code a loop that requires a counter variable. The for statement is useful when you need to increment or decrement a counter that determines how many times the for loop is executed. Within the parentheses of a for statement, you code an expression that assigns a starting value to a counter variable, a conditional expression that determines when the loop ends, and an increment expression that indicates how the counter should be incremented or decremented each time through the loop. for ($count = 1; $count <= 10; $count++) { echo $count . '<br>'; } for ($number = 2; $number <= 10; $number +=2) { echo $number . '<br>'; }

7. Define what a selection structure is. Write the code to create a selection structure where X should equal 283; display if X in fact equals 283 or an error if it does not

A selection structure is when a question is asked, and depending on the answer, the program takes one of two courses of action, after which the program moves on to the next event. The switch statement and conditional operator are used in selection structures. If ($x == 283) echo 'X does equal 283.'; else echo 'Error: X does not equal 283.';

11. Explain what a switch statement is. Write an example switch statement with at least three case labels in it and a default label

A switch statement is a convenient way to express a certain form of if statement. Specifically, it can be used in place of an if statement with multiple else if clauses in which one expression is tested for equality with several values. It starts with the word SWITCH followed by a switch expression inside of parentheses. This expression is not a conditional expression. It is an expression that returns a single value that's used to determine which case to execute. The expression is often as simple as a single variable. But it can also be a more complex expression that results in a number or string value. Once the value for the expression is found, the switch statement checks each of the values in the case labels. Then, it begins executing the code that follows the first case label that is equal to the result of the expression. It continues executing until it reaches either a break statement or the end of the switch statement. If no case labels match the value in the switch expression, the switch statement start executing the code that follows the default label. switch ($letter_grade) { case 'A': $message = 'well above average'; break; case 'B': $message = 'above average'; break; case 'C': $message = 'average'; break; case 'D': $message = 'below average'; break; case 'F': $message = 'failing'; break; default: $message = 'invalid grade'; break; }

9. Describe the controls used to setup a text area in a form?

A text area let the user enter multiple lines of text. To create a text box, you use the <textarea> tag. To set the approx. size of the area, you can use the rows and cols attributes. To display default text in the text area, you can place the text between the opening and closing <textarea> tags.

12. What is a while loop? Write example code for a while loop

A while loop executes a block of code as long as its conditional expression is TRUE. If the conditional expression starts off as FALSE, the code isn't executed at all. When you use a while statement, the condition is tested before the while loop is executed. $total = 0; $count = 0; while ($count < 100) { $number = mt_rand(0, 100); $total += $number; $count ++; } $average = $total / $count; echo 'The average is: ' . $average;

1. What are conditional expressions?

Conditional expressions are expressions that use relational operators to compare the results

6. Briefly explain how to use check boxes to determine values in an array?

For each check box, it uses the isset function to return a Boolean value that indicates whether the name/value pair is set in the $_POST array. If the check box has been selected, it is set in the array. As a result, a True value is stored in the variable. Otherwise, a False value is stored in the variable.

2. What is the difference in a heredoc and a nowdoc?

Heredoc and nowdoc are both methods for defining strings Heredoc parses for variable interpolation whereas Nowdoc doesn't do the same. No parsing is done inside of a nowdoc

1. In Chapter 5, our textbook writers explain why we may want to learn MVC pattern to organize our PHP projects. Paraphrase in your own words what they said.

MVC stands for Model-View-Controller It is a programming pattern that was developed to aid in easing the difficulty of coding, testing, debugging and maintaining of large applications. It makes applications easier to code and maintain. It breaks the application down to three levels, the model, the view and the controller. When using the MVC pattern, you try to construct each layer so that it is as independent as possible. This allows you to make changes to one layer, without worrying about the changes affecting the other layers.

15. Define mantissa

Mantissa is defined as the part of a floating-point number that represents the significant digits of that number, and that is multiplied by the base raised to the exponent to give the actual value of the number.

1. What is the difference in assigning strings with single quotes versus double quotes?

Single quoted strings will display things almost completely "as is." Double quoted strings will allow the PHP engine to perform variable substitution. Variable substitution replaces the variable name in the string with its value. PHP engine will search the string for variables

3. What is escaping?

Some characters have special meaning to the SQL database you are using. When these characters are being used in a query they can cause unexpected and/or unintended behavior including allowing an attacker to compromise your database. To prevent these characters from affecting a query in this way they need to be escaped, or to say it a different way, the database needs to be told to not treat them as special characters in this query. Escape sequences provide a way to insert special characters into text strings. These escape sequences work differently depending on the type of the string

2. Which method would you suggest using for an authentication page, GET or POST, and why?

The POST method should be used for an authentication page. The GET method displays the data for controls in the URL. This is not secure. The POST method will allow for sensitive data to be transmitted without making it visible in the URL.

4. What does the htmlentities function do?

The htmlentities function returns a string with all special HTML characters converted to the HTML entity. You can use the $quotes parameter to control how single and double quotes are converted. This function parses a string and returns a new string with any special characters converted to the corresponding HTML entity.

10. What does the htmlspecialcharacters function do?

The htmlspecialcharacters function converts some special characters into character entities. This provides a way to display special characters and helps guard against XSS attacks.

5. What does the isset function do?

The isset function is used to check whether a variable is set or not. It will return a true or false value. If the variable is null, it will return a false.

16. Define type casting

The meaning of type casting is to use the value of a variable with different data types. In other words, type casting is a way to utilize one data type variable into a different data type.

2. In MVC pattern, what is the purpose of the model (the "M")?

The model consists of PHP files that represent the data of the application. As a general rule the model files don't contain any HTML.

11. What does the nl2br function do?

The nl2br function converts new line characters in a string to HTML <br> tags. This lets you display the line breaks on a web page.

2. What does type coercion mean?

Type coercion converts data from one type to another. If different types of data are being compared, the values are converted to the same data type before the comparison takes place

8. How do you convert a string in to an array?

Use the explode function to convert a string to an array. explode($sep, $str) $names = 'Mike|Anne|Joel|Ray'; $names = explode('|', $names); $name1 = $name[0]; // $name1 is 'Mike' $name2 = $name[1]; // $name2 is 'Anne'

3. What does the input_filter function do?

Use the filter_input function to get the values of an array and make sure they are safe

• parameter

a parameter or "argument" is a value that is passed into a function

• DRY (Don't Repeat Yourself) principal

a principle of software development aimed at reducing repetition of software patterns, replacing them with abstractions; and several copies of the same data, using data normalization to avoid redundancy

Runtime Error

a program error that occurs while the program is running

• type="checkbox"

a selection tool that allows a user to select an option; user can select more than one option

• Argument

a value or address passed to a procedure or function at the time of call

• Bug

an error, flaw, failure or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways

• value="something"

based on the input type, the input area receives a value by the user

• name="something"

based on the input type, the selection type receives a name

• type="text"

creates a text field; user can type in this field; input visible

• type="hidden"

creates a hidden field; not displayed on web page; programmers use hidden fields to pass data from one page to another

• type="password"

creates a password field; user can type, but input is obscured, to keep input private

• global keyword

declares global variable inside user-defined function. Global variable is the variable that is visible/accessible inside the function AND outside the function

8. Using the header function, write a PHP redirect request that will take a user to the https://beausanders.org/CPT283/index.php page.

header('Location: https://beausanders.org/CPT283/index.php');

9. Write example code for an if statement with several else if clauses and an else clause.

if ($average >= 89.5) { $grade = 'A'; } else if ($average >= 79.5) { $grade = 'B'; } else if ($average >= 69.5) { $grade = 'C'; } else if ($average >= 64.5) { $grade = 'D'; } else { $grade = 'F'; }

• return statement

terminates the execution of a function and returns control to the calling function; can also return a value to the calling function

Debug

the routine process of locating and removing computer program bugs, errors or abnormalities

• forward a request

when forwarding a request, all of the processing takes place on the server; after the request, the server forwards the request to another PHP file on the server, eventually returning a response to the browser; it usually runs faster than redirecting a request because it doesn't require a second trip to the server

• redirect a request

when redirecting a request, the server return a response that tells the browser to request another URL

2. What are the "Three Test Phases" discussed in Chapter 6?

• Check the user interface to make sure that it works correctly • Test the application with valid input data to make sure the results are correct. • Test the application with invalid data or unexpected user actions. Try everything you can think of to make the application fail.

4. Pages 194 and 195 lists common PHP errors. Create a bullet list of nine (9) of these errors we should be on the lookout for:

• Misspelling keywords • Forgetting an opening or closing parenthesis, bracket, brace, or comment character. • Forgetting to end a PHP statement with a semicolon. • Forgetting an opening or closing quotation mark. • Not using the same opening and closing quotation mark. • Misspelling or incorrectly capitalizing a variable name. • Using a keyword as a variable name. • Not checking that a value is the right data type before processing it. For example, you expect the user to enter a number, but the user enters a name instead. • Using one equal sign instead of two for testing equality

3. Chapter 6 describes the three types of errors that can occur when developing a PHP application. Describe the three types of errors

• Syntax errors violate the rules for how PHP statements must be written. These errors cause the PHP interpreter to display an error and to stop execution of the script. • Runtime errors don't violate the syntax rules, but they cause the PHP interpreter to display an error that may or may not stop execution of the script. • Logic errors are statements that don't cause syntax or runtime errors, but produce the wrong results.


Set pelajaran terkait

Georgia Drivers Ed Unit 1 Lesson 2: Signs, Signals, Markings and Intersections

View Set

Topic 2: HealthCare Information System

View Set

Unit 3 - Work Safety and Infection Control

View Set

Unit 8: DNA, RNA and Protein Synthesis

View Set

Ch 6: Elasticity Review Questions

View Set

Texas Law of Contracts - Chapter 2

View Set

Chapter 9 social class and sport

View Set